var whentotakearray = [];
var frequencyarray = [];
$(document).ready(function () {
    Hideshow();
    mobileapp();
    //$('#FO_app_list_table').hide();
    debugger;
    LoadBranchForSearchPopUp()
    if ($('#hiddenRole_id').val() == 1) {
        $('#div_SummaryDetails').hide();
        $('#divConsultation').hide();       
    }
    else {
        $('#div_SummaryDetails').show();
        $('#divConsultation').show();
    }


    if ($('#UM_3').css('display') != 'none') {

        $('#SelDoctor_div').hide();
        $('#SelBranch_div').hide();
        dashboardcount();
    }
    debugger;

    if ($('#UM_2').css('display') != 'none' || $('#UM_4').css('display') != 'none') {
        $('#SelDoctor_div').show();
        $('#SelBranch_div').show();
        $('#myschedule').hide();

        if ($('#hiddenRole_id').val() != 1) {
            appointment_summary();
            healthcare();
            // healthcareall();
            unifiedFunction();

        }
    }
    if ($('#UM_5').css('display') != 'none') {

        $('#SelDoctor_div').hide();
        $('#SelBranch_div').hide();
        $('#myschedule').show();

        LoadAppointmentRequest();
    }
    //if ($('#hiddenRole_id').val() == 4 || $('#hiddenRole_id').val() == 6) {
    //    $('#SelDoctor_div').hide();
    //    $('#six_count_box').hide();
    //    $('#data_table_appointment,#my_schedule_div').hide();
    //    $('.app-details-hme').hide();
    //    $('#FO_table').hide();
    //}
    //if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
    //    if ($('#hiddenRole_id').val() == 2) {
    //        $('#SelDoctor_div').show();
    //        $('#six_count_box').hide();
    //        $('#data_table_appointment,#my_schedule_div').hide();
    //        appointment_summary();
    //        $('#FO_six_count_box').show();
    //    }
    //    else if ($('#hiddenRole_id').val() == 3) {
    //        $('#SelDoctor_div').show();
    //        $('#six_count_box').hide();
    //        $('#data_table_appointment,#my_schedule_div').hide();
    //        appointment_summary();
    //    }
    //}
    //else {
    //        $('#SelDoctor_div').hide();
    //        dashboardcount();
    //        LoadAppointmentRequest();
    //}
    $('#vitalclk').click(function () {
        $('#btnquickentryv').show();
        $('#btnquickentryl').hide();
    });
    $('#labclk').click(function () {
        $('#btnquickentryv').hide();
        $('#btnquickentryl').show();
    });
    $('#quickentry').on('shown.bs.modal', function (e) {
        $("#quickentry select").val($("#quickentry select option:first").val());
    })

    //Added by Antony
    if ($('#hiddenRole_id').val() == 1) {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
    else {
        $('#SelBranch_div').show()
        $('#SelDoctor_div').show()
        //   $('#FO_app_list_table').hide()
        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }

    LoadReferredPatientsList()
    debugger;

    if ($('#hiddenRole_id').val() == 1) {
        $('#review_visit_tab').hide();
        $('#healthcareprofessional_tab_list').hide();

    }
    else {
        $('#review_visit_tab').show();
    }
    $('#div_languagecordinator').hide();
    $('#div_painscore').hide();
    $('#div_special_details').hide();
    $('#div_Allergies').hide();  
});

function LoadBranchForSearchPopUp() {
    debugger;
    $('#SelBranchSearchPopup').empty();
    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);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    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 (data1.Table.length == 1) {

                        $('#SelBranchSearchPopup').append(SubDepartment);
                    }
                    else {
                        $('#SelBranchSearchPopup').append(default_opt + SubDepartment);
                    }
                    debugger;
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranchSearchPopup').val($('#HospitalBranchID').val());
                        $('#SelBranchSearchPopup').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}


function appointment_summary() {
    debugger;
    var DoctorId = $('#HiddenDoctorID').val();
    var branchid = ($('#HospitalBranchID').val() == '' ? 0 : $('#HospitalBranchID').val());
    $('#FO_app_list_table tbody').empty();
    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    }
    else {
        btndisable = 'style="display:none";';
    }
    var DoctorData = {
        Dml_Indicator: "A",
        doctor_id: DoctorId,
        product_code: $('#HProductCode').val(),
        hospital_id: $('#HospitalId').val(),
        branch_id: branchid,
        //AppointmentDate: date,
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Dashboard_appointment_count',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject(data1.data)) {
                // If no data, load appointments
                LoadAppointmentRequest($('#HiddenDoctorID').val());
            } else {
                // If data available, build table
                console.log(data1);
                if (data1.msg == "Success") {

                    var tr = '',
                        i;                    
                    var a = data1.data.data1;

                    if (a.length > 0) {
                        for (i = 0; i < a.length; i++) {
                            tr = tr + '<tr class="view">' +
                                "<td class='tb_name opensub'>" + a[i].DoctorName + "</td>" +
                                "<td class='opensub'>" + "Doctor"+ "</td>" +
                                "<td class='opensub'>" + (a[i].Booked + a[i].visited) + "</td>" +
                                "<td class='opensub'>" + a[i].visited + "</td>" +
                                "<td class='opensub'>" + a[i].Booked + "</td>" +
                                "<td class='opensub'>" + a[i].video_call + "</td>" +
                                "<td class='opensub'>" + a[i].Prescribed + "</td>" +
                                '<td class="opensub">' +
                                '<div class="icon-toggle opensub" onclick=\'view_specificappointment_details(\"' + a[i].doctor_id + '\",\"' + a[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';>' +
                                '<i class="fa fa-angle-down" aria-hidden="true"></i>' +
                                '</div>' +
                                '<div class="icon-toggle opensub bind-table-icon" onclick=\'view_revisit_list(\"newapprow_' + (i + 1) + '\",this);\'> ' +
                                '<i class="fa fa-table" aria-hidden="true"></i>' + 
                                '</div>' +
                                '<div class="icon-toggle opensub bind-table-icon" onclick=\'view_review_list(\"newapprow_' + (i + 1) + '\",this);\'>' +
                                '<i class="fa fa-user" aria-hidden="true"></i>' +
                                '</div>' +
                                '</td></tr>' +
                                '<tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>'

                                //'<td class="opensub" onclick=\'view_specificappointment_details(\"' + a[i].doctor_id + '\",\"' + a[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr><tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>'
                               

                            
                        }

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

                        $('#FO_app_list_table tbody').append(tr);

                        //added by nandhini for new design 05/06/2024
                        $(".fold-table tr.view .opensub").on("click", function () {
                            $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
                        });

                       
                       
                    } else {
                        LoadAppointmentRequest($('#HiddenDoctorID').val());
                    }                   
                   
                   
                } else {
                    console.log(data1);
                }
            }
            LoadBranch();
        }
    });
}
function view_review_list(rowid, e) {
    debugger;
    $('#' + rowid + ' td').empty();
    $('#' + rowid + ' td').append(LoadReviewAppointmentListnew(rowid));
}

function LoadReviewAppointmentListnew(row_id) {
    debugger;
    var div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');

    div.removeClass('loading');

    var table = $('<table class="table table-condensed body-borderless table_borderless" id="tblReferredPatientsList">');
    var thead = $('<thead><tr><th class="hidden"></th><th>S. No</th><th>Patient Name</th><th>Referred Date</th><th>Referred By</th><th>Referred To</th><th>Visit type</th><th>Status</th><th>Actions</th></tr></thead>');
    var tbody = $('<tbody>');
    table.append(thead).append(tbody);
    div.append(table);

    var date = '';
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    if ($('#SelDoctor').val() != 0 && $('#SelDoctor').val() != null) {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
    }

    $('#tblReferredPatientsList tbody').addClass('us-db-loader-appointments');
    var indicator;
    var indicator_id = 'S';
    if (indicator != '' && indicator != undefined) {
        indicator_id = indicator;
    }

    var doctor_id = $('#referal_SelDoctor').val();
    var ref_to_doctor_id = $('#referal_to_SelDoctor').val();
    var referal_branchid = $('#referal_SelBranch').val();
    var hidden_doctor_id = $('#hiddenRole_id').val() != 1 ? doctor_id : $('#myHiddenVar').val();

    var Performers = {
        doctor_id: hidden_doctor_id,
        referred_to_doctor_id: ref_to_doctor_id,
        referred_date: date,
        Dml_Indicator: indicator_id,
        branch_id: referal_branchid
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Doctor_Referral_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (response) {
            debugger;
            var data = JSON.parse(response);
            if (data.msg == "Success") {
                var rows = data.data.Table;
                if ($.isEmptyObject(rows)) {
                    var tr1 = '<tr><td colspan="9"><div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img"><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    $('#tblReferredPatientsList tbody').append(tr1);
                } else {
                    var tr = "";
                    for (var i = 0; i < rows.length; i++) {
                        var appointment_status = rows[i].referal_id_count > 0 ?
                            '<span class="label label-success" style="border-radius: 9px;background: white;color: green;">Booked</span>' :
                            '<span class="label label-danger">Not Booked Yet</span>';

                        var btnaction = '-';
                        if (rows[i].visit_typeid == 1 && rows[i].referal_id_count == 0 && $('#hiddenRole_id').val() != 1) {
                            btnaction = '<a class="btn btn-xs label-used" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + rows[i].patient_id + '&PName=\'' + rows[i].patient_name + '\'&Did=' + rows[i].referred_to_doctor_id + '&appdate=' + rows[i].next_appointment_date + '&BId=' + rows[i].branch_id + '&Refered_to_doctorid=' + rows[i].referred_by_doctorid + '&referal_id=' + rows[i].doctor_referral_id + '">Book an Appointment</a>';
                        }

                        tr += '<tr class="db-table-bg-heading">' +
                            '<td>' + (i + 1) + '</td>' +
                            '<td><span class="patientname">' + rows[i].patient_name + '</span><span class="ml-5">|</span><span class="patientid ml-5">' + rows[i].patient_id + '</span></td>' +
                            '<td>' + rows[i].referred_date_time + '</td>' +
                            '<td style="display:none;">' + rows[i].doctor_name + '</td>' +
                            '<td>' + rows[i].referred_by + '</td>' +
                            '<td>' + rows[i].referred_to_doctor + '</td>' +
                            '<td>' + rows[i].visit_type + '</td>' +
                            '<td>' + appointment_status + '</td>' +
                            '<td><div class="col-md-12 padding0"><div class="">' + btnaction + '</div></div></td>' +
                            '</tr>';
                    }
                    $('#tblReferredPatientsList tbody').append(tr);
                }
                $('#tblReferredPatientsList tbody').removeClass('us-db-loader-appointments');
                if ($.fn.DataTable.isDataTable('#tblReferredPatientsList')) {
                    $('#tblReferredPatientsList').DataTable().clear().destroy();
                }
                $('#tblReferredPatientsList').DataTable();
            } else {
                console.log(data);
            }
        }
    });

    return div;
}

function view_revisit_list(rowid, e) {
    debugger;
    $('#' + rowid + ' td').empty();
    $('#' + rowid + ' td').append(LoadReferredPatientsListnew(rowid));
}

function LoadReferredPatientsListnew(row_id) {
    debugger;
    var div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');

    div.removeClass('loading');

    var table = $('<table class="table table-condensed body-borderless table_borderless">');
    var thead = $('<thead><tr><th class="hidden"></th><th>S. No</th><th>Patient Name</th><th>Last Visited Date </th><th>Doctor Name </th><th>Status</th><th>Actions</th></tr></thead>');
    var tbody = $('<tbody>');

    table.append(thead).append(tbody);
    div.append(table);

    var date = '';
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {
        // Do nothing
    } else {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
    }

    var Performers = {
        doctor_id: DoctorId,
        AppointmentDate: date,
        User_role: role_id,
        Dml_Indicator: "RS",
        branch_id: $('#SelBranch').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                tbody.empty(); // Clear the tbody before adding new rows
                if (jQuery.isEmptyObject((data))) {
                    var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img"><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    tbody.append(tr1);
                } else {
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            $('#Hidden_doctor_id').val(data[i].doctor_id);
                            $('#Hidden_next_appointment_date').val(data[i].next_appointment_date);
                            $('#Hidden_appointment_id').val(data[i].appointment_id);

                            var appointment_status = "";
                            var btnaction = '-';

                            if (data[i].appointment_id != null && data[i].appointment_id != "") {
                                appointment_status = '<span class="label label-success" style="border-radius: 9px;background: white;color: green;">Booked</span>';
                            } else {
                                appointment_status = '<span class="label label-danger">Not Booked Yet</span>';
                                btnaction = '<a class="btn btn-xs label-used" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + data[i].patient_id + '&PName=\'' + data[i].patient_first_name + '\'&Did=' + data[i].doctor_id + '&appdate=' + data[i].next_appointment_date + '&BId=' + $('#SelBranch').val() + '">Book an Appointment</a>'
                                    + '<br /><button class="btn btn-xs edit_label mt10" data-toggle="modal" data-target="#change-review-date" onclick=\'PatientReviewDetails(\"' + data[i].patient_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].next_appointment_date + '\")\'>Change Review Date</button></td>';
                            }

                            var case_form = ''
                            if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>';
                            } else {
                                case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>';
                            }
                            var tr = '<tr class="db-table-bg-heading"><td>' + (i + 1) + '</td><td>' + case_form + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span></td>'
                                + '<td>' + data[i].last_visit_date + '</td><td>' + data[i].doctor_name + '</td><td>' + appointment_status + '</td>'
                                + '<td><div class="col-md-12 padding0"><div class="">' + btnaction + '</tr>';
                            tbody.append(tr);
                        }
                    }
                }
            } else {
                console.log(data);
            }
        }
    });

    return div; // Return the div containing the table
}

//added by nandhini for new design 05/06/2024
function view_specificappointment_details(doctor_id,user_id,rowid, e) {
    debugger;
    $('#' + rowid + ' td').empty();
    $('#' + rowid + ' td').append(LoadAppointmentRequestNew(doctor_id, user_id, rowid));

}
//added by nandhini for new design 05/06/2024
function LoadAppointmentRequestNew(doctor_id,user_id,row_id) {
    debugger;
    div = $('<div/>')
    .addClass('loading')
    .addClass('table_child')
    .addClass('table-responsive');


    div.removeClass('loading');
    var tr, row_data='';
    tr = $('<table class="table table-condensed body-borderless table_borderless">');
    tr.append('<thead><tr><th class="hidden"></th><th>Token No</th><th>Appt.Time</th><th>Branch Name</th><th>Patient Details</th><th>Appt Details</th><th>Doctor Name</th><th>Referred Doctor</th><th>Actions</th></tr></thead><tbody>');
   

    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    }
    else {
        btndisable = 'style="display:none";';
    }
    var DoctorId = ($('#hiddenRole_id').val() == 1) ? $('#myHiddenVar').val() : doctor_id;
    var role_id = $('#hiddenRole_id').val();
    
    var Performers = {
        doctor_id: DoctorId,
        AppointmentDate: date,
        User_role: role_id,
        Dml_Indicator: "AS",
        branch_id: ""
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                    //$('#data_table_appointment tbody').empty();

                    //var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    //$('#data_table_appointment tbody').append(tr1);
                    ////$('#data_table_appointment tbody').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');               
                    //$('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                }
                else {
                    console.log(data);

                    var  mtr = '', vtr = '', vdtr = '';
                    if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {



                            var patient_photo = data[i].patient_photo;
                            $('#lab_id').val(data[0].lab_id);
                            $('#lab_data_flag').val(data[0].data_flag);
                            var WaitingTime = 0;
                            if (data[i].check_status > 1) {
                                var checkin_timeminutes = (data[i].checkin_timeminutes);
                                var checkout_timeminutes = (data[i].checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (data[i].check_status == null || data[i].check_status == '') {
                                WaitingTime = '-';
                            }
                            else {
                                var checkin_timeminutes = data[i].checkin_timeminutes;
                                var CurrentTime = data[i].CurrentTime;
                                WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")
                                var WaitingTimes = WaitingTime.split(':');
                                WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                            }
                            var EngagedTime = data[i].enage_time;
                            if (EngagedTime == null || EngagedTime == '') {
                                EngagedTime = '-';
                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';
                            }
                            var photo = '';
                            var delivery = '-';
                            var photoSrc;
                            var PatientPhoto = $('#patphotop').val();
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            var color = '';
                            if ((data[i].doctor_appointment_slot_status == 1 || data[i].doctor_appointment_slot_status == 7) && data[i].pcheckin_timeminutes == null) {
                                color = '';
                            }
                            else {
                                //color = '<i class="fa fa-check-circle above_average" aria-hidden="true"></i>';
                                color = '<small class="label label-success">Completed</small>'
                            }
                            var checkin = '';
                            var Engage = '';
                            var MEngage_1 = '';
                            var MEngage_2 = '';
                            var Decline = '';
                            var noshow = '', balance = '', labtest = '', bal = '-', smslink = '-', reschedule = '';
                            var P_status = ''; var EngageStatus = '', disablebtn = '', previousDue = '';;

                            if (data[i].Status == 1) {
                                P_status = '<a><span class="label label-success">PAID</span></a>'
                            }
                            else if (data[i].Status == 2) {
                                P_status = '<a><span class="label label-warning">PARTIAL</span></a>'
                            }
                            else if (data[i].Status == 5) {
                                P_status = '<a><span class="label label-danger">PENDING</span></a>'
                            }
                            else if (data[i].Status == 3) {
                                P_status = '<a><span class="label label-danger">Due</span></a>'
                            }
                            if (parseFloat(data[i].previousDue) > 0 && data[i].IsApproved != 1) {
                                disablebtn = 'disabled'
                                previousDue = '<a><span class="label label-danger"> Previous Due : ' + data[i].previousDue + '</span></a>'

                            }
                            if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                EngageStatus = P_status;
                            }

                            var bill = '', color1 = '', duebillno = '', edit_bill = '';
                            if (data[i].billno != null) {
                                var s1 = data[i].billno.split(',');

                                for (var p = 0; p < s1.length; p++) {
                                    var amount = '';
                                    var s2 = s1[p].split('/');
                                    if (parseFloat($.trim(s2[2])) > 0) {
                                        color1 = 'red';
                                        amount = $.trim(s2[2]);
                                        if (duebillno == '') {
                                            duebillno = $.trim(s2[0]);
                                        }
                                    }
                                    else {
                                        color1 = 'green'
                                        amount = $.trim(s2[1]);
                                    }

                                    bill = bill + '<i class="fa fa-print mr-20" style="color:' + color1 + ';font-size:14px;" title="Bill preview" onclick=\'bill_preview(' + $.trim(s2[0]) + ',' + data[i].patientid + ',' + data[i].hospitalid + ',' + data[i].branch_id + ',1)\'>' + amount + '</i>'
                                }
                            }
                            if (data[i].edit_bill != 0) {
                                edit_bill = '<li><a href="/BillingMaster/index?billingno=' + data[i].edit_bill + '&branch_id=' + data[i].branch_id + '&visit_report_id=' + data[i].visit_report_id + '&discount_edit_val=1"  title="Edit Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Edit Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Edit Bill</span></a></li>'
                            }
                            var duebillpayment = '';
                            if (duebillno != '') {
                                duebillpayment = '<li><a href=/BillingMaster/billing_receipt?Billing_no=' + duebillno + ' title="Due Payment" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Due Payment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Due Payment</span></a></li>';
                            }

                            //checkin status
                            if (data[i].check_status == '' || data[i].check_status == null) {

                                checkin = '<button type="button" ' + btndisable + ' class="btn btn-primaryuse btn-xs btn-flat mr-20" onclick=checkin("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].status_bill + '","' + data[i].IsBillCheckIn + '");>Check In</button>';
                                noshow = '<a href="javascript:void(0);" id="" onclick=NoShow("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '") class="mr-5" title="noshow" data-trigger="hover" data-toggle="tooltip" data-original-title="no show"><i class="fa fa-eye-slash fa-sm"></i></a>'
                                Decline = '<a href="javascript:void(0);" onclick=Decline("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].coupon_id + '") class="mr-5" title="Decline Appointment" data-trigger="hover" data-toggle="tooltip" data-original-title="Decline Appointment"><i class="fa fa-ban fa-sm"></i></a>'
                                reschedule = '<a href="javascript:void(0);" ' + btndisable + ' onclick=\'reschedule(\"' + data[i].patient_id + '\",\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].branch_id + '\",' + data[i].appointment_type + ')\' class="mr-5" title="Reschedule" data-trigger="hover" data-toggle="tooltip" data-original-title="Reschedule"><i class="fa fa-refresh fa-sm"></i></a>'
                            }

                            else if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                var redirect = '';
                                //var redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    redirect = '/Casestudy/Indexformbuilder?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;

                                }
                                else {
                                    redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                }
                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\", \"' + data[i].age + '\", \"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                if (data[i].appointment_type == 2) {
                                    Engage = '<div class="btn-group"><a type="button" ' + btndisable + ' class="btn btn-submit btn-xs btn-flat mr-20 ' + disablebtn + '" onclick=\'videocallcheck(\"' + data[i].patient_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].appointment_type + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].balance_amount + '\", \"' + data[i].payment_mode + '\",\"' + data[i].doctor_id + '\",\"' + data[i].due_amount + '\",\"' + data[i].totalbills + '\")\';><i class="fa fa-video-camera"></i> Video Call</a>'
                                        + '<button type="button" ' + disablebtn + ' class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu">'
                                        //<li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li>'
                                        //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                        + '</ul></div>';
                                    smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
                                }
                                else {
                                    Engage = '<div class="btn-group">'
                                        //+ '<a type="button" ' + btndisable + ' href="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Engage</div></a>'
                                        + '<a type="button" ' + btndisable + ' data-name="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20 ' + disablebtn + ' btn_r" data-id="CAS_AF" data-type="role_rights_function" data-nav="redirect" ><div>Engage</div></a>'
                                        + '<button type="button" ' + disablebtn + ' class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu"><li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                        + '</li>'
                                        // + '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '</ul></div>';
                                }

                            }
                            else if (data[i].check_status == 2 || data[i].check_status == 4) {
                                Engage = '<span class="pull-left">Engaged</span>';

                                var newbtndisable = btndisable;
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        if (data[i].visit_report_id != null && data[i].visit_report_id != "") {
                                            var d1 = new Date(currentseldate);
                                            var d2 = new Date();
                                            var monthd2 = d2.getMonth() + 1;
                                            var dayd2 = d2.getDate();

                                            var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                            d2 = new Date(outputd2);
                                            var differInTime = Math.abs(d2 - d1);
                                            var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                            if (differDays <= 1) {
                                                newbtndisable = '';
                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                Engage = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                                //Engage = '<a type="button" ' + newbtndisable + ' href="/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'

                                            }
                                        }
                                    }

                                }

                            }

                            else if (data[i].check_status == 3 || data[i].check_status == 5 || data[i].doctor_appointment_slot_status == 4) {
                                var newbtndisable = btndisable;
                                var editbutton = ''
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';

                                }
                                else {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';
                                }
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        var d1 = new Date(currentseldate);
                                        var d2 = new Date();
                                        var monthd2 = d2.getMonth() + 1;
                                        var dayd2 = d2.getDate();

                                        var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                        d2 = new Date(outputd2);
                                        var differInTime = Math.abs(d2 - d1);
                                        var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                        if (differDays <= 1) {
                                            newbtndisable = '';
                                            if (data[i].visit_report_id != null && data[i].visit_report_id != "") {

                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                editbutton = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                            }
                                        }
                                    }

                                }

                                if ($('#hiddenRole_id').val() != 2) {
                                    $('#SelBranch').val($('#HospitalBranchID').val());
                                }

                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                Engage = '<div class="btn-group">' + editbutton
                                    // + '<a type="button" href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                    + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + P_status + ''
                                    + '<ul class="dropdown-menu"><li  ' + btndisable + '><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li>'
                                    //+'<a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li ' + btndisable + '>'
                                    //+'<a  href="#" style="display:none;" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="procedure" data-toggle="tooltip" data-original-title="Procedure"><i class="fa fa-tasks fa-lg"></i><span>Procedure</span></a></li><li ' + btndisable + '>'
                                    + '<a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Diet Plan" data-toggle="tooltip" data-original-title="Diet Plan"><i class="fa fa-male fa-lg"></i><span>Diet Plan</span></a>'
                                    + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                    //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                    //+ '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                    + '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\",\"' + data[i].prescription_page_style + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                   //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                    + '<li><a href=/BillingMaster/index?visit_report_id=' + data[i].visit_report_id + '&patientid=' + data[i].patient_id + '&branch_id=' + data[i].branch_id + '&entity=' + data[i].is_entity + '&type=1&insurance=' + data[i].is_insurance + '&multipay=' + data[i].is_pay + ' title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                    + '</ul></div>'

                                delivery = '<a ' + btndisable + ' href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now </a>';
                            }
                                //no show
                            else {
                                Engage = '<span class="pull-left">No Show</span>';
                                //color = '<i class="fa fa-minus-circle below_average" aria-hidden="true"></i>';
                                color = '<small class="label label-danger">No Show</small>';
                            }
                            if (data[i].visit_report_id != '' && data[i].visit_report_id != null) {
                                if (data[i].total_amount == null || data[i].total_amount == '' && data[i].total_amount != 0) {
                                   
                                }
                                else {
                                    
                                    delivery = '<a href="javascript:void(0)" data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a>';
                                    var invoice_print = '<span onclick=invoiceprint(\"' + data[i].visit_report_id + '\");><i class="fa fa-print fa-lg" title="Invoice Print" data-toggle="tooltip" data-original-title="Invoice Print"></i></span>';

                                   
                                }
                            }
                            else {
                                if (data[i].online_invoice_status == 3) {
                                    //balance = '';
                                    //bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">Paid online</span> &nbsp;';
                                }
                            }

                            var app_type = '';
                            var doctor_pharmacy_id = data[i].pharmacy_id;
                            var pharmacy_id = doctor_pharmacy_id;
                            if (pharmacy_id == '') {
                                delivery = '-';
                            }
                            var doctor_patient_id = '', recentvisits, noofvisits;
                            if (data[i].recent_visit == '' || data[i].recent_visit == null || data[i].recent_visit == '0') recentvisits = '-';
                            else recentvisits = data[i].recent_visit + ' days ago';

                            if (data[i].no_of_visits == "" || data[i].no_of_visits == null || data[i].no_of_visits == "0") noofvisits = '-';
                            else noofvisits = data[i].no_of_visits;

                            var toatl_no_recent_visit = noofvisits + '|' + recentvisits;

                            if (data[i].doctor_patient_id != '' && data[i].doctor_patient_id) {
                                doctor_patient_id = ' | ' + data[i].doctor_patient_id;
                            }

                            app_details = '';
                            var watchicon = "";

                            var walkin = '<i class="fas fa-walking mr-20" style="color:black;font-size:14px;" title="Walkin"></i>',
                                video_call = '<span class="v-icon mr-20"><i class="fa fa-video-camera" aria-hidden="true" title="Video Call"></i></span>',
                                sms = '<i class="fas fa-sms icon-design mr-20" style="color:blue;font-size:14px;" title="Chat Consultation"></i>',

                                mobile_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Patient App"></i>',
                                inclinic = '<i class="fas fa-clinic-medical mr-20" style="color:blue;font-size:14px;" title="Booked In Clinic"></i>',
                                chatbot = '<i class="fa fa-comment-o icon-design mr-20" style="color:#006400;font-size:14px;" title="Chatbot"></i>',
                                doctor_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Doctor App"></i>',

                                package_app = '<i class="fa fa-shield icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Booked from package Coupon"></i>',
                                pay_after = '<i class="fa fa-inr icon-design mr-20" style="color:#f39c12;font-size:14px;" title="Pay after consultation"></i>',
                                prepaid = '<i class="fa fa-inr icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Paid via Mobile App"></i>',
                                doc_collect = '<i class="fas fa-rupee-sign mr-20" style="color:red;font-size:14px;" title="Doctor To Collect Payment"></i>',

                                vip_patient = '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>',
                                watch_patient = '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:14px;" title="Watch List"></i>';

                            if (data[i].source_of_booking == "1") app_details = app_details + inclinic;
                            else if (data[i].source_of_booking == "2") app_details = app_details + mobile_app;
                            else if (data[i].source_of_booking == "3") app_details = app_details + doctor_app;
                            else if (data[i].source_of_booking == "4") app_details = app_details + chatbot;
                            else app_details = app_details;

                            if (data[i].appointment_type == 1) app_details = app_details + walkin;
                            else if (data[i].appointment_type == 2) app_details = app_details + video_call;
                            else app_details = app_details + sms;

                            if (data[i].payment_mode == "1") app_details = app_details + package_app;
                            else if (data[i].payment_mode == "2") app_details = app_details + prepaid;
                            else if (data[i].payment_mode == "3") app_details = app_details + pay_after;
                            else app_details = app_details + doc_collect;

                            if (data[i].vip_description != null && data[i].vip_status == "1") watchicon = vip_patient;

                            var watchlist_end_date = new Date(data[i].watchlist_end_date);
                            var currentdate = new Date(data[i].currentdate);

                            if (watchlist_end_date >= currentdate && data[i].watchlist_status == "1") app_details = app_details + watch_patient;
                            app_details = app_details + bill
                            app_details = '<td class="align-middle">' + app_details + '</td>';

                            var due_status = ''
                            if (data[i].total_due_amount > 0) {
                                due_status = 'Due'
                            }

                            if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    // case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;"  onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                else {
                                    //case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                row_data = row_data + '<tr><td class="hidden"></td><td><span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                     + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td>' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle"><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    //+ '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td>'
                                    + '</tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'


                            }
                            else {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    //case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this)\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                else {
                                    //case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;"  onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                row_data = row_data + '<tr><td class="hidden"><td><span class="mr-10">' + (i + 1) + '</span>' + color + '</td></td><td>span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                    + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td>' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle"><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    //+ '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td>'
                                    + '</tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'
                            }
                        }
                        tr.append(row_data);
                        tr.append("</tbody>");

                        div.append(tr);
                    }
                    else {
                        
                    }

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

           // LoadReviewAppointmentList();
            
        }
    });
    return div;
}


function LoadBranch(dtr_id, b_id) {
    debugger;
    var Indicator = '', user_id = '';
    if (b_id == '' || b_id == undefined) {
        Indicator = "LBRAN";
        user_id = '';
    } else {
        Indicator = "LMB";
        user_id = b_id;
    }
    $('#SelBranch').empty();
    var subdepartment = {
        Dml_Indicator: Indicator,
        doctor_user_id: user_id,
        hospital_id: $('#HospitalId').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)) {
                    // Handle empty data case
                } else {
                    $('#referal_SelBranch').empty();
                    var SubDepartment = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function(i, emp) {
                        SubDepartment += '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranch').append(SubDepartment);
                        $('#SelBranch').change();
                        $('#referal_SelBranch').append(SubDepartment);
                    } else {
                        $('#SelBranch').append(default_opt + SubDepartment);
                        $('#referal_SelBranch').append(default_opt + SubDepartment);
                    }
                    debugger;
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        LoadDoctor();
                    }
                    if (b_id != '') {
                        LoadDoctor(dtr_id);
                    }

                    // Bind values to radio buttons
                    if (data1.Table.length >= 2) {
                        $('#label-1').text(data1.Table[0].branch_name);
                        $('#label-2').text(data1.Table[1].branch_name);
                    }
                }
            } else {
                console.log(data1);
            }
        }
    });
}


$('#SelBranch').change(function () {
    $('#data_table_appointment tbody').empty();
    LoadDoctor(0);
});

function LoadDoctor(dtr_id) {
    debugger;
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        //Dml_Indicator: "DL",
        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) {
            debugger;
            $('#SelDoctor').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {


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

                        if (dtr_id != '' || dtr_id != 0) {
                            $('#SelDoctor').val(dtr_id);
                            LoadAppointmentRequest(dtr_id);
                        }
                    }

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


$('#SelDoctor').change(function () {
    var id = $('#SelDoctor').val();
    LoadAppointmentRequest(id);
});

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

            }
            else {
                console.log(data);
                if (data.msg == "Success") {
                    if (data.data.Table9.length > 0) {
                        $('#pharmacy_id').val(data.data.Table9[0].pharmacy_id);
                    }

                    $('#todayAppointment_loader').addClass('us-db-menu-loader');
                    $('#weeklyappointment_loader').addClass('us-db-menu-loader');
                    $('#Monthlyappointment_loader').addClass('us-db-menu-loader');
                    $('#viplist_loader').addClass('us-db-menu-loader');
                    $('#watchlist_loader').addClass('us-db-menu-loader');

                    var todayAppointment = '', todayvisit = '', weeklyAppointment = '', weeklyVisit = '';

                    if (data.data.Table.length > 0) {
                        $('.appoint').html(data.data.Table[0].total_appointment);
                        todayAppointment = data.data.Table[0].total_appointment;
                    }
                    else {
                        $('.appoint').html('0');
                    }
                    if (data.data.Table1.length > 0) {
                        $('.visit').html(data.data.Table1.length);
                        todayvisit = data.data.Table1.length;
                    }
                    else {
                        $('.visit').html('0');
                    }
                    if (data.data.Table2.length > 0) {
                        $('.appoint_week').html(data.data.Table2[0].total_appointment_week);
                        weeklyAppointment = data.data.Table2[0].total_appointment_week;
                    }
                    else {
                        $('.appoint_week').html('0');
                    }
                    if (data.data.Table3.length > 0) {
                        $('.visit_week').html(data.data.Table3.length);
                        weeklyVisit = data.data.Table3.length;
                    }
                    else {
                        $('.visit_week').html('0');
                    }
                    var Month = '';
                    switch (new Date().getMonth()) {
                        case 0:
                            Month = "Jan ";
                            break;
                        case 1:
                            Month = "Feb ";
                            break;
                        case 2:
                            Month = "Mar ";
                            break;
                        case 3:
                            Month = "Apr ";
                            break;
                        case 4:
                            Month = "May ";
                            break;
                        case 5:
                            Month = "Jun ";
                            break;
                        case 6:
                            Month = "July ";
                            break;
                        case 7:
                            Month = "Aug ";
                            break;
                        case 8:
                            Month = "Sep ";
                            break;
                        case 9:
                            Month = "Oct ";
                            break;
                        case 10:
                            Month = "Nov ";
                            break;
                        case 11:
                            Month = "Dec ";
                            break;
                    }
                    if (data.data.Table4.length > 0) {
                        $('.monthly_appoinment').html(data.data.Table4[0].total_appointment_month);

                        $('.monthly_appoinment_txt').html('No of appointments for ' + Month + new Date().getFullYear());
                    }
                    else {
                        $('.monthly_appoinment').html('0');
                        $('.monthly_appoinment_txt').html('No of appointments for ' + Month + new Date().getFullYear());
                    }
                    if (data.data.Table5.length > 0) {

                        var status = '', val = '', j = '', check_status = '';
                        for (var i = 0; i < data.data.Table5.length; i++) {
                            j++;
                            status = data.data.Table5[i].doctor_appointment_slot_status;
                            check_status = data.data.Table5[i].check_status;
                            if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                if (check_status == 6) {
                                    val = val + '<a href="/casestudy/CaseStudyView_form?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. <i class="fa fa-minus-circle below_average" aria-hidden="true"></i> ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else if (status == 1) {
                                    val = val + '<a href="/casestudy/CaseStudyView_form?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else if (status == 7 && data.data.Table5[i].visit_report_id == null) {
                                    val = val + '<a href="/casestudy/CaseStudyView_form?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else {
                                    val = val + '<a href="/casestudy/CaseStudyView_form?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. <i class="fa fa-check-circle above_average" aria-hidden="true"></i> ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                            }
                            else {
                                if (check_status == 6) {
                                    val = val + '<a href="/casestudy/CaseStudyView?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. <i class="fa fa-minus-circle below_average" aria-hidden="true"></i> ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else if (status == 1) {
                                    val = val + '<a href="/casestudy/CaseStudyView?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else if (status == 7 && data.data.Table5[i].visit_report_id == null) {
                                    val = val + '<a href="/casestudy/CaseStudyView?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                                else {
                                    val = val + '<a href="/casestudy/CaseStudyView?patient_id=' + data.data.Table5[i].patient_id + '&Did=' + data.data.Table5[i].doctor_id + '"><div class="pull-left">' + j + '. <i class="fa fa-check-circle above_average" aria-hidden="true"></i> ' + data.data.Table5[i].first_name + '</div><div class="pull-right">| ' + data.data.Table5[i].slottime + '</div><div class="clearfix"></div></a>'
                                }
                            }
                        };
                        $('.appointmentlist').html(val);
                    }
                    if (data.data.Table6.length > 0) {
                        $('.vip_id').html(data.data.Table6[0].vip_id);
                    }
                    else {
                        $('.vip_id').html('0');
                    }

                    if (data.data.Table7.length > 0) {
                        $('.watch_id').html(data.data.Table7[0].watch_id);
                    }
                    else {
                        $('.watch_id').html('0');
                    }
                    if (data.data.Table8.length > 0) {
                        $('#lab_id').val(data.data.Table8[0].lab_id);
                        $('#lab_data_flag').val(data.data.Table8[0].data_flag);
                    }
                    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) {
                        if (data.data.Table10.length > 0) {
                            var mclcount = data.data.Table10[0].patient_mobile_count;
                            $('.mclCount').html(mclcount);
                        }
                        else {
                            $('#mclCount').html('0');

                        }
                    }
                    else {
                        if (data.data.Table11.length > 0) {
                            var mclcount = data.data.Table11[0].patient_mobile_count;
                            $('.mclCount').html(mclcount);
                        }
                        else {
                            $('#mclCount').html('0');

                        }
                    }
                    var todaycount = ((todayAppointment) - (todayvisit));
                    if (todaycount == 0) {
                        todaycount = 'no';
                    }
                    if (todaycount > 1) {
                        $('.TodayAppointment').html('You have ' + todaycount + ' appointments left for the day.');
                    }
                    else {
                        $('.TodayAppointment').html('You have ' + todaycount + ' appointment left for the day.');
                    }
                    var totweekly = weeklyAppointment - weeklyVisit;
                    if (totweekly == 0) {
                        totweekly = 'no';
                    }
                    if (totweekly > 1) {
                        $('.WeeklyAppointment').html('You have ' + totweekly + ' appointments left for this week.');
                    }
                    else {
                        $('.WeeklyAppointment').html('You have ' + totweekly + ' appointment left for this week.');
                    }
                    $('#todayAppointment_loader').removeClass('us-db-menu-loader');
                    $('#weeklyappointment_loader').removeClass('us-db-menu-loader');
                    $('#Monthlyappointment_loader').removeClass('us-db-menu-loader');
                    $('#viplist_loader').removeClass('us-db-menu-loader');
                    $('#watchlist_loader').removeClass('us-db-menu-loader');
                    $('#critical_loader').removeClass('us-db-menu-loader');
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


function NoOfMobileUser() {
    var dml_ind = 'CSA';
    if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
        dml_ind = "CS";
    }
    var screen = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: dml_ind,
        product_code: $('#HProductCode').val(),
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Dashboard_count',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(screen),
        success: function (datas) {
            var data = JSON.parse(datas);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {


                    console.log(data);
                    var tr = '';
                    for (var i = 0; i < data.Table.length; i++) {
                        var image = data.Table[i].photo;
                        var PatientPhoto = $('#patphotop').val();
                        if ($.trim(data.Table[i].PatientImage) == "" || data.Table[i].PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data.Table[i].PatientImage;
                            photoSrc = PtImage;
                        }
                        //tr = tr + '<div class="img_container"><a href="/casestudy/CaseStudyView?patient_id=' + data.Table[i].patient_id + '"><div class="product-img" style="width: 60px;float: left;"><img onerror="changedefault(this)" src=' + photoSrc + ' class="prof_imgblock"></div><div class="product-info"><span class="product-description"><div class="name-ar"><a href="javascript:void(0)">' + data.Table[i].first_name + '</a></div><div class="phone-ar"><i class="fa fa-phone" aria-hidden="true"></i> ' + data.Table[i].phone_number_1 + '</div></span><div class="clearfix"></div></div></a><div class="overlay_block"><div class="text_block"><a href="/Message" class="icon_outer_span"><i class="fa fa-envelope-o" aria-hidden="true"></i></a><a href="/casestudy/CaseStudyView?patient_id=' + data.Table[i].patient_id + '"  class="icon_outer_span cp_icon_outer_span"><img src="/Content/img/profile_view.png" class="img-responsive cp_icon_img"></a></div></div></div>';
                        //tr = tr + '<div class="row"><table class="table-responsive table table-bordered table-striped no-footer dataTable" id="tbl-scan"><thead> <tr><th>S.no</th><th>Name </th><th>Mobile No</th></tr></thead></table></div>'
                        tr = tr + '<tr><td>' + data.Table[i].patient_id + '</td><td><div class="user-data"><img class="img-responsive"  src="' + photoSrc + '" alt="Patient Image"><p class="ml-10 mt5">' + data.Table[i].first_name + '</p></div></td><td>' + data.Table[i].phone_number_1 + '</td></tr>'
                    }
                    $('.noofmobileuser').html(tr);
                    //$('.modalsortable3').html(tr);
                    //$('.modalsortable3').removeClass('da-load-pp-wl-vip-ma');

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


//Search for cus par
$(function () {
    $.expr[':'].containsIgnoreCase = function (n, i, m) {
        return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

    $('#labParametersListTableInput').keyup(function (e) {
        clearTimeout($.data(this, 'timer'));
        if (e.keyCode == 13)
            search(true);
        else
            $(this).data('timer', setTimeout(search, 100));
    });
});

function search(force) {
    if (this.value == '') {
        $('#labParameters tbody tr').show();
        return;
    }
    var word = $('#labParametersListTableInput')[0].value;
    var word_filter = $('#labParameters tbody tr');
    if ($.trim(word) != '')
        word_filter = word_filter.filter(':containsIgnoreCase(' + word + ')');
    $('#labParameters tbody tr').hide();
    $("#labParameters tbody tr.lt-hm-show-head").show();
    word_filter.show();
}

//lab test static data toggle function


function datefun() {
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndtoday').val(output);

    //yesterday
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate() - 1;

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndyesterday').val(output);

    //tomorrow
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate() + 1;

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndtomorrow').val(output);
}

function datefunction() {
    debugger;
    var date = $('#datepicker').val();
    $('.app_date_current').html(date);
    var id = $("#SelDoctor").val();
    if (id == null || id == '') {
        id = $("#HiddenDoctorID").val();
    }
    LoadAppointmentRequest(id);
    appointment_summary();
    LoadReferredPatientsList()
    
    $('#referal_SelBranch').val(0);
    $('#referal_SelDoctor').empty();
    $('#referal_to_SelDoctor').empty();
}
function leftarrow() {
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }
    else if ($('.app_date_current').html() == 'Yesterday') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() - 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() + 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }


    var displaydate = $('.app_date_current').html();
    var date = '';
    var month = '';
    var displaydates = displaydate.split("/");
    displaydate = displaydates[1];
    if (displaydate == '01' || displaydate == '03' || displaydate == '05' || displaydate == '07' || displaydate == '08' || displaydate == '10' || displaydate == '12') {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '30' + '/' + '11' + '/' + displaydates[2];
                $('.app_date_current').html(date);
            }
            else if (displaydate == '01') {
                date = parseInt(displaydates[1]) + parseInt(1);
                var year = (displaydates[2]) - (1);
                date = '31' + '/' + '12' + '/' + year;
                $('.app_date_current').html(date);
            }
            else if (displaydate == '03') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '28' + '/' + '02' + '/' + displaydates[2];
                $('.app_date_current').html(date);
            }
            else {
                date = displaydates[1] - 1;
                if (date < 10) {
                    date = '0' + date;
                }
                date = '30' + '/' + date + '/' + displaydates[2];
                $('.app_date_current').html(date);
            }
        }

    }
    else if (displaydate == '04' || displaydate == '06' || displaydate == '09' || displaydate == '11') {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + date + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
    }
    else {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + '01' + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
    }

    if (date == $('#hndtoday').val()) {
        $('.app_date_current').html('Today');
    }
    if (date == $('#hndyesterday').val()) {
        $('.app_date_current').html('Yesterday');
    }
    if (date == $('#hndtomorrow').val()) {
        $('.app_date_current').html('Tomorrow');
    }
    var id = $("#SelDoctor").val();
    if (id == null || id == '') {
        id = $("#HiddenDoctorID").val();
    }
    LoadAppointmentRequest(id);
    appointment_summary();
    LoadReferredPatientsList()
    $('#referal_SelBranch').val(0);
    $('#referal_SelDoctor').empty();
    $('#referal_to_SelDoctor').empty();
}

function rightarrow() {
    if ($('.app_date_current').html() == 'Today') {


        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }


    else if ($('.app_date_current').html() == 'Yesterday') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() - 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() + 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('.app_date_current').html(output);
    }
    var displaydate = $('.app_date_current').html();
    var date = '';
    var month = '';
    var displaydates = displaydate.split("/");
    displaydate = displaydates[1];
    if (displaydate == '01' || displaydate == '03' || displaydate == '05' || displaydate == '07' || displaydate == '08' || displaydate == '10' || displaydate == '12') {
        if (displaydates[0] < 31) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                year = parseInt(displaydates[2]) + parseInt(1);
                date = '01' + '/' + '01' + '/' + year;
                $('.app_date_current').html(date);
            }
            else {
                date = parseInt(displaydates[1]) + parseInt(1);
                if (date < 10) {
                    date = '0' + date;
                }
                date = '01' + '/' + date + '/' + displaydates[2];
                $('.app_date_current').html(date);
            }
        }
    }
    else if (displaydate == '04' || displaydate == '06' || displaydate == '09' || displaydate == '11') {
        if (displaydates[0] < 30) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
    }
    else {
        if (displaydates[0] < 28) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('.app_date_current').html(date);
        }
    }
    if ($('.app_date_current').html() == $('#hndtoday').val()) {
        $('.app_date_current').html('Today');
    }
    if ($('.app_date_current').html() == $('#hndyesterday').val()) {
        $('.app_date_current').html('Yesterday');
    }
    if ($('.app_date_current').html() == $('#hndtomorrow').val()) {
        $('.app_date_current').html('Tomorrow');
    }
    var id = $("#SelDoctor").val();
    if (id == null || id == '') {
        id = $("#HiddenDoctorID").val();
    }
    LoadAppointmentRequest(id);
    appointment_summary();
    LoadReferredPatientsList()
    $('#referal_SelBranch').val(0)
    $('#referal_SelDoctor').empty();
    $('#referal_to_SelDoctor').empty();
}

function paymentcls() {
    $('#payphonenumber').val('');
    $('#totpopup_amout >i').html('');
    LoadAppointmentRequest();
}


//commented by nandhini on 22/09/2021

//function LoadAppointmentRequest(id) {
//    if (id == "" || id == null) {

//    }
//    else {
//        $('#SelDoctor').val(id);
//        $('#my_schedule_div,#data_table_appointment').show();
//        $('html, body').animate({
//            scrollTop: $("#data_table_appointment").offset().top
//        }, 1000)
//    }

//    var date = '';
//    if ($('.app_date_current').html() == 'Today') {
//        var d = new Date();
//        var month = d.getMonth() + 1;
//        var day = d.getDate();

//        var output = (day < 10 ? '0' : '') + day + '/' +
//            (month < 10 ? '0' : '') + month + '/' +
//            d.getFullYear();
//        date = output;
//    }

//    else if ($('.app_date_current').html() == 'Yesterday') {
//        date = $('#hndyesterday').val();
//    }
//    else if ($('.app_date_current').html() == 'Tomorrow') {
//        date = $('#hndtomorrow').val();
//    }
//    else {
//        date = $('.app_date_current').html();

//    }
//    var dates = date.split('/');
//    date = dates[2] + '-' + dates[1] + '-' + dates[0];

//    var d = new Date();

//    var month = d.getMonth() + 1;
//    var day = d.getDate();

//    var output = d.getFullYear() + '-' +
//        (month < 10 ? '0' : '') + month + '-' +
//        (day < 10 ? '0' : '') + day;

//    var btndisable = '';
//    if (date == output) {
//        btndisable = '';
//    }
//    else {
//        btndisable = 'style="display:none";';
//    }
//    $('#data_table_appointment').addClass('us-db-loader-appoinments');
//    var DoctorId = $('#myHiddenVar').val();
//    var role_id = $('#hiddenRole_id').val();
//    if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {

//    }
//    else {
//        DoctorId = $('#SelDoctor').val();
//        role_id = 1;
//    }
//    var Performers = {
//        doctor_id: DoctorId,
//        AppointmentDate: date,
//        User_role: role_id
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Dashboard/select_Appointment_Request',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(Performers),
//        success: function (data) {
//            console.log(data);
//            $('#appointment_requests').empty();
//            $('#mobilcardappointment').empty();
//            if (jQuery.isEmptyObject((data))) {
//                $('#data_table_appointment_video,#data_table_appointment_visited').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                $('#data_table_appointment').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                $('#appointment_request-modal').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                $('#data_table_appointment,#data_table_appointment_video,#data_table_appointment_visited').removeClass('us-db-loader-appoinments');
//            }
//            else {
//                var data = JSON.parse(data);
//                console.log(data);
//                var tr = '', mtr = '', vtr = '', vdtr = '';
//                if (data.length > 0) {
//                    for (var i = 0; i < data.length; i++) {
//                        
//                        var patient_photo = data[i].patient_photo;
//                        $('#lab_id').val(data[0].lab_id);
//                        $('#lab_data_flag').val(data[0].data_flag);
//                        var WaitingTime = 0;
//                        if (data[i].check_status > 1) {
//                            var checkin_timeminutes = (data[i].checkin_timeminutes);
//                            var checkout_timeminutes = (data[i].checkout_timeminutes);
//                            if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
//                                WaitingTime = '-';
//                            }
//                            else {

//                                WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
//                                var WaitingTimes = WaitingTime.split(':');
//                                WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
//                            }
//                        }
//                        else if (data[i].check_status == null || data[i].check_status == '') {
//                            WaitingTime = '-';
//                        }
//                        else {
//                            var checkin_timeminutes = data[i].checkin_timeminutes;
//                            var CurrentTime = data[i].CurrentTime;
//                            WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")
//                            var WaitingTimes = WaitingTime.split(':');
//                            WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
//                        }
//                        var EngagedTime = data[i].enage_time;
//                        if (EngagedTime == null || EngagedTime == '') {
//                            EngagedTime = '-';
//                        }
//                        else {
//                            var EngagedTimes = EngagedTime.split(':');
//                            EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';
//                        }
//                        var photo = '';
//                        var delivery = '-';
//                        var photoSrc;
//                        var PatientPhoto = $('#patphotop').val();
//                        if ($.trim(patient_photo) == "" || patient_photo == null) {
//                            photoSrc = "/Content/img/profile_icon.png";
//                        }
//                        else {
//                            photoSrc = PatientPhoto + patient_photo;
//                        }
//                        var color = '';
//                        if ((data[i].doctor_appointment_slot_status == 1 || data[i].doctor_appointment_slot_status == 7) && data[i].pcheckin_timeminutes == null) {
//                            color = '';
//                        }
//                        else {
//                            color = '<i class="fa fa-check-circle above_average" aria-hidden="true"></i>';
//                        }
//                        var checkin = '';
//                        var Engage = '';
//                        var MEngage_1 = '';
//                        var MEngage_2 = '';
//                        var Decline = '';
//                        var noshow = '', balance = '', labtest = '', bal = '-', smslink = '-',reschedule='';
//                        //checkin status
//                        if (data[i].check_status == '' || data[i].check_status == null) {
//                            //commented by nandhini
//                            //checkin = '<a href="javascript:void(0);" ' + btndisable + ' onclick=checkin("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '"); id="" class="btn-default btn btn-save hm-dt-btn apt-checkin">Check In</a>';
//                            //noshow = '<a href="javascript:void(0);" id="" onclick=NoShow("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '") class="hm-dt-action edit " title="no show" data-trigger="hover" data-toggle="tooltip" data-original-title="No show"><i class="fa fa-eye-slash fa-lg"></i></a>'
//                            //Decline = '<a href="javascript:void(0);" id="" onclick=Decline("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].coupon_id + '") class="hm-dt-action" title="Decline" data-trigger="hover" data-toggle="tooltip"><i class="fa fa-ban fa-lg"></i></a>'
//                            //reschedule = '<a href="javascript:void(0);" ' + btndisable + ' id="" onclick=\'reschedule(\"' + data[i].patient_id + '\",\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_first_name + '\")\' class="hm-dt-action edit " title="Reschedule" data-trigger="hover" data-toggle="tooltip" data-original-title="Reschedule"><i class="fa fa-refresh fa-lg"></i></a>'

//                            checkin = '<button type="button" ' + btndisable + ' class="btn btn-primaryuse btn-xs btn-flat mr-20" onclick=checkin("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '");>Check In</button>';
//                            noshow = '<a href="javascript:void(0);" id="" onclick=NoShow("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '") class="mr-5" title="" data-trigger="hover" data-toggle="tooltip" data-original-title="no show"><i class="fa fa-eye-slash fa-sm"></i></a>'
//                            Decline = '<a href="javascript:void(0);" onclick=Decline("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].coupon_id + '") class="mr-5" title="" data-trigger="hover" data-toggle="tooltip" data-original-title="Decline"><i class="fa fa-ban fa-sm"></i></a>'
//                            reschedule = '<a href="javascript:void(0);" ' + btndisable + ' onclick=\'reschedule(\"' + data[i].patient_id + '\",\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_first_name + '\")\' class="mr-5" title="" data-trigger="hover" data-toggle="tooltip" data-original-title="Reschedule"><i class="fa fa-refresh fa-sm"></i></a>'
//                        }

//                        else if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
//                            //commented by nandhini
//                            //var redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
//                            //labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\", \"' + data[i].age + '\", \"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
//                            //if (data[i].appointment_type == 2) {
//                            //    Engage = '<a href="javascript:void(0);" ' + btndisable + 'class="btn btn-default btn btn-save hm-dt-btn pull-left" onclick=\'videocallcheck(\"' + data[i].patient_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].appointment_type + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].balance_amount + '\", \"' + data[i].payment_mode + '\")\';><i class="fa fa-video-camera"></i> Video Call</a><div class="dropdown us-info-dash-warp"><button class="btn-default btn dropdown-toggle us-dash-btn-info" type="button" data-toggle="dropdown" aria-expanded="true"><i class="fa fa-info-circle 2x"></i><span class="caret"></span></button><ul class="dropdown-menu"><li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li>' + labtest + '</ul></div>';
//                            //    smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
//                            //}
//                            //else {
//                            //    Engage = '<a ' + btndisable + ' href="' + redirect + '" class="btn-default btn btn-save hm-dt-btn new-apt-edit-adj"><div>Engage</div></a><div class="dropdown us-info-dash-warp"><button class="btn-default btn dropdown-toggle us-dash-btn-info" type="button" data-toggle="dropdown" aria-expanded="true"><i class="fa fa-info-circle 2x"></i><span class="caret"></span></button><ul class="dropdown-menu"><li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a></li>' + labtest + '</ul></div>';
//                            //}
//                            //MEngage_1 = '<a ' + btndisable + ' href="' + redirect + '" class="btn-default btn btn-save hm-dt-btn">Engage</a>';
//                            //MEngage_2 = '<a href="#" data-toggle="modal" data-target="#quickentry"  data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i></a><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></a>';

//                            var redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
//                            labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\", \"' + data[i].age + '\", \"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
//                            if (data[i].appointment_type == 2) {
//                                Engage = '<div class="btn-group"><button type="button" ' + btndisable + ' class="btn btn-submit btn-xs btn-flat mr-20" onclick=\'videocallcheck(\"' + data[i].patient_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].appointment_type + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].balance_amount + '\", \"' + data[i].payment_mode + '\")\';><i class="fa fa-video-camera"></i> Video Call</button>'
//                                + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>'
//                                + '<ul class="dropdown-menu"><li><a href="#" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li>' + labtest + '</ul></div>';
//                                smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
//                            }
//                            else {
//                                Engage = '<div class="btn-group"><button type="button" ' + btndisable + ' href="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Engage</div></button>'
//                                   + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>'
//                                   + '<ul class="dropdown-menu"><li><a href="#" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a></li>' + labtest + '</ul></div>';
//                            }
//                            //MEngage_1 = '<a ' + btndisable + ' href="' + redirect + '" class="btn-default btn btn-save hm-dt-btn">Engage</a>';
//                            //MEngage_2 = '<a href="#" data-toggle="modal" data-target="#quickentry"  data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i></a><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></a>';
//                        }
//                        else if (data[i].check_status == 2 || data[i].check_status == 4) {
//                            Engage = '<span class="pull-left">Engaged</span>';
//                            //MEngage_1 = '<span class="pull-left">Engaged</span>';
//                        }
//                        //casesheet edit status ' + data[i].patient_id + 
//                        else if (data[i].check_status == 3 || data[i].check_status == 5 || data[i].doctor_appointment_slot_status == 4) {
//                            labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
//                            Engage = '<div class="btn-group"><button type="button" href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></button>'
//                                 + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>'
//                                + '<ul class="dropdown-menu"><li  ' + btndisable + '><a href="#" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li><a href="#" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="procedure" data-toggle="tooltip" data-original-title="Procedure"><i class="fa fa-tasks fa-lg"></i><span>Procedure</span></a></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Diet Plan" data-toggle="tooltip" data-original-title="Diet Plan"><i class="fa fa-male fa-lg"></i><span>Diet Plan</span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '><a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a></li>' + labtest + '<li><a href=/PatientDashboard/PPDF?visitreportid=' + data[i].visit_report_id + '&lantype=1&btnval=1 id="" class="hm-dt-action" title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li></ul></div>'
//                            //MEngage_1 = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '" class="btn-default btn btn-save hm-dt-btn apt-edit">Edit</a>';
//                            //MEngage_2 = '<a href="#" data-toggle="modal" data-target="#collectPayment" data-backdrop="static" data-keyboard="false" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i></a><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="procedure" data-toggle="tooltip" data-original-title="Procedure"><i class="fa fa-tasks fa-lg"></i></a><a href=/PatientDashboard/PPDF?visitreportid=' + data[i].visit_report_id + '&lantype=1&btnval=1 id="" class="hm-dt-action" title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="hm-dt-action edit" title="Diet Plan" data-toggle="tooltip" data-original-title="Diet Plan"><i class="fa fa-male fa-lg"></i><span>Diet Plan</span></a></li><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></a>';
//                            delivery = '<a ' + btndisable + ' href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now </a>';
//                        }
//                        //no show
//                        else {
//                            Engage = '<span class="pull-left">No Show</span>';
//                            //MEngage_1 = '<span class="pull-left">No Show</span>';
//                            color = '<i class="fa fa-minus-circle below_average" aria-hidden="true"></i>';
//                        }
//                        if (data[i].visit_report_id != '' && data[i].visit_report_id != null) {
//                            if (data[i].total_amount == null || data[i].total_amount == '' && data[i].total_amount != 0) {
//                                balance = '';
//                                bal = '<span class="">-</span>';
//                            }
//                            else {
//                                balance = '<span class="f12">Balance: <i class="fa fa-inr"></i>' + data[i].balance_amount + '</span>';
//                                var bal_amt = parseFloat(data[i].total_amount) - parseFloat(data[i].balance_amount);

//                                delivery = '<a href="javascript:void(0)" data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a>';
//                                var invoice_print = '<span onclick=invoiceprint(\"' + data[i].visit_report_id + '\");><i class="fa fa-print fa-lg" title="Invoice Print" data-toggle="tooltip" data-original-title="Invoice Print"></i></span>';

//                                if (data[i].total_amount > data[i].balance_amount && data[i].balance_amount != 0) {
//                                    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="btn-default btn btn-save-orange hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
//                                }
//                                else if (data[i].total_amount == data[i].balance_amount) {
//                                    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="btn btn-submit btn-xs">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
//                                }
//                                else {
//                                    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="btn-default btn btn-save hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
//                                }
//                            }
//                        }
//                        else {
//                            if (data[i].online_invoice_status == 3) {
//                                balance = '';
//                                bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\")\'; class="btn-default btn btn-save hm-dt-btn">Paid online</span> &nbsp;';
//                            }
//                        }

//                        var app_type = '';
//                        var doctor_pharmacy_id = data[i].pharmacy_id;
//                        var pharmacy_id = doctor_pharmacy_id;
//                        if (pharmacy_id == '') {
//                            delivery = '-';
//                        }
//                        var doctor_patient_id = '', recentvisits, noofvisits;
//                        if (data[i].recent_visit == '' || data[i].recent_visit == null || data[i].recent_visit == '0') recentvisits = '-';
//                        else recentvisits = data[i].recent_visit + ' days ago';

//                        if (data[i].no_of_visits == "" || data[i].no_of_visits == null || data[i].no_of_visits == "0") noofvisits = '-';
//                        else noofvisits = data[i].no_of_visits;

//                        var toatl_no_recent_visit = noofvisits + '|'+ recentvisits;

//                        if (data[i].doctor_patient_id != '' && data[i].doctor_patient_id) {
//                            doctor_patient_id = ' | ' + data[i].doctor_patient_id;
//                        }

//                        app_details = '';
//							//commented by nandhini
//                        //var walkin = '<a data-toggle="walkin" title="Walkin"><img src="/Content/img/icons-table/walkin-icon.png" class=" db-flag-icon db-typeofappoinment"></a>',
//                        //    video_call = '<a data-toggle="videocall" title="TeleConsultation"><img src="/Content/img/icons-table/video-call.png" class="db-flag-icon db-typeofappoinment"></a>',
//                        //    sms = '<a data-toggle="Sms" title="Chat Consultation"><img src="/Content/img/icons-table/sms-icon.png" class="db-flag-icon db-typeofappoinment"></a>',

//                        //    mobile_app = '<a data-toggle="Mobileapp" title="Booked From Patient App"><img src="/Content/img/icons-table/mobile-app.png" class="db-flag-icon db-modeofappoinment"></a>',
//                        //    inclinic = '<a data-toggle="inclinic" title="Booked in Clinic"><img src="/Content/img/icons-table/inclinic.png" class="db-flag-icon db-modeofappoinment">',
//                        //    chatbot = '<a data-toggle="Chatbot" title="Chatbot"><img src="/Content/img/icons-table/chat.png" class="db-flag-icon db-modeofappoinment"></a>',
//                        //    doctor_app = '<a data-toggle="chat" title="Booked From Doctor App"><img src="/Content/img/icons-table/mobile-app.png" class="db-modeofappoinment db-flag-icon"></a>',

//                        //    package_app = '<a data-toggle="package" title="Booked from package Coupon"><img src="/Content/img/icons-table/package.png" class="db-flag-icon prepaid"></a>',
//                        //    pay_after = '<a data-toggle="Payafter" title="Pay after consultation"><img src="/Content/img/icons-table/paylater.png" class="db-flag-icon paylater"></a>',
//                        //    prepaid = '<a data-toggle="prepaid" title="Paid via Mobile App"><img src="/Content/img/icons-table/pre-paid.png" class="db-flag-icon prepaid"></a>',
//                        //    doc_collect = '<a data-toggle="Doctorcollect" title="Doctor to Collect Payment"><img src="/Content/img/icons-table/doc-collect.png" class="db-flag-icon pending"></a>',

//                        //    vip_patient = '<a data-toggle="vippatient" title="VIP List"><img src="/Content/img/icons-table/vip-lists.png" class="vip db-flag-icon"></a>',
//                        //    watch_patient = '<a data-toggle="watchlist" title="Watch List"><img src="/Content/img/icons-table/watchlist.png" class="watchlist db-flag-icon"></a>';

//                        var walkin = '<i class="fas fa-walking mr-20" style="color:black;font-size:14px;" title="Walkin"></i>',
//                           video_call = '<span class="v-icon mr-20"><i class="fa fa-video-camera" aria-hidden="true"></i></span>',
//                           sms = '<a data-toggle="Sms" title="Chat Consultation"><img src="/Content/img/icons-table/sms-icon.png" class="db-flag-icon db-typeofappoinment"></a>',

//                           mobile_app = '<a data-toggle="Mobileapp" title="Booked From Patient App"><img src="/Content/img/icons-table/mobile-app.png" class="db-flag-icon db-modeofappoinment"></a>',
//                           inclinic = '<i class="fas fa-clinic-medical mr-20" style="color:blue;font-size:14px;" title="Booked In Clinic"></i>',
//                           chatbot = '<a data-toggle="Chatbot" title="Chatbot"><img src="/Content/img/icons-table/chat.png" class="db-flag-icon db-modeofappoinment"></a>',
//                           doctor_app = '<a data-toggle="chat" title="Booked From Doctor App"><img src="/Content/img/icons-table/mobile-app.png" class="db-modeofappoinment db-flag-icon"></a>',

//                           package_app = '<a data-toggle="package" title="Booked from package Coupon"><img src="/Content/img/icons-table/package.png" class="db-flag-icon prepaid"></a>',
//                           pay_after = '<a data-toggle="Payafter" title="Pay after consultation"><img src="/Content/img/icons-table/paylater.png" class="db-flag-icon paylater"></a>',
//                           prepaid = '<a data-toggle="prepaid" title="Paid via Mobile App"><img src="/Content/img/icons-table/pre-paid.png" class="db-flag-icon prepaid"></a>',
//                           doc_collect = '<i class="fas fa-rupee-sign mr-20" style="color:red;font-size:14px;" title="Doctor To Collect Payment"></i>',

//                           vip_patient = '<i class="fa fa-star mr-20" style="color:#3276b1;font-size:14px;" title="VIP"></i>',
//                           watch_patient = '<span class="waitlist-icon"><i class="fa fa-star"></i></span>';

//                        if (data[i].source_of_booking == "1") app_details = app_details + inclinic;
//                        else if (data[i].source_of_booking == "2") app_details = app_details + mobile_app;
//                        else if (data[i].source_of_booking == "3") app_details = app_details + doctor_app;
//                        else if (data[i].source_of_booking == "4") app_details = app_details + chatbot;
//                        else app_details = app_details;

//                        if (data[i].appointment_type == 1) app_details = app_details + walkin;
//                        else if (data[i].appointment_type == 2) app_details = app_details + video_call;
//                        else app_details = app_details + sms;

//                        if (data[i].payment_mode == "1") app_details = app_details + package_app;
//                        else if (data[i].payment_mode == "2") app_details = app_details + prepaid;
//                        else if (data[i].payment_mode == "3") app_details = app_details + pay_after;
//                        else app_details = app_details + doc_collect;

//                        if (data[i].vip_description != null && data[i].vip_status == "1") app_details = app_details + vip_patient;

//                        var watchlist_end_date = new Date(data[i].watchlist_end_date);
//                        var currentdate = new Date(data[i].currentdate);//                        if (watchlist_end_date >= currentdate && data[i].watchlist_status == "1") app_details = app_details + watch_patient;

//                        app_details = '<td class="align-middle">' + app_details + '</td>';

//                        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
//                            
//                            tr = tr + '<tr class="view odd" onclick=\'view_more_details(\"' + WaitingTime + '\",\"' + EngagedTime + '\",\"'+ toatl_no_recent_visit + '\",\"' + bal + '\",\"' + delivery + '\",\"'+ smslink +'\",\"demo_' + (i + 1) + '\")\';><td>' + (i + 1) + '</td><td><span class="appoinment-time">' + color + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
//                            + '<td class="opensub"><a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a><span class="waitlist-icon"><i class="fa fa-star"></i></span><span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="c-icon ml-10" id="" onclick="uschathelpscroller()"><i class="fa fa-comment-o"></i></span></td>'
//                            + app_details
//                            + '<td class="align-middle"><span class="doctorname">' + data[i].doctor_name + '</span></td>'
//                            + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
//                            + '<td class="opensub"><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
//                            + '<tr class="fold" id=demo_' + (i + 1) + '></tr>'
//                            //+ '<td colspan="7"><div class="row"><div class="col-md-12"><div class="col-sm-2"><div class="form-group"><p>Waiting | Engage Time</p><p>' + WaitingTime + ' | ' + EngagedTime + '</p></div></div><div class="col-sm-2"><div class="form-group"><p>Recent Visit</p><p>' + toatl_no_recent_visit + '</p></div></div>'
//                            //+ '<div class="col-sm-3"><div class="form-group">' + bal + '</div></div><div class="col-sm-3"><div class="form-group">' + delivery + '</div></div><div class="col-sm-2"><div class="form-group"><p>SMS</p><p>' + smslink + '</p></div></div></div></div></td></tr>';


//                        }
//                        else {
//                            
//                            tr = tr + '<tr class="view odd" onclick=\'view_more_details(\"' + WaitingTime + '\",\"' + EngagedTime + '\",\"' + toatl_no_recent_visit + '\",\"' + bal + '\",\"' + delivery + '\",\"' + smslink + '\",\"demo_' + (i + 1) + '\")\';><td>' + (i + 1) + '</td><td><span class="appoinment-time">' + color + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
//                                 + '<td class="opensub"><a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a><span class="waitlist-icon"><i class="fa fa-star"></i></span><span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="c-icon ml-10" id="" onclick="uschathelpscroller()"><i class="fa fa-comment-o"></i></span></td>'
//                                + app_details
//                                + '<td class="align-middle"><span class="doctorname">' + data[i].doctor_name + '</span></td>'
//                                + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
//                                + '<td class="opensub"><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
//                                + '<tr class="fold" id=demo_' + (i + 1) + '></tr>'
//                                //+'<td colspan="7"><div class="row"><div class="col-md-12"><div class="col-sm-2"><div class="form-group"><p>Waiting | Engage Time</p><p>' + WaitingTime + ' | ' + EngagedTime + '</p></div></div><div class="col-sm-2"><div class="form-group"><p>Recent Visit</p><p>' + toatl_no_recent_visit + '</p></div></div>'
//                                //+ '<div class="col-sm-3"><div class="form-group">' + bal + '</div></div><div class="col-sm-3"><div class="form-group">' + delivery + '</div></div><div class="col-sm-2"><div class="form-group"><p>SMS</p><p>' + smslink + '</p></div></div></div></div></td></tr>';

//                        }

//                     //commented by nandhini
//                        //if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
//                        //    
//                        //    t1 = '<tr role="row" class="odd prod-flag-align"><td>' + color + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</td>'
//                        //    + '<td class="align-middle "><div class="product-img img"><img onerror="changedefault(this)" class=chat-image chat-image-default src="' + photoSrc + '"></div></td>'
//                        //    + app_details
//                        //    + '<td class="align-middle"><a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '"><span class="mys-nme">' + data[i].patient_first_name + '</span></a><br /><span class="mys-ph">ph : ' + data[i].patient_phone_number + '</span><br /><span class="mys-id">' + data[i].patient_id + doctor_patient_id + '</span></td>'
//                        //    + '<td class="align-middle"><span class="db-doc-name">' + data[i].doctor_name + '</span></td>'
//                        //    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
//                        //    + '<td class="align-middle">' + bal + '</td>'
//                        //    + '<td class="align-middle us-db-tb-et"><i class="fa fa-hourglass-end" aria-hidden="true"></i> <span>' + WaitingTime + '</span> <br> <i class="fa fa-handshake-o" aria-hidden="true"></i> <span>' + EngagedTime + '</span></td>'
//                        //    + '<td class="align-middle"><span>' + toatl_no_recent_visit + '</span> </td><td class="align-middle us-db-tb-on"><span>' + delivery + '</span></td><td>' + smslink + '</td></tr>'
//                        //    if (data[i].appointment_type == 1 && (data[i].doctor_appointment_slot_status == 4 || data[i].doctor_appointment_slot_status == 7 || data[i].doctor_appointment_slot_status == 8)) {
//                        //            vtr = vtr + t1;
//                        //            t1 = " ";
//                        //        }
//                        //        else if (data[i].appointment_type == 1) {
//                        //            tr = tr + t1;
//                        //            t1 = " ";
//                        //        }
//                        //        else if (data[i].appointment_type == 2) {
//                        //            vdtr = vdtr + t1;
//                        //            t1 = "";
//                        //        }
//                        //}
//                        //else {
//                        //    
//                        //    t1 =  '<tr role="row" class="odd prod-flag-align"><td>' + color + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</td>'
//                        //        + '<td class="align-middle"><div class="product-img img"><img onerror="changedefault(this)" class=chat-image chat-image-default src="' + photoSrc + '"></div></td>'
//                        //        + app_details
//                        //        + '<td class="align-middle"><a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '"><span class="mys-nme">' + data[i].patient_first_name + '</span></a><br /><span class="mys-ph">ph : ' + data[i].patient_phone_number + '</span><br /><span class="mys-id">' + data[i].patient_id + doctor_patient_id + '</span></td>'
//                        //        + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
//                        //        + '<td class="align-middle">' + bal + '</td>'
//                        //        + '<td class="align-middle us-db-tb-et"><i class="fa fa-hourglass-end" aria-hidden="true"></i> <span>' + WaitingTime + '</span> <br> <i class="fa fa-handshake-o" aria-hidden="true"></i> <span>' + EngagedTime + '</span></td>'
//                        //        + '<td class="align-middle"><span>' + toatl_no_recent_visit + '</span> </td><td class="align-middle us-db-tb-on"><span>' + delivery + '</span></td><td>' + smslink + '</td></tr>';
//                        //    if (data[i].appointment_type == 1 && ( data[i].doctor_appointment_slot_status == 4 || data[i].doctor_appointment_slot_status == 7 || data[i].doctor_appointment_slot_status == 8)) {
//                        //        vtr = vtr + t1;
//                        //        t1 = " ";
//                        //    }
//                        //    else if (data[i].appointment_type == 1) {
//                        //        tr = tr + t1;
//                        //        t1 = " ";
//                        //    }
//                        //    else if (data[i].appointment_type == 2) {
//                        //        vdtr = vdtr + t1;
//                        //        t1 = "";
//                        //    }
//                        //}
//                        // parthiban code
//                        mtr = mtr + '<div class="col-xs-12 col-md-6"><div class="row mobile-db-card-head"><div class="col-xs-6"><p class="mdch-patientname"><a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '"><span class="mys-nme">' + data[i].patient_first_name + '</span></a><p class="mdch-patientphone">' + data[i].patient_phone_number + '</p> </div><div class="col-xs-6 text-right"><p class="mdch-patientid">' + data[i].patient_id + doctor_patient_id + '</p><p class="mdch-patientlv"><i class="fa fa-calendar-check-o" aria-hidden="true"></i> : <span>' + data[i].lastvisitdate + '</span></p></div><div class="col-xs-12"><p class="mdch-appttime-head">Appt Time  : <span class="mdch-appttime"> ' + color + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + ' </span></p></div>'
//                                  + '<div class="col-xs-12">'+ app_details +'</div>'
//                                  + '<div class="col-xs-12 mdch-footer-card"><div class="col-xs-6"><span class="mdchenggtime-head"><i class="fa fa-hourglass-end" aria-hidden="true"></i></span> : <span class="mdchenggtime"> ' + WaitingTime + ' </span><br /><span class="mdchenggtime-head"><i class="fa fa-handshake-o" aria-hidden="true"></i></span> : <span class="mdchenggtime">' + EngagedTime + '</span></div>'
//                                  + '<div class="col-xs-6"><p class="mdch-ordernow text-center"><a href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a></p></div>'
//                                  + '<div class="col-xs-12"><p class="mdch-adj-footer-btn"><span>' + checkin + Engage + Decline + noshow +reschedule+ '</span></p>'
//                                  + '</div></div></div></div>'
//                    }

//                    if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
//                    //    var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                    //+ '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Doctor Name</th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        if (vtr != '') {
//                                var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Doctor Name</th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }
//                        else if (tr != '') {
//                                var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Doctor Name</th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }
//                        else if (vdtr != '') {
//                                var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Doctor Name</th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }

//                    }
//                    else {
//                        //var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                        //+ '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        if (vtr != '') {
//                            var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }
//                        else if (tr != '') {
//                            var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }
//                        else if (vdtr != '') {
//                            var table = '<table id="dashMysheduleTable" class="table-responsive table table-condensed body-borderless table_borderless m-db-table-head" style="width:100%"><thead>'
//                            + '<tr><th>Appointment Time</th><th>Image</th><th>Appointment Details</th><th>Patient Details </th><th>Action</th><th>Payment</th><th>Waiting | Engage Time </th><th>#visit | Recent visit</th><th>Medicine Order</th><th>SMS</th></tr></thead>';
//                        }
//                    }                
//                    var bodystart = '<tbody>';
//                    var bodyend = '</tbody>';
//                    $('#data_table_appointment tbody').empty();
//                    if ($(window).width() > 1200) {
//                        //$('#data_table_appointment').html(table + bodystart + tr + bodyend);
//                        $('#data_table_appointment tbody').append(tr);

//                        $("tr.view .opensub").on("click", function () {
//                            $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
//                        });

//                        $('#data_table_appointment_video').html(table + bodystart + vdtr + bodyend);
//                        $('#data_table_appointment_visited').html(table + bodystart + vtr + bodyend);
//                        $('#dashMysheduleTable').DataTable({
//                            "lengthChange": false,
//                            "info": false,
//                            "pageLength": 1000,
//                            "bPaginate": false,
//                            "ordering": false
//                        });
//                        $('.dataTables_length').addClass('bs-select');
//                    }
//                    else {
//                        $('#mobilcardappointment').html(mtr);
//                        //$('#data_table_appointment').html(mtr);
//                    }
//                    $('#data_table_appointment').removeClass('us-db-loader-appoinments');
//                    $('#data_table_appointment_video').removeClass('us-db-loader-appoinments');
//                    $('#data_table_appointment_visited').removeClass('us-db-loader-appoinments');
//                    $('[rel=popover]').popover();
//                    $('#docappdetails').show();
//                }
//                else {
//                    $('#data_table_appointment').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                    $('#appointment_request-modal').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                    $('#data_table_appointment,#data_table_appointment_video,#data_table_appointment_visited').removeClass('us-db-loader-appoinments');
//                    $('#data_table_appointment_video,#data_table_appointment_visited').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
//                    $('#docappdetails').show();
//                }
//            }
//        }
//    });
//}

function AppointmentDetails(id, branchid) {
    debugger;

    $('#myschedule_tab_list').tab('show').click().focus();

    //LoadBranch(id, branchid);
    LoadAppointmentRequest1(id)
}
function LoadAppointmentRequest1(id) {
    debugger;
   
    $('#data_table_appointment tbody').empty();

    console.log('id---' + id);
    if (id == "" || id == null) {
        $('#SelDoctor_div').hide();
        $('#SelBranch_div').hide();
    }
    else {
        //$('#SelDoctor').val(id);
        $('#myschedule').show();
        var role_id = $('#hiddenRole_id').val();
        if (role_id == 1 || role_id == 5) {
            $('#SelDoctor_div').hide();
            $('#SelBranch_div').hide();
        }
        else {
            if ($('#referredpatients_tab_list').attr('aria-expanded') != "true") {
                $('#SelBranch_div').show();
                $('#SelDoctor_div').show();
            }
        }
        $('#UM_5,#data_table_appointment').show();
        $('html, body').animate({
            scrollTop: $("#data_table_appointment").offset().top
        }, 1000)
    }

    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    }
    else {
        btndisable = 'style="display:none";';
    }
    $('#data_table_appointment').addClass('us-db-loader-appoinments');
    var DoctorId =($('#hiddenRole_id').val()==1)? $('#myHiddenVar').val():id;
    var role_id = $('#hiddenRole_id').val();
    //if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {
    //}
    //else {
    //    DoctorId = $('#SelDoctor').val();
    //    role_id = 1;
    //    branch_id = (branch_id == null || branch_id == "") ? $('#HospitalBranchID').val() : branch_id;
    //}
    var Performers = {
        doctor_id: DoctorId,
        AppointmentDate: date,
        User_role: role_id,
        Dml_Indicator: "AS",
        branch_id: ""
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            $('#mobilcardappointment').empty();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

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

                    var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    $('#data_table_appointment tbody').append(tr1);
                    //$('#data_table_appointment tbody').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');               
                    $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                }
                else {
                    console.log(data);

                    var tr = '', mtr = '', vtr = '', vdtr = '';
                    if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {



                            var patient_photo = data[i].patient_photo;
                            $('#lab_id').val(data[0].lab_id);
                            $('#lab_data_flag').val(data[0].data_flag);
                            var WaitingTime = 0;
                            if (data[i].check_status > 1) {
                                var checkin_timeminutes = (data[i].checkin_timeminutes);
                                var checkout_timeminutes = (data[i].checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (data[i].check_status == null || data[i].check_status == '') {
                                WaitingTime = '-';
                            }
                            else {
                                var checkin_timeminutes = data[i].checkin_timeminutes;
                                var CurrentTime = data[i].CurrentTime;
                                WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")
                                var WaitingTimes = WaitingTime.split(':');
                                WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                            }
                            var EngagedTime = data[i].enage_time;
                            if (EngagedTime == null || EngagedTime == '') {
                                EngagedTime = '-';
                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';
                            }
                            var photo = '';
                            var delivery = '-';
                            var photoSrc;
                            var PatientPhoto = $('#patphotop').val();
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            var color = '';
                            if ((data[i].doctor_appointment_slot_status == 1 || data[i].doctor_appointment_slot_status == 7) && data[i].pcheckin_timeminutes == null) {
                                color = '';
                            }
                            else {
                                //color = '<i class="fa fa-check-circle above_average" aria-hidden="true"></i>';
                                color = '<small class="label label-success">Completed</small>'
                            }
                            var checkin = '';
                            var Engage = '';
                            var MEngage_1 = '';
                            var MEngage_2 = '';
                            var Decline = '';
                            var noshow = '', balance = '', labtest = '', bal = '-', smslink = '-', reschedule = '';
                            var P_status = ''; var EngageStatus = '',disablebtn = '', previousDue = '';;

                            if (data[i].Status == 1) {
                                P_status = '<a><span class="label label-success">PAID</span></a>'
                            }
                            else if (data[i].Status == 2) {
                                P_status = '<a><span class="label label-warning">PARTIAL</span></a>'
                            }
                            else if (data[i].Status == 5) {
                                P_status = '<a><span class="label label-danger">PENDING</span></a>'
                            }
                            else if (data[i].Status == 3) {
                                P_status = '<a><span class="label label-danger">Due</span></a>'
                            }
                            if (parseFloat(data[i].previousDue) > 0 && data[i].IsApproved != 1) {
                                disablebtn = 'disabled'
                                previousDue = '<a><span class="label label-danger"> Previous Due : ' + data[i].previousDue + '</span></a>'

                            }
                            if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                EngageStatus = P_status;
                            }

                            var bill = '', color1 = '', duebillno = '', edit_bill = '';
                            if (data[i].billno != null) {
                                var s1 = data[i].billno.split(',');

                                for (var p = 0; p < s1.length; p++) {
                                    var amount = '';
                                    var s2 = s1[p].split('/');
                                    if (parseFloat($.trim(s2[2])) > 0) {
                                        color1 = 'red';
                                        amount = $.trim(s2[2]);
                                        if (duebillno == '') {
                                            duebillno = $.trim(s2[0]);
                                        }
                                    }
                                    else {
                                        color1 = 'green'
                                        amount = $.trim(s2[1]);
                                    }

                                    bill = bill + '<i class="fa fa-print mr-20" style="color:' + color1 + ';font-size:14px;" title="Bill preview" onclick=\'bill_preview(' + $.trim(s2[0]) + ',' + data[i].patientid + ',' + data[i].hospitalid + ',' + data[i].branch_id + ',1)\'>' + amount + '</i>'
                                }
                            }
                            if (data[i].edit_bill != 0) {
                                edit_bill = '<li><a href="/BillingMaster/index?billingno=' + data[i].edit_bill + '&branch_id=' + data[i].branch_id + '&visit_report_id=' + data[i].visit_report_id + '&discount_edit_val=1"  title="Edit Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Edit Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Edit Bill</span></a></li>'
                            }
                            var duebillpayment = '';
                            if (duebillno != '') {
                                duebillpayment = '<li><a href=/BillingMaster/billing_receipt?Billing_no=' + duebillno + ' title="Due Payment" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Due Payment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Due Payment</span></a></li>';
                            }

                            //checkin status
                            if (data[i].check_status == '' || data[i].check_status == null) {

                                checkin = '<button type="button" ' + btndisable + ' class="btn btn-primaryuse btn-xs btn-flat mr-20" onclick=checkin("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].status_bill + '","' + data[i].IsBillCheckIn + '");>Check In</button>';
                                noshow = '<a href="javascript:void(0);" id="" onclick=NoShow("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '") class="mr-5" title="noshow" data-trigger="hover" data-toggle="tooltip" data-original-title="no show"><i class="fa fa-eye-slash fa-sm"></i></a>'
                                Decline = '<a href="javascript:void(0);" onclick=Decline("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].coupon_id + '") class="mr-5" title="Decline Appointment" data-trigger="hover" data-toggle="tooltip" data-original-title="Decline Appointment"><i class="fa fa-ban fa-sm"></i></a>'
                                reschedule = '<a href="javascript:void(0);" ' + btndisable + ' onclick=\'reschedule(\"' + data[i].patient_id + '\",\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].branch_id + '\",' + data[i].appointment_type + ')\' class="mr-5" title="Reschedule" data-trigger="hover" data-toggle="tooltip" data-original-title="Reschedule"><i class="fa fa-refresh fa-sm"></i></a>'
                            }

                            else if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                var redirect = '';
                                //var redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    redirect = '/Casestudy/Indexformbuilder?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;

                                }
                                else {
                                    redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                }
                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\", \"' + data[i].age + '\", \"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                if (data[i].appointment_type == 2) {
                                    Engage = '<div class="btn-group"><a type="button" ' + btndisable + ' class="btn btn-submit btn-xs btn-flat mr-20 ' + disablebtn + '" onclick=\'videocallcheck(\"' + data[i].patient_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].appointment_type + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].balance_amount + '\", \"' + data[i].payment_mode + '\",\"' + data[i].doctor_id + '\",\"' + data[i].due_amount + '\",\"' + data[i].totalbills + '\")\';><i class="fa fa-video-camera"></i> Video Call</a>'
                                        + '<button type="button" ' + disablebtn + ' class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu">'
                                        //<li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li>'
                                        //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                        + '</ul></div>';
                                    smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
                                }
                                else {
                                    Engage = '<div class="btn-group">'
                                        //+ '<a type="button" ' + btndisable + ' href="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Engage</div></a>'
                                        + '<a type="button" ' + btndisable + ' data-name="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20 ' + disablebtn + ' btn_r" data-id="CAS_AF" data-type="role_rights_function" data-nav="redirect" ><div>Engage</div></a>'
                                        + '<button type="button" ' + disablebtn + ' class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu"><li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a><a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                        + '</li>'
                                        // + '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '</ul></div>';
                                }

                            }
                            else if (data[i].check_status == 2 || data[i].check_status == 4) {
                                Engage = '<span class="pull-left">Engaged</span>';

                                var newbtndisable = btndisable;
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        if (data[i].visit_report_id != null && data[i].visit_report_id != "") {
                                            var d1 = new Date(currentseldate);
                                            var d2 = new Date();
                                            var monthd2 = d2.getMonth() + 1;
                                            var dayd2 = d2.getDate();

                                            var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                            d2 = new Date(outputd2);
                                            var differInTime = Math.abs(d2 - d1);
                                            var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                            if (differDays <= 1) {
                                                newbtndisable = '';
                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                Engage = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                                //Engage = '<a type="button" ' + newbtndisable + ' href="/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'

                                            }
                                        }
                                    }

                                }

                            }

                            else if (data[i].check_status == 3 || data[i].check_status == 5 || data[i].doctor_appointment_slot_status == 4) {
                                var newbtndisable = btndisable;
                                var editbutton = ''
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';

                                }
                                else {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';
                                }
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        var d1 = new Date(currentseldate);
                                        var d2 = new Date();
                                        var monthd2 = d2.getMonth() + 1;
                                        var dayd2 = d2.getDate();

                                        var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                        d2 = new Date(outputd2);
                                        var differInTime = Math.abs(d2 - d1);
                                        var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                        if (differDays <= 1) {
                                            newbtndisable = '';
                                            if (data[i].visit_report_id != null && data[i].visit_report_id != "") {

                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                editbutton = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                            }
                                        }
                                    }

                                }

                                if ($('#hiddenRole_id').val() != 2) {
                                    $('#SelBranch').val($('#HospitalBranchID').val());
                                }

                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                Engage = '<div class="btn-group">' + editbutton
                                    // + '<a type="button" href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                    + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + P_status + ''
                                    + '<ul class="dropdown-menu"><li  ' + btndisable + '><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li>'
                                    //+'<a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li ' + btndisable + '>'
                                    //+'<a  href="#" style="display:none;" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="procedure" data-toggle="tooltip" data-original-title="Procedure"><i class="fa fa-tasks fa-lg"></i><span>Procedure</span></a></li><li ' + btndisable + '>'
                                    + '<a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Diet Plan" data-toggle="tooltip" data-original-title="Diet Plan"><i class="fa fa-male fa-lg"></i><span>Diet Plan</span></a>'
                                    + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                    //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                    //+ '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                    + '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\",\"' + data[i].prescription_page_style + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                   //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                    + '<li><a href=/BillingMaster/index?visit_report_id=' + data[i].visit_report_id + '&patientid=' + data[i].patient_id + '&branch_id=' + data[i].branch_id + '&entity=' + data[i].is_entity + '&type=1&insurance=' + data[i].is_insurance + '&multipay=' + data[i].is_pay + ' title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                    + '</ul></div>'

                                delivery = '<a ' + btndisable + ' href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now </a>';
                            }
                                //no show
                            else {
                                Engage = '<span class="pull-left">No Show</span>';
                                //color = '<i class="fa fa-minus-circle below_average" aria-hidden="true"></i>';
                                color = '<small class="label label-danger">No Show</small>';
                            }
                            if (data[i].visit_report_id != '' && data[i].visit_report_id != null) {
                                if (data[i].total_amount == null || data[i].total_amount == '' && data[i].total_amount != 0) {
                                    //balance = '';
                                    //bal = '<span class="">-</span>';
                                }
                                else {
                                    //balance = '<span class="f12">Balance: <i class="fa fa-inr"></i>' + data[i].balance_amount + '</span>';
                                    //var bal_amt = parseFloat(data[i].total_amount) - parseFloat(data[i].balance_amount);

                                    delivery = '<a href="javascript:void(0)" data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a>';
                                    var invoice_print = '<span onclick=invoiceprint(\"' + data[i].visit_report_id + '\");><i class="fa fa-print fa-lg" title="Invoice Print" data-toggle="tooltip" data-original-title="Invoice Print"></i></span>';

                                    //if (data[i].total_amount > data[i].balance_amount && data[i].balance_amount != 0) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save-orange hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                    //else if (data[i].total_amount == data[i].balance_amount) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' +data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn btn-submit btn-xs">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                    //else {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' +data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' +data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                }
                            }
                            else {
                                if (data[i].online_invoice_status == 3) {
                                    //balance = '';
                                    //bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">Paid online</span> &nbsp;';
                                }
                            }

                            var app_type = '';
                            var doctor_pharmacy_id = data[i].pharmacy_id;
                            var pharmacy_id = doctor_pharmacy_id;
                            if (pharmacy_id == '') {
                                delivery = '-';
                            }
                            var doctor_patient_id = '', recentvisits, noofvisits;
                            if (data[i].recent_visit == '' || data[i].recent_visit == null || data[i].recent_visit == '0') recentvisits = '-';
                            else recentvisits = data[i].recent_visit + ' days ago';

                            if (data[i].no_of_visits == "" || data[i].no_of_visits == null || data[i].no_of_visits == "0") noofvisits = '-';
                            else noofvisits = data[i].no_of_visits;

                            var toatl_no_recent_visit = noofvisits + '|' + recentvisits;

                            if (data[i].doctor_patient_id != '' && data[i].doctor_patient_id) {
                                doctor_patient_id = ' | ' + data[i].doctor_patient_id;
                            }

                            app_details = '';
                            var watchicon = "";

                            var walkin = '<i class="fas fa-walking mr-20" style="color:black;font-size:14px;" title="Walkin"></i>',
                                video_call = '<span class="v-icon mr-20"><i class="fa fa-video-camera" aria-hidden="true" title="Video Call"></i></span>',
                                sms = '<i class="fas fa-sms icon-design mr-20" style="color:blue;font-size:14px;" title="Chat Consultation"></i>',

                                mobile_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Patient App"></i>',
                                inclinic = '<i class="fas fa-clinic-medical mr-20" style="color:blue;font-size:14px;" title="Booked In Clinic"></i>',
                                chatbot = '<i class="fa fa-comment-o icon-design mr-20" style="color:#006400;font-size:14px;" title="Chatbot"></i>',
                                doctor_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Doctor App"></i>',

                                package_app = '<i class="fa fa-shield icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Booked from package Coupon"></i>',
                                pay_after = '<i class="fa fa-inr icon-design mr-20" style="color:#f39c12;font-size:14px;" title="Pay after consultation"></i>',
                                prepaid = '<i class="fa fa-inr icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Paid via Mobile App"></i>',
                                doc_collect = '<i class="fas fa-rupee-sign mr-20" style="color:red;font-size:14px;" title="Doctor To Collect Payment"></i>',

                                vip_patient = '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>',
                                watch_patient = '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:14px;" title="Watch List"></i>';

                            if (data[i].source_of_booking == "1") app_details = app_details + inclinic;
                            else if (data[i].source_of_booking == "2") app_details = app_details + mobile_app;
                            else if (data[i].source_of_booking == "3") app_details = app_details + doctor_app;
                            else if (data[i].source_of_booking == "4") app_details = app_details + chatbot;
                            else app_details = app_details;

                            if (data[i].appointment_type == 1) app_details = app_details + walkin;
                            else if (data[i].appointment_type == 2) app_details = app_details + video_call;
                            else app_details = app_details + sms;

                            if (data[i].payment_mode == "1") app_details = app_details + package_app;
                            else if (data[i].payment_mode == "2") app_details = app_details + prepaid;
                            else if (data[i].payment_mode == "3") app_details = app_details + pay_after;
                            else app_details = app_details + doc_collect;

                            if (data[i].vip_description != null && data[i].vip_status == "1") watchicon = vip_patient;

                            var watchlist_end_date = new Date(data[i].watchlist_end_date);
                            var currentdate = new Date(data[i].currentdate);

                            if (watchlist_end_date >= currentdate && data[i].watchlist_status == "1") app_details = app_details + watch_patient;
                            app_details = app_details + bill
                            app_details = '<td class="align-middle">' + app_details + '</td>';

                            var due_status = ''
                            if (data[i].total_due_amount > 0) {
                                due_status = 'Due'
                            }

                            if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                   // case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;"  onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                else {
                                    //case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                              }
                                tr = tr + '<tr class="view"><td class="hidden"></td><td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td class="opensub" class="tbsno o details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                     + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td>' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'                                  
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    + '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'


                            }
                            else {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    //case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this)\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                else {
                                    //case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                    case_form = '<a data-toggle="modal" style="cursor: pointer;"  onclick=\'billing_details(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + due_status + '\",this,\"' + data[i].visit_report_id + '\",\"' + data[i].appointment_type + '\")\'><span class="patientname">' + data[i].patient_first_name + '</span></a>'

                                }
                                tr = tr + '<tr class="view"><td class="hidden"></td><td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\")\';><span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td class="tbsno opensub details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\")\';><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                    + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td class="opensub">' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'                                    
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    + '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'
                            }
                        }
                        $('#data_table_appointment tbody').empty();

                        $('#data_table_appointment').dataTable().fnClearTable();

                        $('#data_table_appointment').dataTable().fnDestroy();

                        $('#data_table_appointment tbody').append(tr);

                        //$(".fold-table tr.view .opensub").on("click", function () {
                        //    $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
                        //});
                        //$('.dataTables_length').addClass('bs-select');
                        $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                        $('#data_table_appointment').DataTable();
                        // $('[rel=popover]').popover();
                        $('#docappdetails').show();
                    }
                    else {
                        $('#data_table_appointment').DataTable().destroy();
                        $('#data_table_appointment tbody').empty();
                        //
                        //var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                        //$('#data_table_appointment tbody').append(tr1);
                        //$('#data_table_appointment tbody ').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
                        $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                        ////if ($('#hiddenRole_id').val() == 1)
                        ////{
                        // $('#data_table_appointment').DataTable();
                        ////  }
                        $('#docappdetails').show();
                    }

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

            LoadReviewAppointmentList();
            // LoadReferredPatientsList();
        }
    });
}
function LoadAppointmentRequest(id) {
    debugger;
    //$('#HiddenDoctorID').val(id),
    //$('#Hbranch_id').val(branch_id)
    ////id = $('#SelDoctor_div').val($('#HiddenDoctorID').val()),
    //id = $('#SelDoctor').val($('#HiddenDoctorID').val()),
    //branch_id= $('#SelBranch').val($('#Hbranch_id').val())

    //if (id != '' || branch_id != '') {
    //    //$('#SelBranch').attr('disabled', true);
    //    //$('#SelDoctor').attr('disabled', true);
    //}
    //if (branch_id != null || branch_id != '' || branch_id != 0)
    //{
    //    LoadBranch(id, branch_id);
    //}
    $('#data_table_appointment tbody').empty();

    //$('#data_table_appointment').dataTable().fnClearTable();

    //$('#data_table_appointment').DataTable().destroy();
    console.log('id---' + id);
    if (id == "" || id == null) {
        $('#SelDoctor_div').hide();
        $('#SelBranch_div').hide();
    }
    else {
        $('#SelDoctor').val(id);
        $('#myschedule').show();
        var role_id = $('#hiddenRole_id').val();
        if (role_id == 1 || role_id == 5) {
            $('#SelDoctor_div').hide();
            $('#SelBranch_div').hide();
        }
        else {
            if ($('#referredpatients_tab_list').attr('aria-expanded') != "true") {
                $('#SelBranch_div').show();
                $('#SelDoctor_div').show();
            }
        }
        $('#UM_5,#data_table_appointment').show();
        $('html, body').animate({
            scrollTop: $("#data_table_appointment").offset().top
        }, 1000)
    }

    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    }
    else {
        btndisable = 'style="display:none";';
    }
    $('#data_table_appointment').addClass('us-db-loader-appoinments');
    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    var branch_id = $('#SelBranch').val();
    if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {

    }
    else {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
        branch_id = (branch_id == null || branch_id == "") ? $('#HospitalBranchID').val() : branch_id;
    }
    var Performers = {
        doctor_id: DoctorId,
        AppointmentDate: date,
        User_role: role_id,
        Dml_Indicator: "AS",
        branch_id: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            $('#mobilcardappointment').empty();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

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

                    var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    $('#data_table_appointment tbody').append(tr1);
                    //$('#data_table_appointment tbody').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');               
                    $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                }
                else {
                    console.log(data);

                    var tr = '', mtr = '', vtr = '', vdtr = '';
                    if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {



                            var patient_photo = data[i].patient_photo;
                            $('#lab_id').val(data[0].lab_id);
                            $('#lab_data_flag').val(data[0].data_flag);
                            var WaitingTime = 0;
                            if (data[i].check_status > 1) {
                                var checkin_timeminutes = (data[i].checkin_timeminutes);
                                var checkout_timeminutes = (data[i].checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (data[i].check_status == null || data[i].check_status == '') {
                                WaitingTime = '-';
                            }
                            else {
                                var checkin_timeminutes = data[i].checkin_timeminutes;
                                var CurrentTime = data[i].CurrentTime;
                                WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")
                                var WaitingTimes = WaitingTime.split(':');
                                WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                            }
                            var EngagedTime = data[i].enage_time;
                            if (EngagedTime == null || EngagedTime == '') {
                                EngagedTime = '-';
                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';
                            }
                            var photo = '';
                            var delivery = '-';
                            var photoSrc;
                            var PatientPhoto = $('#patphotop').val();
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            var color = '';
                            if ((data[i].doctor_appointment_slot_status == 1 || data[i].doctor_appointment_slot_status == 7) && data[i].pcheckin_timeminutes == null) {
                                color = '';
                            }
                            else {
                                //color = '<i class="fa fa-check-circle above_average" aria-hidden="true"></i>';
                                color = '<small class="label label-success">Completed</small>'
                            }
                            var checkin = '';
                            var Engage = '';
                            var MEngage_1 = '';
                            var MEngage_2 = '';
                            var Decline = '';
                            var noshow = '', balance = '', labtest = '', bal = '-', smslink = '-', reschedule = '';
                            var P_status = ''; var EngageStatus = '';

                            if (data[i].Status == 1) {
                                P_status = '<a><span class="label label-success">PAID</span></a>'
                            }
                            else if (data[i].Status == 2) {
                                P_status = '<a><span class="label label-warning">PARTIAL</span></a>'
                            }
                            else if (data[i].Status == 5) {
                                P_status = '<a><span class="label label-danger">PENDING</span></a>'
                            }
                            else if (data[i].Status == 3) {
                                P_status = '<a><span class="label label-danger">Due</span></a>'
                            }

                            if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                EngageStatus = P_status;
                            }

                            var bill = '', color1 = '', duebillno = '', edit_bill = '';
                            if (data[i].billno != null) {
                                var s1 = data[i].billno.split(',');

                                for (var p = 0; p < s1.length; p++) {
                                    var amount = '';
                                    var s2 = s1[p].split('/');
                                    if (parseFloat($.trim(s2[2])) > 0) {
                                        color1 = 'red';
                                        amount = $.trim(s2[2]);
                                        if (duebillno == '') {
                                            duebillno = $.trim(s2[0]);
                                        }
                                    }
                                    else {
                                        color1 = 'green'
                                        amount = $.trim(s2[1]);
                                    }

                                    bill = bill + '<i class="fa fa-print mr-20" style="color:' + color1 + ';font-size:14px;" title="Bill preview" onclick=\'bill_preview(' + $.trim(s2[0]) + ',' + data[i].patientid + ',' + data[i].hospitalid + ',' + data[i].branch_id + ',1)\'>' + amount + '</i>'
                                }
                            }
                            if (data[i].edit_bill != 0) {
                                edit_bill = '<li><a href="/BillingMaster/index?billingno=' + data[i].edit_bill + '&branch_id=' + data[i].branch_id + '&visit_report_id=' + data[i].visit_report_id + '&discount_edit_val=1"  title="Edit Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Edit Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Edit Bill</span></a></li>'
                            }
                            var duebillpayment = '';
                            if (duebillno != '') {
                                duebillpayment = '<li><a href=/BillingMaster/billing_receipt?Billing_no=' + duebillno + ' title="Due Payment" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Due Payment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Due Payment</span></a></li>';
                            }

                            //checkin status
                            if (data[i].check_status == '' || data[i].check_status == null) {                            

                                checkin = '<button type="button" ' + btndisable + ' class="btn btn-primaryuse btn-xs btn-flat mr-20" onclick=checkin("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].status_bill + '","' + data[i].IsBillCheckIn + '");>Check In</button>';
                                noshow = '<a href="javascript:void(0);" id="" onclick=NoShow("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '") class="mr-5" title="noshow" data-trigger="hover" data-toggle="tooltip" data-original-title="no show"><i class="fa fa-eye-slash fa-sm"></i></a>'
                                Decline = '<a href="javascript:void(0);" onclick=Decline("' + data[i].patient_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].coupon_id + '") class="mr-5" title="Decline Appointment" data-trigger="hover" data-toggle="tooltip" data-original-title="Decline Appointment"><i class="fa fa-ban fa-sm"></i></a>'
                                reschedule = '<a href="javascript:void(0);" ' + btndisable + ' onclick=\'reschedule(\"' + data[i].patient_id + '\",\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].branch_id + '\",' + data[i].appointment_type + ')\' class="mr-5" title="Reschedule" data-trigger="hover" data-toggle="tooltip" data-original-title="Reschedule"><i class="fa fa-refresh fa-sm"></i></a>'
                            }

                            else if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                var redirect = '';
                                //var redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    redirect = '/Casestudy/Indexformbuilder?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;

                                }
                                else {
                                    redirect = '/Casestudy?patient_id=' + data[i].patient_id + '&slotdate=' + data[i].slot_start_time + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
                                }
                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\", \"' + data[i].age + '\", \"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                if (data[i].appointment_type == 2) {
                                    Engage = '<div class="btn-group"><a type="button" ' + btndisable + ' class="btn btn-submit btn-xs btn-flat mr-20" onclick=\'videocallcheck(\"' + data[i].patient_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].appointment_type + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].balance_amount + '\", \"' + data[i].payment_mode + '\",\"' + data[i].doctor_id + '\",\"' + data[i].due_amount + '\",\"' + data[i].totalbills + '\")\';><i class="fa fa-video-camera"></i> Video Call</a>'
                                        + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu">'
                                       //-- //<li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li>'
                                        //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment + '</li>'
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                       + '</ul></div>';
                                    smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
                                }
                                else {
                                    Engage = '<div class="btn-group">'
                                        //+ '<a type="button" ' + btndisable + ' href="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Engage</div></a>'
                                        + '<a type="button" ' + btndisable + ' data-name="' + redirect + '" class="btn btn-submit btn-xs btn-flat mr-20 btn_r" data-id="CAS_AF" data-type="role_rights_function" data-nav="redirect" ><div>Engage</div></a>'
                                        + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle mr-20" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + EngageStatus + ''
                                        + '<ul class="dropdown-menu"><li><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry " data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li>'
                                        //+'<li><a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li>'
                                        //+'<li><a href="#" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Order Lab Test " data-toggle="tooltip" data-original-title="Order Lab Test "><i class="fa fa-tasks fa-lg"></i><span>Procedure </span></a></li>'
                                        + '<li><a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Add Diet Plan " data-toggle="tooltip" data-original-title="Add Diet Plan "><i class="fa fa-male fa-lg"></i><span>Add Diet Plan </span></a>'
                                        +'<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                        //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                        + '<li><a href="javascript:void(0);" onclick=\'quickbill(\"' + data[i].visit_report_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].branch_id + '\",\"' + data[i].is_entity + '\",\"' + data[i].is_insurance + '\",\"' + data[i].doctor_id + '\",\"' + data[i].is_pay + '\",\"' + data[i].slot_start_time + '\")\'; title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                        + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                        + '</li>'
                                        // + '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                        + '</ul></div>';
                                }

                            }
                            else if (data[i].check_status == 2 || data[i].check_status == 4) {
                                Engage = '<span class="pull-left">Engaged</span>';

                                var newbtndisable = btndisable;
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        if (data[i].visit_report_id != null && data[i].visit_report_id != "") {
                                            var d1 = new Date(currentseldate);
                                            var d2 = new Date();
                                            var monthd2 = d2.getMonth() + 1;
                                            var dayd2 = d2.getDate();

                                            var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                            d2 = new Date(outputd2);
                                            var differInTime = Math.abs(d2 - d1);
                                            var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                            if (differDays <= 1) {
                                                newbtndisable = '';
                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                Engage = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                                //Engage = '<a type="button" ' + newbtndisable + ' href="/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'

                                            }
                                        }
                                    }

                                }

                            }

                            else if (data[i].check_status == 3 || data[i].check_status == 5 || data[i].doctor_appointment_slot_status == 4) {
                                var newbtndisable = btndisable;
                                var editbutton = ''
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';

                                }
                                else {
                                    editbutton = '<a type="button" ' + btndisable + ' href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&branchid=' + data[i].branch_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>';
                                }
                                // Edit casesheet button enable for 48 hours
                                if (date == output) {
                                    newbtndisable = '';
                                }
                                else {
                                    if (data[i].enable_previous_casesheet_edit == 1 || data[i].enable_previous_casesheet_edit == "1") {
                                        var d1 = new Date(currentseldate);
                                        var d2 = new Date();
                                        var monthd2 = d2.getMonth() + 1;
                                        var dayd2 = d2.getDate();

                                        var outputd2 = (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day + '/' + d2.getFullYear();
                                        d2 = new Date(outputd2);
                                        var differInTime = Math.abs(d2 - d1);
                                        var differDays = Math.ceil((differInTime / (1000 * 3600 * 24)));
                                        if (differDays <= 1) {
                                            newbtndisable = '';
                                            if (data[i].visit_report_id != null && data[i].visit_report_id != "") {

                                                var Form_redirect = '';
                                                if (parseInt($('#HFormbuilder_id').val()) == 1) {

                                                    Form_redirect = '/Casestudy/Indexformbuilder?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                else {
                                                    Form_redirect = '/Casestudy?VisitReport=' + data[i].visit_report_id + '&patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '&appointment_type=' + data[i].appointment_type + '&PharmacyID=' + $('#pharmacy_id').val() + '&branchid=' + data[i].branch_id;
                                                }
                                                editbutton = '<a type="button" ' + newbtndisable + ' href="' + Form_redirect + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                            }
                                        }
                                    }

                                }

                                if ($('#hiddenRole_id').val() != 2) {
                                    $('#SelBranch').val($('#HospitalBranchID').val());
                                }

                                labtest = '<li class="lt-db"><a ' + btndisable + ' data-toggle="modal" data-target="#lab_details"  data-backdrop="static" data-keyboard="false" onclick=\'full_lab_test(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].doctor_id + '\")\';  title="lab Test" data-trigger="hover" data-toggle="tooltip" ><i class="fa fa-flask fa-lg"></i><span>lab test</span></a></li>';
                                Engage = '<div class="btn-group">' + editbutton
                                     // + '<a type="button" href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '" class="btn btn-submit btn-xs btn-flat mr-20"><div>Edit </div></a>'
                                     + '<button type="button" class="btn btn-primaryuse btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-info-circle 2x"></i><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button>' + P_status + ''
                                     + '<ul class="dropdown-menu"><li  ' + btndisable + '><a href="javascript:void(0);" data-toggle="modal" data-target="#quickentry" data-backdrop="static" data-keyboard="false" onclick=\'quickentry(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Vitals Entry" data-toggle="tooltip" data-original-title="Vitals Entry"><i class="fa fa-pencil-square-o fa-lg"></i><span>Vitals Entry</span></a></li><li>'
                                    // +'<a href="javascript:void(0)" data-toggle="modal" data-target="#AddVisitAttachment" data-backdrop="static" data-keyboard="false" onclick=\'AddVisitAttachment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Add Attachment" data-toggle="tooltip" data-original-title="Add Attachment"><i class="fa fa-pencil-square-o fa-lg"></i><span>Add Attachment</span></a></li><li ' + btndisable + '>'
                                     //+'<a  href="#" style="display:none;" data-toggle="modal" data-target="#us_procedure"  data-backdrop="static" data-keyboard="false" onclick=\'procedure(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="procedure" data-toggle="tooltip" data-original-title="Procedure"><i class="fa fa-tasks fa-lg"></i><span>Procedure</span></a></li><li ' + btndisable + '>'
                                     + '<a href="#" data-toggle="modal" data-target="#dietplanDashboard"  data-backdrop="static" data-keyboard="false" onclick=\'DeitPlan(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].visit_report_id + '\")\'; class="hm-dt-action edit" title="Diet Plan" data-toggle="tooltip" data-original-title="Diet Plan"><i class="fa fa-male fa-lg"></i><span>Diet Plan</span></a>'
                                     + '<a href="#" data-toggle="modal" data-target="#modal-cs-prescri"  data-backdrop="static" data-keyboard="false" onclick=\'Prescription_click(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].doctor_user_designation + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\",\"' + data[i].Pat_branch_id + '\")\'; class="hm-dt-action edit" title="Prescription" data-toggle="tooltip" data-original-title="Prescription"><i class="fa fa-file-text-o  fa-lg"></i><span>Prescription</span></a></li></li><li ' + btndisable + '>'
                                     //+ '<a href="#" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="hm-dt-action edit" title="Payment" data-toggle="tooltip" data-original-title="Wallet"><i class="fa fa-money fa-lg"></i><span>Payment</span></a>'
                                   //  + '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                   + '</li><li><a href="javascript:void(0);" id="" class="hm-dt-action"  onclick=\'printprescriptionpdf(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patientid + '\",\"' + data[i].hospitalid + '\",\"' + data[i].branch_id + '\",\"' + data[i].doctor_name + '\",\"' + data[i].hospital_name + '\",\"' + data[i].patient_phone_number + '\",\"' + data[i].email_id + '\",\"' + data[i].prescription_page_style + '\")\'; title="Prescription Print" data-toggle="tooltip" data-original-title="Prescription Print"><i class="fa fa-print fa-lg"></i><span>Prescription Print</span></a></li>'
                                  //+ '<li><a href="#"  onclick=\'files_appointment(\"' + data[i].doctor_appointment_slot_id + '\")\'; class="hm-dt-action edit" title="Appointment Files " data-toggle="modal" data-target="#appointment_files" data-backdrop="static" data-keyboard="false" data-original-title="Appointment Files "><i class="fa fa-file-text-o  fa-lg"></i><span>Appointment Files </span></a></li>'
                                     + '<li><a href=/BillingMaster/index?visit_report_id=' + data[i].visit_report_id + '&patientid=' + data[i].patient_id + '&branch_id=' + data[i].branch_id + '&entity=' + data[i].is_entity + '&type=1&insurance=' + data[i].is_insurance + '&multipay=' + data[i].is_pay + ' title="Quick Bill" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Quick Bill"><i class="fa fa-pencil-square-o fa-lg"></i><span>Quick Bill</span></a></li>' + edit_bill + '' + duebillpayment
                                         + '<li><a href="javascript:void(0);" onclick=\'Forms(\"' + data[i].visit_report_id + '\",\"' + data[i].visit_reportid + '\",\"' + data[i].patient_id + '\",\"' + data[i].patientid + '\","' + data[i].doctor_id + '","' + data[i].doctor_appointment_slot_id + '","' + data[i].branch_id + '")\';  title="Forms" class="hm-dt-action edit" data-toggle="tooltip" data-original-title="Forms"><i class="fa fa-pencil-square-o fa-lg"></i><span>Forms</span></a></li>' + '</li>'
                                     + '</ul></div>'

                                delivery = '<a ' + btndisable + ' href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now </a>';
                            }
                            //no show
                            else {
                                Engage = '<span class="pull-left">No Show</span>';
                                //color = '<i class="fa fa-minus-circle below_average" aria-hidden="true"></i>';
                                color = '<small class="label label-danger">No Show</small>';
                            }
                            if (data[i].visit_report_id != '' && data[i].visit_report_id != null) {
                                if (data[i].total_amount == null || data[i].total_amount == '' && data[i].total_amount != 0) {
                                    //balance = '';
                                    //bal = '<span class="">-</span>';
                                }
                                else {
                                    //balance = '<span class="f12">Balance: <i class="fa fa-inr"></i>' + data[i].balance_amount + '</span>';
                                    //var bal_amt = parseFloat(data[i].total_amount) - parseFloat(data[i].balance_amount);

                                    delivery = '<a href="javascript:void(0)" data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a>';
                                    var invoice_print = '<span onclick=invoiceprint(\"' + data[i].visit_report_id + '\");><i class="fa fa-print fa-lg" title="Invoice Print" data-toggle="tooltip" data-original-title="Invoice Print"></i></span>';

                                    //if (data[i].total_amount > data[i].balance_amount && data[i].balance_amount != 0) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save-orange hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                    //else if (data[i].total_amount == data[i].balance_amount) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' +data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn btn-submit btn-xs">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                    //else {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' +data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' +data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print;
                                    //}
                                }
                            }
                            else {
                                if (data[i].online_invoice_status == 3) {
                                    //balance = '';
                                    //bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">Paid online</span> &nbsp;';
                                }
                            }

                            var app_type = '';
                            var doctor_pharmacy_id = data[i].pharmacy_id;
                            var pharmacy_id = doctor_pharmacy_id;
                            if (pharmacy_id == '') {
                                delivery = '-';
                            }
                            var doctor_patient_id = '', recentvisits, noofvisits;
                            if (data[i].recent_visit == '' || data[i].recent_visit == null || data[i].recent_visit == '0') recentvisits = '-';
                            else recentvisits = data[i].recent_visit + ' days ago';

                            if (data[i].no_of_visits == "" || data[i].no_of_visits == null || data[i].no_of_visits == "0") noofvisits = '-';
                            else noofvisits = data[i].no_of_visits;

                            var toatl_no_recent_visit = noofvisits + '|' + recentvisits;

                            if (data[i].doctor_patient_id != '' && data[i].doctor_patient_id) {
                                doctor_patient_id = ' | ' + data[i].doctor_patient_id;
                            }

                            app_details = '';
                            var watchicon = "";

                            var walkin = '<i class="fas fa-walking mr-20" style="color:black;font-size:14px;" title="Walkin"></i>',
                                video_call = '<span class="v-icon mr-20"><i class="fa fa-video-camera" aria-hidden="true" title="Video Call"></i></span>',
                                sms = '<i class="fas fa-sms icon-design mr-20" style="color:blue;font-size:14px;" title="Chat Consultation"></i>',

                                mobile_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Patient App"></i>',
                                inclinic = '<i class="fas fa-clinic-medical mr-20" style="color:blue;font-size:14px;" title="Booked In Clinic"></i>',
                                chatbot = '<i class="fa fa-comment-o icon-design mr-20" style="color:#006400;font-size:14px;" title="Chatbot"></i>',
                                doctor_app = '<i class="fa fa-mobile icon-design mr-20" style="color:blue;font-size:14px;" title="Booked From Doctor App"></i>',

                                package_app = '<i class="fa fa-shield icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Booked from package Coupon"></i>',
                                pay_after = '<i class="fa fa-inr icon-design mr-20" style="color:#f39c12;font-size:14px;" title="Pay after consultation"></i>',
                                prepaid = '<i class="fa fa-inr icon-design mr-20" style="color:#00a65a;font-size:14px;" title="Paid via Mobile App"></i>',
                                doc_collect = '<i class="fas fa-rupee-sign mr-20" style="color:red;font-size:14px;" title="Doctor To Collect Payment"></i>',

                                vip_patient = '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>',
                                watch_patient = '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:14px;" title="Watch List"></i>';

                            if (data[i].source_of_booking == "1") app_details = app_details + inclinic;
                            else if (data[i].source_of_booking == "2") app_details = app_details + mobile_app;
                            else if (data[i].source_of_booking == "3") app_details = app_details + doctor_app;
                            else if (data[i].source_of_booking == "4") app_details = app_details + chatbot;
                            else app_details = app_details;

                            if (data[i].appointment_type == 1) app_details = app_details + walkin;
                            else if (data[i].appointment_type == 2) app_details = app_details + video_call;
                            else app_details = app_details + sms;

                            if (data[i].payment_mode == "1") app_details = app_details + package_app;
                            else if (data[i].payment_mode == "2") app_details = app_details + prepaid;
                            else if (data[i].payment_mode == "3") app_details = app_details + pay_after;
                            else app_details = app_details + doc_collect;

                            if (data[i].vip_description != null && data[i].vip_status == "1") watchicon = vip_patient;

                            var watchlist_end_date = new Date(data[i].watchlist_end_date);
                            var currentdate = new Date(data[i].currentdate);

                            if (watchlist_end_date >= currentdate && data[i].watchlist_status == "1") app_details = app_details + watch_patient;
                            app_details = app_details + bill
                            app_details = '<td class="align-middle">' + app_details + '</td>';


                            if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                }
                                else {
                                    case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                }
                                tr = tr + '<tr class="view"><td class="hidden"></td><td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td class="opensub" class="tbsno o details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                     + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td>' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'                           
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    + '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'


                            }
                            else {
                                var case_form = '';
                                if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                    case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                }
                                else {
                                    case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                                }
                                tr = tr + '<tr class="view"><td class="hidden"></td><td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\")\';><span class="mr-10">' + (i + 1) + '</span>' + color + '</td><td class="tbsno opensub details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\")\';><span class="appoinment-time">' + data[i].appointment_time + ':' + data[i].appointment_minutes + ' ' + app_type + '</span></td>'
                                    + '<td class="align-middle">' + data[i].branch_name + '</td>'
                                    + '<td class="opensub">' + case_form + watchicon + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span><span class="ml-5">|<span class="doctorpatientid ml-5">' + ((data[i].doctor_patient_id != null && data[i].doctor_patient_id != "null" && data[i].doctor_patient_id != "") ? data[i].doctor_patient_id : '-') + '</span></td>'
                                    + app_details
                                    + '<td class="align-middle tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><span class="doctorname">' + data[i].doctor_name + '</span></td>'
                                    + '<td class="align-middle">' + data[i].referred_doctor_name + '</td>'
                                    + '<td class="align-middle">' + checkin + Engage + Decline + noshow + reschedule + '</td>'
                                    + '<td class="tbsno  details-control" onclick=\'view_more_details(\"' + data[i].doctor_appointment_slot_id + '\",\"' + data[i].patient_id + '\",\"' + data[i].doctor_id + '\",\"demo_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr>'
                                //+ '<tr class="fold" id=demo_' + (i + 1) + '></tr>'
                            }
                        }
                        $('#data_table_appointment tbody').empty();

                        $('#data_table_appointment').dataTable().fnClearTable();

                        $('#data_table_appointment').dataTable().fnDestroy();

                        $('#data_table_appointment tbody').append(tr);

                        //$(".fold-table tr.view .opensub").on("click", function () {
                        //    $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
                        //});
                        //$('.dataTables_length').addClass('bs-select');
                        $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                        $('#data_table_appointment').DataTable();
                        // $('[rel=popover]').popover();
                        $('#docappdetails').show();
                    }
                    else {
                        $('#data_table_appointment').DataTable().destroy();
                        $('#data_table_appointment tbody').empty();
                        //
                        //var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                        //$('#data_table_appointment tbody').append(tr1);
                        //$('#data_table_appointment tbody ').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
                        $('#data_table_appointment tbody').removeClass('us-db-loader-appoinments');
                        ////if ($('#hiddenRole_id').val() == 1)
                        ////{
                        // $('#data_table_appointment').DataTable();
                        ////  }
                        $('#docappdetails').show();
                    }

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

            LoadReviewAppointmentList();
            // LoadReferredPatientsList();
        }
    });
}


function quickbill(visit_report_id, patient_id, branch_id, is_entity, is_insurance, doctor_id, is_pay, slot_start_time) {
    debugger;
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);

    if (visit_report_id != null && visit_report_id != "null" && visit_report_id != "") {
        window.location.href = '/BillingMaster/index?visit_report_id=' + visit_report_id + '&patientid=' + patient_id + '&branch_id=' + branch_id + '&entity=' + is_entity + '&type=1&insurance=' + is_insurance + '&multipay=' + is_pay + '&doctorid=' + $('#pop_doctor_id').val();
    }
    else {
        var VisitreportId = {
            Patient_id: $('#Hdnpatient_id').val(),
            slotTime: $('#Hdnappointment_date').val(),
            doctor_id: $('#pop_doctor_id').val(),
            Dml_Indicator: '15'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CaseStudy',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(VisitreportId),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {

                        if (data.Table.length > 0) {
                            var VisitReportID = (data.Table[0].VisitReport_id);
                            $('#VisitReportID').val(VisitReportID);
                            window.location.href = '/BillingMaster/index?visit_report_id=' + $('#VisitReportID').val() + '&patientid=' + patient_id + '&branch_id=' + branch_id + '&entity=' + is_entity + '&type=1&insurance=' + is_insurance + '&multipay=' + is_pay + '&doctorid=' + $('#pop_doctor_id').val();
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }

}

function printprescriptionpdf(visit_report_id, visitid, patientid, hospitalid, branchid, doctorname, hospitalname, phone_number, email_id, prescription_page_style) {
    // if ($('#HCasesheetPrintType').val() == 0) {
    if (prescription_page_style != "8") {
        window.location.href = '/PatientDashboard/PPDF?visitreportid=' + visit_report_id + '&lantype=1&btnval=1';
    }
    else {
        //var load_data = {
        //    formid: "137",
        //    branchid: branchid,
        //    hospitalid: hospitalid,
        //    patientid: patientid,
        //    visit_reportid: visitid
        //}
        //$.ajax({
        //    async: true,
        //    type: 'POST',
        //    url: '/reports/PrintCrystalReport',
        //    contentType: 'application/json; charset=UTF-8',
        //    data: JSON.stringify(load_data),
        //    success: function (data) {
        //        debugger;

        //        var byteArray = new Uint8Array(data);
        //        var blob = new Blob([byteArray], { type: "application/pdf" });
        //        var link = window.URL.createObjectURL(blob);
        //        window.open(link, '_blank');

        //    }
        //});

        var load_data = {
            formid: '137',
            branchid: branchid,
            hospitalid: hospitalid,
            patientid: patientid,
            visit_reportid: visitid,
            doctorname: doctorname,
            hospital_name: hospitalname,
            phone_number: phone_number,
            email_id: email_id
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/reports/SetPrescriptionReportParameters',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(load_data),
            success: function (data) {
                window.open('/Webform/PrescriptionPrint.aspx', '_blank');
            }
        });
    }
}



function bill_preview(bill_no, patientid, hospitalid, branch_id, visittype) {
    debugger;
    var load_data = {
        indicator_id: "LRD",
        ReportId: (visittype == 2 ? "19" : "65")
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/Hospital_Reports',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var ReportName = ''; var reportparameters = "";
                    if (data1.Table[0] != null) {
                        ReportName = data1.Table[0].report_form_name;
                        var dml_indicator = data1.Table[0].dml_indicator;
                        reportparameters = data1.Table[0].report_parameters_list;

                        $('#iframeHeader').html(ReportName);

                        var fromdate = ''; var todate = '';
                        if ($('#txtfrom_date').val() != null && $('#txtfrom_date').val() != "") {
                            var fromdate = $('#txtfrom_date').val();
                            var a = fromdate.split('/');
                            fromdate = a[2] + '-' + a[1] + '-' + a[0];
                        }

                        if ($('#txtto_date').val() != null && $('#txtto_date').val() != "") {
                            var todate = $('#txtto_date').val();
                            var a = todate.split('/');
                            todate = a[2] + '-' + a[1] + '-' + a[0];

                        }

                        var load_data = {
                            dmlind: dml_indicator,
                            report_name: ReportName,
                            branchid: branch_id,
                            hospitalid: hospitalid,
                            patientid: patientid,
                            billno: bill_no,
                            reportparameters: reportparameters,
                            fromdate: fromdate,
                            todate: todate

                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/reports/SetReportParameters',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(load_data),
                            success: function (data) {
                                $('#iframepopup').modal('toggle');
                                $('#dvReport').html('<iframe src="/Webform/WebForm1.aspx" id="dvLoadingReport" style="width: 100%;min-height: 450px; max-height: 450px; overflow: auto;"></iframe>');
                            }
                        });
                    }
                }
            }
            else {
                console.log(data2);
            }
        }
    });
}





// added by nandhini on 09/08/2022
// --------------Review Appointment Tab List  Start --------------------------
function LoadReviewAppointmentList() {
    debugger;

    var date = '';
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    //$('#Hidden_appointment_date').val(date)

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {

    }
    else {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
    }
    $('#tblReviewVisitList tbody').addClass('us-db-loader-appoinments');

    var Performers = {
        doctor_id: DoctorId,
        AppointmentDate: date,
        User_role: role_id,
        Dml_Indicator: "RS",
        branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                    $('#tblReviewVisitList tbody').empty();
                    var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    $('#tblReviewVisitList tbody').append(tr1);
                    $('#tblReviewVisitList tbody').removeClass('us-db-loader-appoinments');
                }
                else {
                    if (data.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data.length; i++) {

                            $('#Hidden_doctor_id').val(data[i].doctor_id);
                            $('#Hidden_next_appointment_date').val(data[i].next_appointment_date);
                            $('#Hidden_appointment_id').val(data[i].appointment_id);

                            var appointment_status = "";
                            var btnaction = '-';

                            if (data[i].appointment_id != null && data[i].appointment_id != "") {
                                appointment_status = '<span class="label label-success" style="border-radius: 9px;background: white;color: green;">Booked</span>'
                            }
                            else {
                                appointment_status = '<span class="label label-danger">Not Booked Yet</span>';
                                btnaction = '<a class="btn btn-xs label-used" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + data[i].patient_id + '&PName=\'' + data[i].patient_first_name + '\'&Did=' + data[i].doctor_id + '&appdate=' + data[i].next_appointment_date + '&BId=' + $('#SelBranch').val() + '">Book an Appointment</a>'
                                    + '<br /><button class="btn btn-xs edit_label mt10" data-toggle="modal" data-target="#change-review-date" onclick=\'PatientReviewDetails(\"' + data[i].patient_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].next_appointment_date + '\")\'>Change Review Date</button></td>';

                            }
                            var case_form = ''
                            if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                            }
                            else {
                                case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + data[i].patient_id + '&Did=' + data[i].doctor_id + '"><span class="patientname">' + data[i].patient_first_name + '</span></a>'
                            }
                            tr = tr + '<tr class="db-table-bg-heading"><td>' + (i + 1) + '</td><td>' + case_form + '<span class="ml-5">|</span><span class="patientid ml-5">' + data[i].patient_id + '</span></td>'
                                + '<td>' + data[i].last_visit_date + '</td><td>' + data[i].doctor_name + '</td><td>' + appointment_status + '</td>'
                                + '<td><div class="col-md-12 padding0"><div class="">' + btnaction + '</tr>'
                        }

                        //$('#tblReviewVisitList tbody').removeClass('us-db-loader-appoinments');
                        //$('#tblReviewVisitList tbody').empty();

                        //$('#tblReviewVisitList tbody').append(tr);

                        //$('#tblReviewVisitList').DataTable().destroy();
                        //$('#tblReviewVisitList').DataTable();


                        $('#tblReviewVisitList tbody').removeClass('us-db-loader-appoinments');
                        $('#tblReviewVisitList tbody').empty();


                        $('#tblReviewVisitList tbody').append(tr);

                        $('#tblReviewVisitList').DataTable().fnClearTable();
                        $('#tblReviewVisitList').DataTable().fnDraw();
                        $('#tblReviewVisitList').DataTable().fndestroy();
                        $('#tblReviewVisitList').DataTable();
                    }
                    else {
                        $('#tblReviewVisitList tbody').empty();
                        var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                        $('#tblReviewVisitList tbody').append(tr1);
                        $('#tblReviewVisitList tbody').removeClass('us-db-loader-appoinments');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

}

function PatientReviewDetails(patient_id, visit_report_id, next_appointment_date) {
    PatientSearch(patient_id, '1', $('#SelBranch').val(), visit_report_id);
    $('#nextappointmentdate').val(next_appointment_date);
    $('#VisitReportID').val(visit_report_id);
}

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

    var cdate = '';
    if ($('#nextappointmentdate').val() != '' && $('#nextappointmentdate').val() != null) {
        var sdate = $('#nextappointmentdate').val().split('/');
        cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
    }

    var create_visit_report = {
        Dml_Indicator: 'RAD',
        visit_report_id: $('#VisitReportID').val(),
        next_appointment_date: cdate,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/VisitReport_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(create_visit_report),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    toastr.success('Review Date Changed Successfully');
                    LoadReviewAppointmentList();
                    $('#btnCloseReviewPopUp').click();
                }
            }
            else {
                console.log(data);
            }
        }
    });
});

// --------------Review Appointment Tab List  End --------------------------

// ----------Referred Patients Tab List Start -----------------

function LoadReferredPatientsList(indicator) {
    debugger;

    var date = '';
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    if ($('#SelDoctor').val() == 0 || $('#SelDoctor').val() == null) {

    }
    else {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
    }
    $('#tblReferredPatientsList tbody').addClass('us-db-loader-appoinments');

    var indicator_id = 'S', reffered_by_to_doctor_id = ''
    if (indicator != '' && indicator != undefined) {
        indicator_id = indicator
    }

    var doctor_id = $('#referal_SelDoctor').val()
    var ref_to_doctor_id = $('#referal_to_SelDoctor').val()
    var referal_branchid = $('#referal_SelBranch').val()

    var hidden_doctor_id = '';

    if ($('#hiddenRole_id').val() != 1) {
        hidden_doctor_id = doctor_id
    }
    else {
        hidden_doctor_id = $('#myHiddenVar').val()
    }

    var Performers = {
        //doctor_id: DoctorId,
        doctor_id: hidden_doctor_id,
        referred_to_doctor_id: ref_to_doctor_id,
        referred_date: date,
        //Dml_Indicator: "S"
        Dml_Indicator: indicator_id,
        branch_id: referal_branchid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Doctor_Referral_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                    $('#tblReferredPatientsList tbody').empty();
                    var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    $('#tblReferredPatientsList tbody').append(tr1);
                    $('#tblReferredPatientsList tbody').removeClass('us-db-loader-appoinments');
                }
                else {
                    if (data.Table.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data.Table.length; i++) {

                            var appointment_status = "";
                            var btnaction = '-';

                            if (data.Table[i].visit_typeid == 1) {
                                if (data.Table[i].referal_id_count > 0) {
                                    appointment_status = '<span class="label label-success" style="border-radius: 9px;background: white;color: green;">Booked</span>'
                                }
                                else {
                                    appointment_status = '<span class="label label-danger">Not Booked Yet</span>';
                                    if ($('#hiddenRole_id').val() != 1) {
                                        //  btnaction = '<a class="btn btn-xs label-used" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + data.Table[i].patient_id + '&PName=\'' + data.Table[i].patient_name + '\'&Did=' + data.Table[i].referred_to_doctor_id + '&appdate=' + data.Table[i].next_appointment_date + '&BId=' + $('#SelBranch').val() + '&Refered_to_doctorid=' + data.Table[i].referred_by_doctorid + '&referal_id=' + data.Table[i].doctor_referral_id + '">Book an Appointment</a>'
                                        btnaction = '<a class="btn btn-xs label-used" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + data.Table[i].patient_id + '&PName=\'' + data.Table[i].patient_name + '\'&Did=' + data.Table[i].referred_to_doctor_id + '&appdate=' + data.Table[i].next_appointment_date + '&BId=' + data.Table[i].branch_id + '&Refered_to_doctorid=' + data.Table[i].referred_by_doctorid + '&referal_id=' + data.Table[i].doctor_referral_id + '">Book an Appointment</a>'
                                    }
                                }
                            }

                            tr = tr + '<tr class="db-table-bg-heading"><td>' + (i + 1) + '</td><td><span class="patientname">' + data.Table[i].patient_name + '</span></a><span class="ml-5">|</span><span class="patientid ml-5">' + data.Table[i].patient_id + '</span></td>'
                                + '<td>' + data.Table[i].referred_date_time + '</td><td style="display:none;">' + data.Table[i].doctor_name + '</td><td>' + data.Table[i].referred_by + '</td><td>' + data.Table[i].referred_to_doctor + '</td><td>' + data.Table[i].visit_type + '</td><td>' + appointment_status + '</td>'
                                //+ '</tr>'
                                + '<td><div class="col-md-12 padding0"><div class="">' + btnaction + '</tr>'
                        }

                        $('#tblReferredPatientsList tbody').removeClass('us-db-loader-appoinments');
                        $('#tblReferredPatientsList tbody').empty();
                        $('#tblReferredPatientsList').dataTable().fnClearTable();
                        $('#tblReferredPatientsList').dataTable().fnDraw();
                        $('#tblReferredPatientsList').dataTable().fnDestroy();
                        $('#tblReferredPatientsList tbody').append(tr);

                        //$('#tblReferredPatientsList').DataTable().destroy();

                        $('#tblReferredPatientsList').DataTable();
                    }
                    else {
                        $('#tblReferredPatientsList tbody').empty();
                        var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div></td></tr>';
                        $('#tblReferredPatientsList tbody').append(tr1);
                        $('#tblReferredPatientsList tbody').removeClass('us-db-loader-appoinments');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

}

// ---------Referred Patients Tab List End

function files_appointment(slot_id) {
    var data = {
        doctor_appointment_slot_id: slot_id,
        Dml_Indicator: "AF"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Appointment_Files',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {

            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    console.log(data);
                    if (data.Table[0].Files != '' && data.Table[0].Files != null) {
                        $('#health_concern').html(data.Table[0].health_concern);
                    }
                    else {
                        $('#health_concern').html("    -");
                    }
                    $('#tblAppointmentFiles_body').empty();
                    if (data.Table[0].Files != '' && data.Table[0].Files != null) {
                        var files = data.Table[0].Files.split("&&");

                        var file_tr = '', k = 1;
                        for (var i = 0; i < files.length; i++) {
                            console.log(files[i]);

                            var d, n, drloimage;
                            d = new Date();
                            n = d.getTime();
                            var file = $('#hdnHomeCareFilesView').val() + "HomeCareFiles/ParvathyFiles/" + files[i] + "?" + n;
                            file_tr = file_tr + '<tr><td>' + k + '</td><td><a href = ' + file + ' target=_blank> File </a></td></tr>';

                            k = k + 1;
                        }
                        $('#tblAppointmentFiles_body').html(file_tr);


                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function expandAll() {
    $(".opensub").click();
}
function view_more_details(slot_id, patient_id, doctorId, rowid, e) {
    debugger;
    var tr = e.closest('tr');
    var row = $('#data_table_appointment').DataTable().row(tr);
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(view_more(slot_id, patient_id, doctorId, rowid)).show();
        tr.addClass('shown');
    }
}

function view_more(slot_id, patient_id, doctorId, rowid) {
    debugger;
    div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');


    div.removeClass('loading')
    var tr, row_data, service_status = '-';
    tr = $('<table class="table table-condensed body-borderless table_borderless">');
    if ($('#hpharmstatus').val() == 0 && $('#hpharmvisit').val() == 37) {
        debugger;
        tr.append('<thead><tr><th>Waiting | Engage Time</th><th>Recent Visit</th><th>SMS</th></tr></thead><tbody>');
    }
    else {
        tr.append('<thead><tr><th>Waiting | Engage Time</th><th>Recent Visit</th><th>Medicine Order</th><th>SMS</th></tr></thead><tbody>');
    }
    var date = '';
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('.app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    }
    else {
        btndisable = 'style="display:none";';
    }

    var Performers = {
        doctor_id: doctorId,
        patient_id: patient_id,
        doctor_appointment_slot_id: slot_id,
        Dml_Indicator: "MAS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Performers),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {


                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var photoSrc;
                            var patient_photo = data[i].patient_photo;
                            var PatientPhoto = $('#patphotop').val();
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            var WaitingTime = 0;
                            if (data[i].check_status > 1) {
                                var checkin_timeminutes = (data[i].checkin_timeminutes);
                                var checkout_timeminutes = (data[i].checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (data[i].check_status == null || data[i].check_status == '') {
                                WaitingTime = '-';
                            }
                            else {
                                var checkin_timeminutes = data[i].checkin_timeminutes;
                                var CurrentTime = data[i].CurrentTime;
                                WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")
                                var WaitingTimes = WaitingTime.split(':');
                                WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                            }
                            var EngagedTime = data[i].enage_time;
                            if (EngagedTime == null || EngagedTime == '') {
                                EngagedTime = '-';
                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';
                            }

                            var delivery = '-';

                            var balance = '', labtest = '', bal = '-', smslink = '-';

                            if (data[i].check_status == 1 && data[i].doctor_appointment_slot_status != 4) {
                                if (data[i].appointment_type == 2) {
                                    smslink = '<a href="javascript:void(0);" onclick=\'smslinkfun(\"' + data[i].patient_phone_number + '\",\"' + data[i].patient_first_name + '\")\';>Inform Delay</a>'
                                }

                            }

                            else if (data[i].check_status == 3 || data[i].check_status == 5 || data[i].doctor_appointment_slot_status == 4) {
                                delivery = '<a ' + btndisable + ' href="javascript:void(0)"  data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now </a>';
                            }

                            if (data[i].visit_report_id != '' && data[i].visit_report_id != null) {
                                if (data[i].total_amount == null || data[i].total_amount == '' && data[i].total_amount != 0) {
                                    balance = '';
                                    //bal = '<span class="">-</span>';
                                }
                                else {
                                    //balance = '<span class="f12">Balance: <i class="fa fa-inr"></i>' + data[i].balance_amount + '</span>';
                                    //var bal_amt = parseFloat(data[i].total_amount) - parseFloat(data[i].balance_amount);

                                    delivery = '<a href="javascript:void(0)" data-toggle="modal" data-target="#order-Popup" data-backdrop="static" data-keyboard="true" class="btn btn-primaryuse btn-xs us-db-pkup-pup" onclick=pickup("' + data[i].visit_report_id + '","' + data[i].patient_id + '")>Order Now</a>';
                                    var invoice_print = '<span onclick=invoiceprint(\"' + data[i].visit_report_id + '\");><i class="fa fa-print fa-lg" title="Invoice Print" data-toggle="tooltip" data-original-title="Invoice Print"></i></span>';
                                    var email = '<span data-toggle="modal" data-target="#email_Popup"><i class="fa fa-envelope" title="Email"  data-toggle="tooltip" data-original-title="Email" style="font-size:18px"></i></span>';

                                    //if (data[i].total_amount > data[i].balance_amount && data[i].balance_amount != 0) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save-orange hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print + "&nbsp" + email;
                                    //}
                                    //else if (data[i].total_amount == data[i].balance_amount) {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn btn-submit btn-xs">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print + "&nbsp" + email;
                                    //}
                                    //else {
                                    //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">&#8377;  ' + data[i].total_amount + '</span> &nbsp;' + invoice_print + "&nbsp" + email;
                                    //}
                                }
                            }
                            else {
                                //if (data[i].online_invoice_status == 3) {
                                //    balance = '';
                                //    bal = '<span data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#collectPayment" onclick=\'collectpayment(\"' + data[i].patient_id + '\",\"' + data[i].patient_first_name + '\",\"' + data[i].patient_phone_number + '\",\"' + photoSrc + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].slot_start_time + '\",\"' + data[i].doctor_id + '\",\"' + data[i].age + '\",\"' + data[i].gender + '\")\'; class="btn-default btn btn-save hm-dt-btn">Paid online</span> &nbsp;';
                                //}
                            }

                            var doctor_pharmacy_id = data[i].pharmacy_id;
                            var pharmacy_id = doctor_pharmacy_id;
                            if (pharmacy_id == '') {
                                delivery = '-';
                            }
                            var doctor_patient_id = '', recentvisits, noofvisits;
                            if (data[i].recent_visit == '' || data[i].recent_visit == null || data[i].recent_visit == '0') recentvisits = '-';
                            else recentvisits = data[i].recent_visit + ' days ago';

                            if (data[i].no_of_visits == "" || data[i].no_of_visits == null || data[i].no_of_visits == "0") noofvisits = '-';
                            else noofvisits = data[i].no_of_visits;

                            var toatl_no_recent_visit = noofvisits + '|' + recentvisits;

                        }
                        if ($('#hpharmstatus').val() == 0 && $('#hpharmvisit').val() == 37) {
                            debugger;
                            row_data = '<tr><td>' + WaitingTime + ' | ' + EngagedTime + '</td><td>' + toatl_no_recent_visit + '</td><td>' + smslink + '</td></tr>'
                        }
                        else {
                            row_data = '<tr><td>' + WaitingTime + ' | ' + EngagedTime + '</td><td>' + toatl_no_recent_visit + '</td><td>' + delivery + '</td><td>' + smslink + '</td></tr>'
                        }

                        //var tr = '<td colspan="7"><div class="row"><div class="col-md-12"><div class="col-sm-2"><div class="form-group"><p class="sub-heading">Waiting | Engage Time</p><p>' + WaitingTime + ' | ' + EngagedTime + '</p></div></div><div class="col-sm-2"><div class="form-group"><p class="sub-heading">Recent Visit</p><p>' + toatl_no_recent_visit + '</p></div></div>'
                        ////+ '<div class="col-sm-3"><div class="form-group"><p class="sub-heading">Payment</p><p>' + bal + '</p></div></div>'
                        //+ '<div class="col-sm-3"><div class="form-group"><p class="sub-heading">Medicine Order</p><p>' + delivery + '</p></div></div><div class="col-sm-2"><div class="form-group"><p class="sub-heading">SMS</p><p>' + smslink + '</p></div></div></div></div></td>';
                        // row_data = '<tr><td>' + WaitingTime + ' | ' + EngagedTime + '</td><td>' + toatl_no_recent_visit + '</td><td>' + delivery + '</td><td>' + smslink + '</td></tr>'
                        //$('#' + rowid).html(tr);
                        tr.append(row_data);
                        tr.append("</tbody>");

                        div.append(tr);
                    }


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

    return div;
}

function videocallcheck(patient_id, slot_start_time, appointment_type, visit_report_id, balance_amount, payment_mode, doctor_id, due_amount, totalbills) {
    if (payment_mode == "1" || payment_mode == "2") {   // mobile prepaid
        window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
    }
    else if (payment_mode == "3" && (due_amount == "0.00" || due_amount == 0)) {  //mobile payafter
        if (confirm("The payment for this invoice in still not received. Do you want to start the consultation ?")) {
            window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
        }
        else {
        }
    }
    else if (payment_mode == "3" && due_amount != "0.00") {
        window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
    }
    else if (visit_report_id == "" || visit_report_id == null || visit_report_id == "null") {
        if (confirm("The invoice for this appointment is not generated, do you want to proceed?")) {
            window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
        }
        else {
        }
    }
    else if (visit_report_id != null && totalbills != 0) {
        if (confirm("The payment for this invoice in still not received. Do you want to start the consultation ?")) {
            window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
        }
        else {
        }
    }
    else {
        window.location.href = '/Casestudy/Indexformbuilder?patient_id=' + patient_id + '&slotdate=' + slot_start_time + '&Did=' + doctor_id + '&appointment_type=' + appointment_type + '&PharmacyID=' + $('#pharmacy_id').val();
    }
}

function changedefault(e) {
    var photoSrc = "/Content/img/profile_icon.png";
    console.log("Image Error")
    $(e).attr("src", photoSrc)
}

function HomeDelivery(visit_report_id, patient_id, did_not_purchase) {
    if (confirm('The order will be made has Home delivery. Request the patient to complete the order in the mobile app')) {
        var didnot = {
            visit_report_id: visit_report_id,
            pharmacy_id: $('#pharmacy_id').val(),
            patient_id: patient_id,
            doctor_id: $('#HiddenDoctorID').val(),
            did_not_purchase: did_not_purchase
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/notpurchase',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(didnot),
            success: function (data) {
                console.log(data);
                console.log(data.status);
                console.log(data.medicine_order_id);
                var data = JSON.parse(data);
                if (data.msg == "Success") {


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

                    }
                    else {

                        if (data.result.length > 0) {
                            if (data.result[0] = "Success") {
                                $('.close').click();
                            }
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        });

    } else {

        toastr.warning('Please Confirm before clicking Cancel Button');
    }
}

function pickupDelivery(visit_report_id, patient_id, did_not_purchase) {
    var didnot = {
        visit_report_id: visit_report_id,
        pharmacy_id: $('#pharmacy_id').val(),
        patient_id: patient_id,
        doctor_id: $('#HiddenDoctorID').val(),
        did_not_purchase: did_not_purchase
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/set_notpurchase',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(didnot),
        success: function (data) {
            console.log(data);
            console.log(data.status);
            console.log(data.medicine_order_id);
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.result.length > 0) {
                        if (data.result[0] = "Success") {
                            $('.close').click();
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function pickup(visit_report_id, patient_id) {

    $('#O_visit_report_id').val(visit_report_id);
    $('#O_patient_id').val(patient_id);
    var checkin = {
        visit_report_id: visit_report_id,
        Dml_Indicator: 'S',
        product_code: $('#HProductCode').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/pharmacy_order_now',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(checkin),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#btnpickup').hide();
                    $('#btnordernow').hide();
                    $('#tblorder').hide();
                    $('#btnorder').hide();
                    toastr.warning('medicine not prescribed for current visit');
                    $('.colse').click();
                }
                else {

                    if (data.Table.length > 0) {
                        if (data.Table[0].did_not_purchase == null || data.Table[0].did_not_purchase == '') {
                            $('#btnpickup').show();
                            $('#btnordernow').show();
                            $('#tblorder').hide();
                            $('#btnorder').hide();
                            $('#gobacktopickup').hide();

                        }
                        else if (data.Table[0].did_not_purchase == 5) {
                            $('#btnpickup').hide();
                            $('#btnordernow').hide();
                            $('#tblorder').show();
                            $('#gobacktopickup').show();
                            $('#btnorder').hide();
                        }
                        else {
                            $('#btnpickup').hide();
                            $('#btnordernow').hide();
                            $('#tblorder').hide();
                            $('#gobacktopickup').hide();
                            $('#btnorder').hide();
                        }
                        var tr = '';
                        var j = 0;
                        $('#tblorder_body').html('');
                        for (var i = 0; i < data.Table.length; i++) {
                            j++;

                            tr = '<tr><td>' + data.Table[i].medicine_prescription_id + '</td><td>' + data.Table[i].medicine_type + ' ' + data.Table[i].medicine_name + '</td><td>' + data.Table[i].max_quantity + '</td><td><input id=req_val_' + j + ' type="text"/></td></tr>';
                            var request_quantity = data.Table[i].request_quantity;
                            var id = 'req_val_' + j;
                            $('#tblorder_body').append(tr);
                            $('#' + id).val(request_quantity);
                        }

                    }
                    else {
                        $('#btnpickup').hide();
                        $('#btnordernow').hide();
                        $('#tblorder').hide();
                        $('#gobacktopickup').hide();
                        $('#btnorder').hide();
                        toastr.warning('medicine not prescribed for current visit');
                        $('.close').click();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#btnpickup').click(function () {
    $('#tblorder').show();
    $('#tblorder').show();
    $('#btnorder').show();
    $('#btnpickup').hide();
    $('#btnordernow').hide();
    $('#gobacktopickup').show();
});

$('#btnordernow').click(function () {
    var did_not_purchase = 2;
    HomeDelivery($('#O_visit_report_id').val(), $('#O_patient_id').val(), did_not_purchase);
});

$('#gobacktopickup').click(function () {
    $('#tblorder').hide();
    $('#tblorder').hide();
    $('#btnorder').hide();
    $('#btnpickup').show();
    $('#btnordernow').show();
    $('#gobacktopickup').hide();
});

$('#btnorder').click(function () {
    var j = 0, k = 0;
    var rowCount = $('#laborderjob_body tr').length;
    $('#tblorder_body tr').each(function () {
        j++;
        var $row = jQuery(this).closest('tr');
        var $columns = $row.find('td');
        var values = "";
        jQuery.each($columns, function (i, item) {
            ptsID = $(this).parent("tr").find("td:first").text();
        });
        var med_val = {
            medicine_prescription_id: ptsID,
            request_quantity: $('#req_val_' + j).val(),
            pharmacy_id: $('#pharmacy_id').val(),
            updated_by: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'I'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/pharmacy_order_now',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(med_val),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        if (rowCount == k) {
                            setTimeout(function () {
                                var did_not_purchase = 5;
                                pickupDelivery($('#O_visit_report_id').val(), $('#O_patient_id').val(), did_not_purchase);
                                toastr.warning('Please collect medicine(s) in the pharmacy');
                                $('.close').click();
                            }, 3000);
                        }
                        k++;
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    });
});

function invoiceprint(visit_report_id) {
    window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&doctorId=' + $('#HiddenDoctorID').val() + '&indicator=NP' + '&btnval=1', "_blank");
}



function checkin(patient, slotId, btncheckinbill,is_billchk) {
    debugger;
    if (btncheckinbill == 0 && is_billchk == 1) {
        toastr.warning('Please Pay Bill')
    }
else{
    var DoctorId = $('#myHiddenVar').val();
    var checkindata = {
        check_by: DoctorId,
        check_staus: '1',
        patient_id: patient,
        doctor_appointment_slot_id: slotId,
        Dml_Indicator: 'SCI'

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(checkindata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
               // CheckFormRights(patient,92,1,2)
                LoadAppointmentRequest();
            }
            else {
                console.log(data);
            }
        }
    });
}
}


function Decline(patient, slotId, couponid) {
    //toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button>", 'You Need to decline the appointment ?',

    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button>", 'You Need to decline the appointment ?',
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    $('#hdn_patientid').val(patient);
                    $('#hdn_slotid').val(slotId);
                    $('#hdn_couponid').val(couponid);
                    $('#appointmentdecline').modal("show")

                });

            }
        });

}

$("#btn_reason_submit").click(function () {
    debugger;
    declinereason();
})
function declinereason() {
    debugger;
    var checkindata = {
        coupon_id: $('#hdn_couponid').val(),
        patient_id: $('#hdn_patientid').val(),
        doctor_appointment_slot_id: $('#hdn_slotid').val(),
        Reason: $('#decline_reason_txt').val(),
        Dml_Indicator: 'D'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(checkindata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    LoadAppointmentRequest();
                    Appointmentlist();
                    location.reload();
                }
                else {
                    console.log(data);
                    if (data[0].msg == "failure") {
                        toastr.warning("Patient already visited");
                    }
                    else {

                        toastr.success("Appointment decline Successfully");
                        setTimeout(function () {
                            location.reload();
                        }, 1000);

                        LoadAppointmentRequest();
                        Appointmentlist();
                        location.reload();
                    }

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

}


function NoShow(patient, slotId) {
    debugger;
    if (confirm("Are you sure you want to make no show for this appointment?")) {
        var checkindata = {
            patient_id: patient,
            doctor_appointment_slot_id: slotId,
            Dml_Indicator: 'NS'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/Patient_checkin',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(checkindata),
            success: function (data) {
                debugger;

                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                        LoadAppointmentRequest();
                        Appointmentlist();
                        location.reload();
                    }
                    else {


                        if (data[0].msg == "failure") {
                            toastr.warning("Patient already visited");
                        }
                        else {
                            LoadAppointmentRequest();
                            Appointmentlist();
                            location.reload();
                        }

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

function LoadPaitentsTrend() {

    var PaitentsTrend = {
        Dml_Indicator: 1,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $('.da-load-graph').show();
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/PaitentsTrend',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (datas) {
            // LoadAppointmentday();  //load function
            var data = JSON.parse(datas);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    var Oldlabel = [];

                    var PaitentsTrend = {
                        Dml_Indicator: 2,
                        doctor_id: $('#HiddenDoctorID').val()
                    }

                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Dashboard/PaitentsTrend',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(PaitentsTrend),
                        success: function (datass) {
                            var data11 = JSON.parse(datass);
                            if (data11.msg == "Success") {
                                var data1 = data11.data;
                                if (jQuery.isEmptyObject((data1))) {
                                    $('.divcanvas').removeClass('da-load-pp-wl-vip-ma');
                                }
                                else {


                                    for (var i = 0; i < data1.length; i++) {
                                        Oldlabel.push(data1[i].total);
                                    }
                                    //var data1 = JSON.parse(datas);
                                    var gFdata = [], value, label, labelname = [];
                                    var DateValue;
                                    for (var i = 0; i < data1.length; i++) {
                                        gFdata.push(data1[i].total);
                                        labelname.push(data1[i].month);
                                    }
                                    var barPercentage = 1;
                                    if (data1.length < 4) {
                                        barPercentage = .25;
                                    }
                                    else if (data1.length < 7) {
                                        barPercentage = .50;
                                    }
                                    else if (data1.length < 10) {
                                        barPercentage = .75;
                                    }
                                    else {
                                    }
                                    var chartColors = {
                                        red: 'rgb(255, 99, 132)',
                                        redfade: 'rgba(255, 99, 132,0.5)',
                                        orange: 'rgb(255, 159, 64)',
                                        yellow: 'rgb(255, 205, 86)',
                                        green: 'rgb(75, 192, 192)',
                                        blue: 'rgb(54, 162, 235)',
                                        greenfade: 'rgba(75, 192, 192,0.8)',
                                        bluefade: 'rgba(54, 162, 235,0.4)',
                                        purple: 'rgb(153, 102, 255)',
                                        grey: 'rgb(231,233,237)',
                                        greyfade: 'rgba(231,233,237,0.7)',
                                        violet: 'rgb(76, 68, 255)',
                                        white: 'rgb(255, 255, 255)',
                                        whitefade: 'rgba(255, 255, 255,0.7)',
                                        newgreen: '#BED630',
                                        newblue: '#0266B3'
                                    };
                                    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                                    var config = {
                                        type: 'bar',
                                        data: {
                                            type: 'column',
                                            labels: labelname,
                                            //click: onClick,

                                            datasets: [{
                                                label: "New Patients",
                                                backgroundColor: chartColors.newgreen,
                                                borderColor: chartColors.newgreen,
                                                data: gFdata,
                                            }, {
                                                label: "Follow-up patients",
                                                backgroundColor: chartColors.newblue,
                                                borderColor: chartColors.newblue,
                                                data: Oldlabel,
                                            }]
                                        },
                                        options: {
                                            responsive: true,
                                            tooltips: {
                                                mode: 'label',
                                            },
                                            legend: {
                                                display: false,
                                            },

                                            responsive: true,

                                            scales: {
                                                xAxes: [{
                                                    stacked: true,
                                                    display: true,
                                                    barPercentage: barPercentage,
                                                    scaleLabel: {
                                                        display: true,
                                                        labelString: 'Month',
                                                        fontSize: 9,
                                                        // 
                                                    },
                                                    ticks: {
                                                        fontSize: 9,
                                                        fontColor: "#222"
                                                    },
                                                    gridLines: {
                                                        display: false,
                                                        color: '#aaa'
                                                    }
                                                }],
                                                yAxes: [{
                                                    stacked: true,
                                                    display: true,
                                                    scaleLabel: {
                                                        display: false,
                                                        labelString: 'Value',
                                                        fontSize: 9
                                                    },
                                                    ticks: {
                                                        fontSize: 9,
                                                        beginAtZero: true,
                                                        fontColor: "#222"
                                                    },
                                                    gridLines: {
                                                        display: false,
                                                        color: '#aaa'
                                                    }
                                                }]
                                            }
                                        }
                                    };
                                    var ctx = document.getElementById("canvas").getContext("2d");
                                    window.myLine = new Chart(ctx, config);
                                    $('.da-load-graph').hide();
                                    $('.divcanvas').removeClass('da-load-pp-wl-vip-ma');

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

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

function loadwatchlist() {
    var PaitentsVip = {
        Dml_Indicator: 'W',
        doctor_id: $('#HiddenDoctorID').val()
    }

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

                $('#sortable1').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
                $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');

            }
            else {
                console.log(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.length > 0) {
                        var tr = '';
                        for (var i = 0; i < data.length; i++) {
                            var name = data[i].first_name;
                            var phone_number = data[i].phone_number_1;
                            var photo = data[i].photo;
                            var Fasting_blood_sugar = data[i].Fasting_blood_sugar;
                            var Postprandial_blood_sugar = data[i].Postprandial_blood_sugar;
                            var bp_max = data[i].bp_max;
                            var bp_min = data[i].bp_min;
                            var last_updated = data[i].created_on;
                            var patientId = data[i].patient_id;
                            var photoSrc = '';
                            var PatientPhoto = $('#patphotop').val();
                            var remaining_days = data[i].remaining_days;
                            var sugar = '', bp = '';
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            if (bp_max == '' || bp_max == null) {
                                bp_max = '';
                            }

                            if (bp_min == '' || bp_min == null) {
                                bp_min = '';
                            }
                            if (bp_max != '' && bp_min != '') {

                            }
                            if (bp_min != '' && bp_max != '') {
                                bp = 'SYS ' + bp_max + '/ DIA ' + bp_min + ' mmHg';
                            }
                            else if (bp_min != '') {
                                bp = 'DIA ' + bp_min + ' mmHg';
                            }
                            else if (bp_max != '') {
                                bp = 'SYS ' + bp_max + ' mmHg';
                            }
                            else {
                                bp = '';
                            }



                            if (Fasting_blood_sugar == '' || Fasting_blood_sugar == null) {
                                Fasting_blood_sugar = '';
                            }
                            if (Postprandial_blood_sugar == '' || Postprandial_blood_sugar == null) {
                                Postprandial_blood_sugar = '';
                            }
                            if (Fasting_blood_sugar != '' && Postprandial_blood_sugar != '') {
                                sugar = 'FBS ' + Fasting_blood_sugar + '/ PBS ' + Postprandial_blood_sugar + ' mg/dL ';
                            }
                            else if (Fasting_blood_sugar != '') {
                                sugar = 'FBS ' + Fasting_blood_sugar + ' mg/dL ';
                            }
                            else if (Postprandial_blood_sugar != '') {
                                sugar = 'PBS ' + Postprandial_blood_sugar + ' mg/dL '
                            }
                            else {
                                sugar = '';
                            }
                            //tr = tr + '<div class="row item search-boxa lchild"><div class="li-inner-row"><div class="col-md-2 pad0 lir-img"><span class="pull-left lir-drag"><i class=" fa fa-bars colormt20 f18"> &nbsp;</i></span> <img class="prof_imgblock" width="40" src="' + photoSrc + '"></div><div class="col-md-5 pad0 lir-name"><a href="/casestudy/CaseStudyView?patient_id=' + patientId + '">' + name + ' </a><br /><span class="lir-mobile"><i class="fa fa-phone" aria-hidden="true"></i> ' + phone_number + ' </span></div><div class="col-md-4 pad0 lir-data"><a tabindex="0"class=""data-html="true"data-toggle="popover"data-placement="bottom"data-trigger="hover"title="<span class=\'text-center\'>Last Updated<br><strong>' + last_updated + '</strong></span>"><span class=" pull-left lir-data1">' + sugar + '</span><br><span class=" pull-left lir-data2">' + bp + ' </span></a></div><div class="col-md-1 pull-right pad0 colormt20 lir-options"><div tabindex="0"class=""data-html="true"data-toggle="popover"data-placement="left"data-trigger="click"data-content="<div class=\'list-group\'><div class=\'list-group-item\'><span onclick=watchlistDel(' + data[i].watch_id + ')><i class=\'fa fa-trash\'></i> Delete</span></div><div class=\'list-group-item\'><select class=\'form-control\'><option value=\'0\'>Move To</option><option value=\'1\'>Low</option><option value=\'2\'>Medium</option><option value=\'3\'>High</option></select></div><div class=\'list-group-item\'><span>Settings</span></div></div>"><span><i class="fa fa-circle"></i><i class="fa fa-circle"></i><i class="fa fa-circle"></i></span></div></div></div></div>';
                            //tr = tr + '<div class="row item search-boxa lchild"><div class="li-inner-row"><div class="col-md-2 pad0 lir-img"><span class="pull-left lir-drag"><i class=" fa fa-bars colormt20 f18"> &nbsp;</i></span> <img class="prof_imgblock" width="40" src="' + photoSrc + '"></div><div class="col-md-5 pad0 lir-name"><a href="/casestudy/CaseStudyView?patient_id=' + patientId + '">' + name + ' </a><br /><span class="lir-mobile"><i class="fa fa-phone" aria-hidden="true"></i> ' + phone_number + ' </span></div><div class="col-md-4 pad0 lir-data"><a tabindex="0"class=""data-html="true"data-toggle="popover"data-placement="bottom"data-trigger="hover"title="<span class=\'text-center\'>Last Updated<br><strong>' + last_updated + '</strong></span>"><span class=" pull-left lir-data1">' + sugar + ' </span><br><span class=" pull-left lir-data2">' + bp + ' </span></a></div><div class="col-md-1 pull-right pad0 colormt20 lir-options"><div tabindex="0"class=""><div class="wldropdown_sec text-right"><span><i class="fa fa-circle"></i><i class="fa fa-circle"></i><i class="fa fa-circle"></i></span><div class="wldropdown_content"><div class=\'list-group-item\'><span onclick=watchlistDel(this) watchid=' + data[i].watch_id + ' patientid=' + data[i].patient_id + '  ><i class=\'fa fa-trash\'></i> Delete</span></div><input type="hidden" id="name_' + patientId + '" value="' + name + '"/><div class=\'list-group-item\'><span href=\'#myPatientDashModal\' role=\'button\' class=\'m25\' data-toggle=\'modal\' onclick=watchlsedit("' + patientId + '","' + phone_number + '","' + data[i].dob + '","' + data[i].age + '","' + data[i].gender + '");><i class=\'fa fa-pencil\'></i> Edit</span></div></div></div></div></div></div></div>';
                            tr = tr + '<div class="col-md-12 wt-style"><div class="col-md-4"><div class="modal-intro-content"><div class="row waitlist-content"> <div class="profile-img"> <img class="img-responsive" src="' + photoSrc + '" alt="Patient Image"></div><div class="pat-det mt15"><p class="PatientName">' + name + '</p><p class="Patientpno"><i class="fa fa-phone" aria-hidden="true">&nbsp;&nbsp;</i>' + phone_number + '</p></div></div></div></div><div class="col-md-6"><div class="pat-msg mt15"><p>Patient Will be removed from the watchlist in next <strong>' + remaining_days + ' days</strong></p></div></div><div class="col-md-2 mt20"><button class="btn addicon-btn btn-sm"><i class="fa fa-pencil" href=\'#myPatientDashModal\' role=\'button\' class=\'m25\' data-toggle=\'modal\' onclick=watchlsedit("' + patientId + '","' + phone_number + '","' + data[i].dob + '","' + data[i].age + '","' + data[i].gender + '","' + data[i].first_name + '"); aria-hidden="true"></i></button></a><button class="btn deleteicon-btn btn-sm"><i class="fa fa-trash" onclick=watchlistDel(this) watchid=' + data[i].watch_id + ' patientid=' + data[i].patient_id + ' aria-hidden="true"></i></button></a></div></div>'
                        }
                        $('#sortable1').html(tr);
                        $("[data-toggle=popover]").popover();
                        $('.da-load-watchlist').hide();
                        $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');

                    }
                    else {
                        $('#sortable1').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ><br><div class="no_data_content">No data found.</div></div>');
                        $('.da-load-watchlist').hide();
                        $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}
function loadvip() {
    var PaitentsVip = {
        Dml_Indicator: 'V',
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/PatientWatchlistDash',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsVip),
        success: function (datas) {
            var data = JSON.parse(datas);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    //console.log("no data found VIP");
                }
                else {

                    console.log(data);
                    var a = '';
                    var tr = "";
                    for (var i = 0; i < data.length; i++) {
                        var name = data[i].first_name;
                        var phone_number = data[i].phone_number_1;
                        var next_visit = data[i].next_visit;
                        var last_visit = data[i].last_visit;
                        var photo = data[i].photo;
                        var last_updated = data[i].last_updated;
                        var patientId = data[i].patient_id;
                        var vipdescription = data[i].description;
                        var photoSrc = '';
                        var PatientPhoto = $('#patphotop').val();
                        if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                            photoSrc = PtImage;
                        }
                        if (next_visit == '' || next_visit == null) {
                            next_visit = ' - ';
                        }
                        if (last_visit == '' || last_visit == null) {
                            last_visit = ' - ';
                        }
                        tr = tr + '<div class="col-md-12 wt-style"><div class="col-md-5 col-sm-5"><div class="modal-intro-content"><div class="row waitlist-content"><div class="profile-img"><img class="img-responsive" src="' + photoSrc + '" alt="Patient Image"></div><div class="pat-det mt15"><p class="PatientName">' + name + '</p><p class="Patientpno"><i class="fa fa-phone" aria-hidden="true">&nbsp;&nbsp;</i>' + phone_number + '</p></div></div></div></div><div class="col-md-5 col-sm-5"><div class="pat-det mt15"><p>Next Visit : <span >' + next_visit + '</span></p><p>Last Visit : <span >' + last_visit + '</span></p></div></div><div class="col-md-2 col-sm-2 mt20"><button class="btn deleteicon-btn btn-xs"><i class="fa fa-trash" onclick=vipdel(this) vipid=' + data[i].vip_id + ' patientid=' + data[i].patient_id + ' aria-hidden="true"></i></button></a></div></div>'
                    }

                }
                $('#viplists').html(tr);
            }
            else {
                console.log(data);
            }
        }
    });
}

function watchlistvipcount() {
    var PaitentsVip = {
        Dml_Indicator: 'Co',
        doctor_id: $('#HiddenDoctorID').val()
    }

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

            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.length > 0) {
                        $('#mwlCount').html(data[0].watchlistcount);
                        $('#mvlCount').html(data[0].vipcount);
                        $('#mmwlCount').html(data[0].watchlistcount);
                        $('#mmvlCount').html(data[0].vipcount);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function fullwatchlist() {
    var PaitentsVip = {
        Dml_Indicator: 'WL',
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/PatientWatchlistDash',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsVip),
        success: function (datas) {
            $('.modalsortable1').html('');
            var data = JSON.parse(datas);
            if (jQuery.isEmptyObject((data))) {
                $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');
            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.length > 0) {
                        var tr = '';
                        for (var i = 0; i < data.length; i++) {
                            var name = data[i].first_name;
                            var phone_number = data[i].phone_number_1;
                            var photo = data[i].photo;
                            var Fasting_blood_sugar = data[i].Fasting_blood_sugar;
                            var Postprandial_blood_sugar = data[i].Postprandial_blood_sugar;
                            var bp_max = data[i].bp_max;
                            var bp_min = data[i].bp_min;
                            var last_updated = data[i].created_on;
                            var patientId = data[i].patient_id;
                            var photoSrc = '';
                            var PatientPhoto = $('#patphotop').val();
                            var sugar = '', bp = '';
                            if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                                photoSrc = PtImage;
                            }
                            if (bp_max == '' || bp_max == null) {
                                bp_max = '';
                            }

                            if (bp_min == '' || bp_min == null) {
                                bp_min = '';
                            }
                            if (bp_max != '' && bp_min != '') {

                            }
                            if (bp_min != '' && bp_max != '') {
                                bp = 'SYS ' + bp_max + '/ DIA ' + bp_min + ' mmHg';
                            }
                            else if (bp_min != '') {
                                bp = 'DIA ' + bp_min + ' mmHg';
                            }
                            else if (bp_max != '') {
                                bp = 'SYS ' + bp_max + ' mmHg';
                            }
                            else {
                                bp = '';
                            }
                            if (Fasting_blood_sugar == '' || Fasting_blood_sugar == null) {
                                Fasting_blood_sugar = '';
                            }
                            if (Postprandial_blood_sugar == '' || Postprandial_blood_sugar == null) {
                                Postprandial_blood_sugar = '';
                            }
                            if (Fasting_blood_sugar != '' && Postprandial_blood_sugar != '') {
                                sugar = 'FBS ' + Fasting_blood_sugar + '/ PBS ' + Postprandial_blood_sugar + ' mg/dL ';
                            }
                            else if (Fasting_blood_sugar != '') {
                                sugar = 'FBS ' + Fasting_blood_sugar + ' mg/dL ';
                            }
                            else if (Postprandial_blood_sugar != '') {
                                sugar = 'PBS ' + Postprandial_blood_sugar + ' mg/dL '
                            }
                            else {
                                sugar = '';
                            }
                            var case_form = ''
                            if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + patientId + '">' + name + ' </a>'
                            }
                            else {
                                case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + patientId + '">' + name + ' </a>'
                            }
                            tr = tr + '<div class="row item search-boxa lchild"><div class="li-inner-row"><div class="col-md-2 col-xs-2 pad0 lir-img"> <img class="prof_imgblock" width="40" src="' + photoSrc + '"></div><div class="col-md-5 col-xs-5 pad0 lir-name">' + case_form + '<br /><span class="lir-mobile"><i class="fa fa-phone" aria-hidden="true"></i> ' + phone_number + ' </span></div><div class="col-md-4 col-xs-4 pad0 lir-data"><a tabindex="0"class=""data-html="true"data-toggle="popover"data-placement="bottom"data-trigger="hover"title="<span class=\'text-center\'>Last Updated<br><strong>' + last_updated + '</strong></span>"><span class=" pull-left lir-data1">' + sugar + ' </span><br><span class=" pull-left lir-data2">' + bp + ' </span><br><span class=" pull-left lir-data1">Patient will be removed from the watchlist in next <strong>' + data[i].No_of_Days + ' days </strong></span></a></div><div class="col-md-1 col-xs-1 pull-right pad0 colormt20 lir-options"><div tabindex="0"class=""><div class="wldropdown_sec text-right"><span><i class="fa fa-circle"></i><i class="fa fa-circle"></i><i class="fa fa-circle"></i></span><div class="wldropdown_content"><div class=\'list-group-item\'><span onclick=watchlistDel(this) watchid=' + data[i].watch_id + ' patientid=' + data[i].patient_id + '  ><i class=\'fa fa-trash\'></i> Delete</span></div><input type="hidden" id="name_' + patientId + '" value="' + name + '"/><div class=\'list-group-item\'><span href=\'#myPatientDashModal\' role=\'button\' class=\'m25\' data-toggle=\'modal\' onclick=watchlsedit("' + patientId + '","' + phone_number + '","' + data[i].dob + '","' + data[i].age + '","' + data[i].gender + '");><i class=\'fa fa-pencil\'></i> Edit</span></div></div></div></div></div></div></div>';
                        }
                        $('.modalsortable1').html(tr);
                        $("[data-toggle=popover]").popover();
                        $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    $('.modalsortable1').removeClass('da-load-pp-wl-vip-ma');
    fullviplist();
}

function fullviplist() {

    $('.da-load-Viplist').show();
    var PaitentsVip = {
        Dml_Indicator: 'VL',
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/PatientWatchlistDash',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsVip),
        success: function (datas) {
            $('.modalsortable2').html('');
            var data = JSON.parse(datas);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('.modalsortable2').removeClass('da-load-pp-wl-vip-ma');
                }
                else {
                    var a = '';
                    for (var i = 0; i < data.length; i++) {
                        var name = data[i].first_name;
                        var phone_number = data[i].phone_number_1;
                        var next_visit = data[i].next_visit;
                        var last_visit = data[i].last_visit;
                        var photo = data[i].photo;
                        var last_updated = data[i].last_updated;
                        var patientId = data[i].patient_id;
                        var vipdescription = data[i].description;
                        var photoSrc = '';
                        var PatientPhoto = $('#patphotop').val();
                        if ($.trim(data[i].PatientImage) == "" || data[i].PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + data[i].PatientImage;
                            photoSrc = PtImage;
                        }
                        if (next_visit == '' || next_visit == null) {
                            next_visit = ' - ';
                        }
                        if (last_visit == '' || last_visit == null) {
                            last_visit = ' - ';
                        }
                        var case_form = ''
                        if (parseInt($('#HFormbuilder_id').val()) == 1) {
                            case_form = '<a href="/casestudy/CaseStudyView_form?patient_id=' + patientId + '" tabindex="0" class="" data-html="true" data-toggle="popover" data-placement="bottom" data-trigger="hover" title="" data-original-title="<span class=\'text-center\'>' + vipdescription + '</span>">' + name + '</a>'
                        }
                        else {
                            case_form = '<a href="/casestudy/CaseStudyView?patient_id=' + patientId + '" tabindex="0" class="" data-html="true" data-toggle="popover" data-placement="bottom" data-trigger="hover" title="" data-original-title="<span class=\'text-center\'>' + vipdescription + '</span>">' + name + '</a>'
                        }
                        a = a + '<div class="row item search-boxa lchild"><div class="li-inner-row"><div class="col-md-2 col-xs-2 pad0 lir-img"><img onerror="changedefault(this)" class="prof_imgblock" width="40" src="' + photoSrc + '"></div><div class="col-md-5 col-xs-5 pad0 lir-name">' + case_form + '<br /><span class="lir-mobile"><i class="fa fa-phone" aria-hidden="true"></i> ' + phone_number + ' </span></div><div class="col-md-4 col-xs-4 pad0 lir-data"><a tabindex="0"class="" data-html="true" data-toggle="popover" data-placement="bottom" data-trigger="hover" title="<span class=\'text-center\'>Last Updated<br><strong>' + last_updated + '</strong></span>"><span class=" pull-left lir-data1">Last Visit : ' + last_visit + ' </span><br><span class=" pull-left lir-data2">Next Visit :' + next_visit + ' </span></a></div><div class="col-md-1 col-xs-1 pull-right pad0 colormt20 lir-options"><span onclick=vipdel(this) vipid=' + data[i].vip_id + ' patientid=' + data[i].patient_id + '><i style="font-size:16px;" class=\'fa fa-trash\'></i></span>"></div></div></div></div>';
                    }
                }
                $('.modalsortable2').html(a);
                $('.modalsortable2').removeClass('da-load-pp-wl-vip-ma');
                $("[data-toggle=popover]").popover();
            }
            else {
                console.log(data);
            }
        }
    });
    $('.da-load-Viplist').hide();
    $(function () {
        var tabs = $("#tabs").tabs();
        tabs.find(".ui-tabs-nav").sortable({
            axis: "x",
            stop: function () {
                tabs.tabs("refresh");
            }
        });
    });

    $(function () {
        $(".modalsortable1, .modalsortable2").sortable().disableSelection();
        var $tabs = $("#tabs").tabs();
        var $tab_items = $(".lparent:first lchild", $tabs).droppable({
            accept: ".connectedSortable lchild",
            hoverClass: "ui-state-hover",
            drop: function (event, ui) {
                var $item = $(this);
                var $list = $($item.find("a").attr("href"))
                    .find(".connectedSortable");

                ui.draggable.hide("slow", function () {
                    $tabs.tabs("option", "active", $tab_items.index($item));
                    $(this).appendTo($list).show("slow");
                });
            }
        });
    });
}

function changedefault(e) {
    var photoSrc = "/Content/img/profile_icon.png";
    console.log("Image Error")
    $(e).attr("src", photoSrc)
}

function watchlistDel(e) {
    debugger;
    if (confirm('Are you sure you want to delete?')) {
        var WatchId = e.getAttribute("watchid")
        var patientid = e.getAttribute("patientid");
        var PaitentsVip = {
            Dml_Indicator: 'WU',
            watch_id: WatchId,
            patient_id: patientid,
            doctor_id: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/PatientWatchlistDash',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PaitentsVip),
            success: function (datas) {
                debugger;
                loadwatchlist();
                fullwatchlist();
                watchlistvipcount();
                dashboardcount();
                var data = JSON.parse(datas);
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (data.msg == "Success") {

                    }
                    else {
                        console.log(data);
                    }

                }
            }
        });
    }
    else {

    }
    LoadAppointmentRequest();
}

function vipdel(e) {

    if (confirm('Are you sure you want to delete?')) {
        var vipid = e.getAttribute("vipid")
        var patientid = e.getAttribute("patientid");
        var PaitentsVip = {
            Dml_Indicator: 'VU',
            vip_id: vipid,
            patient_id: patientid,
            doctor_id: $('#HiddenDoctorID').val()
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/PatientWatchlistDash',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PaitentsVip),
            success: function (datas) {
                loadvip();
                fullviplist();
                watchlistvipcount();
                dashboardcount();
                var data = JSON.parse(datas);
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (data.msg == "Success") {

                    }
                    else {
                        console.log(data);
                    }

                }
            }
        });
    }
    else {

    }
    LoadAppointmentRequest();
}

var patient = '';
function watchlsedit(patientid, phone_number, dob, age, gender, patientname) {

    $('#WpatientId').html(patientid);
    patient = patientid;
    //var name = $('#name_' + patientid).val();
    $('#WpatientName').html(patientname);
    $('#Wpatientnumber').html(phone_number);
    var gender = gender;
    if (gender == 1) {
        gender = 'Male';
    }
    else if (gender == 2) {
        gender = 'Female';
    }
    else if (gender == 3) {
        gender = 'Others';
    }
    $('#Wpatientage').html(age + ' years ' + gender);
    loadwatch_parameter();
}

function loadwatch_parameter() {

    var PrescriptionVisitId = {
        Dml_Indicator: 'P',
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PrescriptionVisitId),
        success: function (data) {
            var data = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    var op = '';
                    var sel = '<option value="0">--select--</option>';
                    for (var i = 0; i < data.length; i++) {
                        op = op + '<option value=' + data[i].watch_parameter_id + '>' + data[i].description + '</option>';
                    }
                    $('#SelParameter').append(sel + op);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    loadfrequency_parameter();
}

function loadfrequency_parameter() {

    var PrescriptionVisitId = {
        Dml_Indicator: 'F',
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PrescriptionVisitId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {


                    var op = '';
                    var sel = '<option value="0">--select--</option>';
                    for (var i = 0; i < data.length; i++) {
                        op = op + '<option value=' + data[i].watch_frequency_id + '>' + data[i].description + '</option>';
                    }
                    $('#SelFrequency').append(sel + op);

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

function loadwatch_list() {

    var loadwatchlist = {
        Dml_Indicator: 'S',
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(loadwatchlist),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('a[data-toggle="SelPriority"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
                $('a[data-toggle="SelPriority"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
                $('a[data-toggle="SelPriority"]').not('[data-title="' + 3 + '"]').removeClass('active').addClass('not-active');
                $('#WatchTable tbody').empty();
                if (jQuery.isEmptyObject((data))) {

                }
                else {


                    console.log(data);

                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var SelPriority = data[0].priority;

                            $('#Chknepropathy').val(SelPriority);
                            $('a[data-toggle=SelPriority][data-title="' + SelPriority + '"]').addClass('active');

                            $('#endDate').val(data[0].end_date);
                            $('#watch_id').val(data[0].watch_id);
                            var rowcount = $.trim($('#WatchTableRowCount').val());
                            var tot_row = (Number(rowcount) + 1);
                            var ikey = '';
                            var sess_data = data[i].ParameterDescription + "," + data[i].watch_parameter_id + "," + data[i].FrequencyDescription + "," + data[i].watch_frequency_id + "," + data[i].target_1 + "," + data[i].target_2;
                            ikey = 'row' + tot_row;
                            sessionStorage.setItem(ikey, sess_data);

                            var value = "<tr id='t_" + ikey + "'><td>" + data[i].ParameterDescription + "</td><td>" + data[i].FrequencyDescription + "</td><td>" + data[i].target_1 + "</td><td>" + data[i].target_2 + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                            $('#WatchTable > tbody:last').append(value);
                            $('#WatchTableRowCount').val(tot_row);
                            if (tot_row > 0) {

                                $('#mWatchlist').prop('checked', true);
                                $('#mWatchSection').show();
                            }
                        }
                    }
                    else {

                    }

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

function loadViplist() {
    var loadViplist = {
        Dml_Indicator: 'S',
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Viplist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(loadViplist),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    var status = '';
                    for (var i = 0; i < data.length; i++) {
                        status = data[i].status;
                        if (status == 1) {
                            $('#modalVIP').prop('checked', true);
                            $('#mVIPSection').show();
                            $('#txtVipDetails').val(data[i].description);
                        }
                    }

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

$('#SelParameter').change(function () {
    if ($('#SelParameter').val() == 1) {
        $('#lbltarget1').html('SYS');
        $('#lbltarget2').html('DIA');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }
    else if ($('#SelParameter').val() == 2) {
        $('#lbltarget1').html('FBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else if ($('#SelParameter').val() == 3) {
        $('#lbltarget1').html('PBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else {
        $('#lbltarget1').html('Target 1');
        $('#lbltarget2').html('Target 2');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }
});

$('#addwatchlist').click(function () {
    if ($.trim($('#SelParameter :selected').val()) == "" || $('#SelParameter :selected').val() == "0") {
        $('#PSelParameter').show();
        $('#PSelParameter').fadeOut(8000);
        $('#PSelParameter').html('Select Parameter');
        $('#SelParameter').focus();
        $('#SelParameter :selected').val('0');
        return false;
    }
    if ($.trim($('#SelFrequency :selected').val()) == "" || $('#SelFrequency :selected').val() == "0") {
        $('#PSelFrequency').show();
        $('#PSelFrequency').fadeOut(8000);
        $('#PSelFrequency').html('Select Frequency');
        $('#SelFrequency').focus();
        $('#SelFrequency :selected').val('0');
        return false;
    }
    if ($.trim($('#txttarget1').val()) == "") {
        $('#Ptxttarget1').show();
        $('#Ptxttarget1').fadeOut(8000);
        $('#Ptxttarget1').html('Enter value');
        $('#txttarget1').focus();
        $('#txttarget1').val('');
        return false;
    }

    var sess_key;
    var rowcount = $.trim($('#WatchTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var ikey = '';
    var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val();

    if (rowcount >= 1) {
        var getEid = $('#WatchTable  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterInc = parseInt(afterSplit[1]) + 1;
        console.log(afterInc);
        ikey = 'row' + afterInc;
    }
    else {

        ikey = 'row' + tot_row;
    }
    sessionStorage.setItem(ikey, sess_data);

    var value = "<tr id='t_" + ikey + "'><td>" + $('#SelParameter :selected').text() + "</td><td>" + $('#SelFrequency :selected').text() + "</td><td>" + $('#txttarget1').val() + "</td><td>" + $('#txttarget2').val() + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#WatchTable > tbody:last').append(value);
    $('#WatchTableRowCount').val(tot_row);
    $('#SelParameter').val(0);
    $('#SelFrequency').val(0);
    $('#txttarget1').val('');
    $('#txttarget2').val('');

});

function watchlistedit(val) {

    $('#addwatchlist').hide();
    $('#updatewatchlist').show();
    $('#hnd_watchlist').val(val);

    var gkey = val;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#SelParameter').val(row_data_split[1]);
    $('#SelFrequency').val(row_data_split[3]);
    $('#txttarget1').val(row_data_split[4]);
    $('#txttarget2').val(row_data_split[5]);


    if (row_data_split[1] == 1) {
        $('#lbltarget1').html('SYS');
        $('#lbltarget2').html('DIA');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }
    else if (row_data_split[1] == 2) {
        $('#lbltarget1').html('FBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else if (row_data_split[1] == 3) {
        $('#lbltarget1').html('PBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else {
        $('#lbltarget1').html('Target 1');
        $('#lbltarget2').html('Target 2');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }

}
function watchlistdelete(val) {
    sessionStorage.removeItem(val);
    $('#t_' + val).remove();
    var a = $.trim($('#WatchTableRowCount').val());
    var a = (a) - (1);
    $('#WatchTableRowCount').val(a);
}

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

    var table_id = $('#hnd_watchlist').val();

    if ($.trim($('#SelParameter :selected').val()) == "" || $('#SelParameter :selected').val() == "0") {
        $('#PSelParameter').show();
        $('#PSelParameter').fadeOut(8000);
        $('#PSelParameter').html('Select Parameter');
        $('#SelParameter').focus();
        $('#SelParameter :selected').val('0');
        return false;
    }
    if ($.trim($('#SelFrequency :selected').val()) == "" || $('#SelFrequency :selected').val() == "0") {
        $('#PSelFrequency').show();
        $('#PSelFrequency').fadeOut(8000);
        $('#PSelFrequency').html('Select Frequency');
        $('#SelFrequency').focus();
        $('#SelFrequency :selected').val('0');
        return false;
    }
    if ($.trim($('#txttarget1').val()) == "") {
        $('#Ptxttarget1').show();
        $('#Ptxttarget1').fadeOut(8000);
        $('#Ptxttarget1').html('Select Types');
        $('#txttarget1').focus();
        $('#txttarget1').val('');
        return false;
    }

    $('#addwatchlist').show();
    $('#updatewatchlist').hide();

    var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val();
    var ikey = table_id;
    sessionStorage.setItem(ikey, sess_data);

    $('#WatchTable > tbody:last').empty();


    var tot_row = $.trim($('#WatchTableRowCount').val());
    var i, j;


    for (i = 1; i <= tot_row; i++) {
        var gkey = 'row' + i;
        console.log(sessionStorage.getItem(gkey));
        var row_data = sessionStorage.getItem(gkey);

        if (row_data == null) {
            console.log(gkey + '--------->' + row_data);
        }
        if (row_data != null) {
            row_data = row_data.split(',');
            var value = "<tr id='t_" + gkey + "'><td>" + row_data[0] + "</td><td>" + row_data[2] + "</td><td>" + row_data[4] + "</td><td>" + row_data[5] + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='edit btn btn-primary btn-sm btn-add' onclick='watchlistdelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

            $('#WatchTable > tbody:last').append(value);
        }
    }

    $('#SelParameter').val(0);
    $('#SelFrequency').val(0);
    $('#txttarget1').val('');
    $('#txttarget2').val('');
});


$('#btnwatchlist').click(function () {
    var Notesdata = {
        watch_id: $('#watch_id').val(),
        Dml_Indicator: 'D'
    }
    $('#myPatientDashModal').modal('toggle');
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Notesdata),
        success: function (data) {
            Addwatchlist();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
            }
            else {
                console.log(data);
            }
        }
    });

});


function Addwatchlist() {
    var enddate = $('#endDate').val();
    enddate = enddate.split('/');
    var End_Date = enddate[2] + "-" + enddate[1] + "-" + enddate[0];
    var Notesdata = {
        patient_id: patient,
        created_by: $('#HiddenDoctorID').val(),
        removed_on: '',
        removed_by: $('#HiddenDoctorID').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        priority: $('#SelPriority').val(),
        end_date: End_Date,
        Dml_Indicator: 'I'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Notesdata),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var watch_id = '';
                    //if (data.length > 2) {
                    $.each(data1, function (i, emp) {
                        watch_id = emp.watch_id;
                    });
                    var tot_rowM = $.trim($('#WatchTableRowCount').val());
                    $("#BtnLabSubmit").html('Update changes');
                    if (tot_rowM > 0) {
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            var a = $('#WatchTable_body').children('tr').eq(L);
                            var b = a.prop('id');
                            L++;
                            var C = b.split('_');
                            var gkey = C[1];

                            var row_data = sessionStorage.getItem(gkey);
                            var K = 0;
                            if (row_data == "") {
                                console.log(gkey + '--------->' + row_data);
                            }
                            if (row_data != "" && row_data != null) {
                                console.log(gkey + '-------' + row_data);
                                row_data = row_data.split(',');

                                var sms = {
                                    Dml_Indicator: 'DI',
                                    watch_parameter_id: row_data[1],
                                    watch_id: watch_id,
                                    watch_frequency_id: row_data[3],
                                    target_1: row_data[4],
                                    target_2: row_data[5],
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/CaseStudy/Watchlist',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(sms),
                                    success: function (data) {
                                    }
                                });
                            }
                        }
                    }
                    // }
                }
                AddVip();
            }
            else {
                console.log(data1);
            }
        }
    });
}

function AddVip() {
    var description = $.trim($('#txtVipDetails').val());
    var status = "1";
    if (description == '') {
        status = "0";
    }
    var vipdata = {
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val(),
        description: description,
        status: status,
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Viplist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(vipdata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
                popclear();
            }
            else {
                console.log(data);
            }
        }
    });
}
function popclear() {
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 3 + '"]').removeClass('active').addClass('not-active');
    $('#WatchTable tbody').empty();
    $('#endDate').val('');
    $('#SelParameter').empty();
    $('#SelFrequency').empty();
    $('#txttarget1').val('');
    $('#txttarget2').val('');

    $('#txtVipDetails').val('');
}

$('#btnclose').click(function () {
    popclear();
});

$('#btncloseX').click(function () {
    popclear();
});

$(function () {
    // Enables popover
    $("[data-toggle=popover]").popover();

    $("#endDate").datepicker('setDate', "");

});

$(function () {
    var tabs = $("#tabs").tabs();
    tabs.find(".ui-tabs-nav").sortable({
        axis: "x",
        stop: function () {
            tabs.tabs("refresh");
        }
    });
});

$(function () {
    $("#sortable1, #sortable2").sortable().disableSelection();

    var $tabs = $("#tabs").tabs();

    var $tab_items = $(".lparent:first lchild", $tabs).droppable({
        accept: ".connectedSortable lchild",
        hoverClass: "ui-state-hover",
        drop: function (event, ui) {
            var $item = $(this);
            var $list = $($item.find("a").attr("href"))
                .find(".connectedSortable");

            ui.draggable.hide("slow", function () {
                $tabs.tabs("option", "active", $tab_items.index($item));
                $(this).appendTo($list).show("slow");
            });
        }
    });
});
//Dashboard drag and drop viplist ends

//procedure start
function procedure(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time, doctor_id, age, gender) {
    var gen = "";
    $('.imgphoto').attr("src", photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);
    labtype();

    var labval = {
        Dml_Indicator: 'S',
        patient_id: patient_id,
        slot_time: slot_start_time
    }

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

            var data = JSON.parse(data);
            console.log(data);
            if (jQuery.isEmptyObject((data))) {
                $('#DiagnosticsTestTable').empty();
            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    $('#DiagnosticsTestTable').html('');
                    if (data.Table.length > 0) {
                        if (data.Table[0].VVisit_report_id == '' || data.Table[0].VVisit_report_id == null) {
                        }
                        else {
                            var tr = '';

                            for (var i = 0; i < data.Table.length; i++) {

                                tr = tr + "<tr><td>" + data.Table[i].lab_prescription + "</td><td>" + data.Table[i].lab_type_name + "</td><td><button class='edit btn btn-primary btn-xs btn-add mr-15' onclick='scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-xs btn-add' onclick='deleteRow(\"" + (data.Table[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                                $('#VisitReportID').val(data.Table[i].visit_report_id);
                            }
                            $('#DiagnosticsTestTable').html(tr);
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function loadlab_prescription() {
    var labval = {
        Dml_Indicator: 'SS',
        visit_report_id: $('#VisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Dashboard_quick_lab_procedure',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            $('#DiagnosticsTestTable').empty();
            var data = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {
                $('#DiagnosticsTestTable').empty();
            }
            else {
                console.log(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.Table.length > 0) {
                        var tr = '';
                        for (var i = 0; i < data.Table.length; i++) {
                            tr = tr + "<tr><td>" + data.Table[i].lab_prescription + "</td><td>" + data.Table[i].lab_type_name + "</td><td><button class='edit btn addicon-btn btn-sm btn-add mr-20' onclick='scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default   btn-sm btn-add' onclick='deleteRow(\"" + (data.Table[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        }
                        $('#DiagnosticsTestTable').html(tr);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function labtype() {
    var country = {
        Dml_Indicator: "TS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            $('#labtype').empty();
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var tr = '';
                    $('#labtype').append('');
                    $.each(data1, function (i, emp) {
                        tr = tr + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';
                    });
                    $('#labtype').append(tr);
                }
                else {
                    console.log(data1);
                }
            }
        }
    });
}

$('#Add_Lab_record').click(function () {
    VisitreportId_lab_prescription(1);
});
function VisitreportId_lab_prescription(id) {
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: '15'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        if (id == 1) {
                            insert_lab_prescription();
                        }
                        else if (id == 2) {
                            update_lab_record();
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


function deleteRow(id) {

    var sms = {
        Dml_Indicator: 'DD',
        prescription_scan_id: id,
        visit_report_id: $('#VisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            var tr = '';
            var data = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                if (data.msg == "Success") {
                    loadlab_prescription();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}
function deleteRow_1(id) {

    var sms = {
        Dml_Indicator: 'D',
        prescription_scan_id: id,
        visit_report_id: $('#VisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            var tr = '';
            var data = JSON.parse(data);

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

            }
            else {
                var value = '';
                if (data.msg == "Success") {
                    var data = data.data;
                    $('#tbl-scan_1 > tbody').empty();
                    for (var i = 0; i < data.length; i++) {
                        value = value + "<tr><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td>" + data[i].suggested_date + "</td><td><button class='btn btn-primary addicon-btn  btn-sm mr-20' onclick='scanedit_1(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm btn-danger' onclick='deleteRow_1(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                    }
                    $('#tbl-scan_1 > tbody').html(value);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function scanedit(scan_id) {

    var sms = {
        Dml_Indicator: 'ES',
        prescription_scan_id: scan_id,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            var data = JSON.parse(data);

            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {


                    console.log(data);
                    for (var i = 0; i < data.length; i++) {
                        var lab_type = data[0].lab_type;
                        $('#report').val(data[0].lab_prescription);
                        $('#labtype').val(data[0].lab_type);

                    }
                    $('#Add_Lab_record').hide();
                    $('#Update_Lab_record').show();
                    $('#hdn_scan_id').val(scan_id);

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

        }
    });

}
function scanedit_1(scan_id) {

    var sms = {
        Dml_Indicator: 'ES',
        prescription_scan_id: scan_id,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            var data = JSON.parse(data);

            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {


                    console.log(data);
                    for (var i = 0; i < data.length; i++) {
                        var lab_type = data[0].lab_type;

                        $('#report_1').val(data[0].lab_prescription);
                        $('#labtype_1').val(data[0].lab_type);
                        $('#datepickerscan').val(data[0].suggested_date)
                    }
                    $('#Add_Lab_record_1').hide();
                    $('#Update_Lab_record_1').show();
                    $('#hdn_scan_id').val(scan_id);

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

        }
    });

}

function insert_lab_prescription() {
    if ($('#labtype').val() == 0 || $('#labtype').val() == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select test type');
        $('#SelFacilityId').focus();
        $('#SelFacilityId').val('0');
        return false;
    }

    if ($('#report').val() == '') {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter the test name');
        $('#report').focus();
        $('#report').val('');
        return false;
    }

    var labval = {
        Dml_Indicator: 'I',
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        lab_prescription: $('#report').val(),
        lab_type: $('#labtype').val(),
        lab_id: $('#lab_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Dashboard_quick_lab_procedure',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            var data = JSON.parse(data);
            if (jQuery.isEmptyObject((data))) {
                $('#DiagnosticsTestTable').empty();
            }
            else {
                if (data.msg == "Success") {
                    var data = data.data;
                    var tr = '';
                    $('#DiagnosticsTestTable').empty();
                    for (var i = 0; i < data.Table.length; i++) {
                        tr = tr + "<tr><td>" + data.Table[i].lab_prescription + "</td><td>" + data.Table[i].lab_type_name + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default   btn-sm btn-add' onclick='deleteRow(\"" + (data.Table[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    }
                    $('#DiagnosticsTestTable').html(tr);
                }
                else {
                    console.log(data);
                }
            }
            $('#report').val('');
            $('#labtype').val('1');
        }
    });

}

$('#Update_Lab_record').click(function () {
    VisitreportId_lab_prescription(2);
});
function update_lab_record() {
    var table_id = $('#hdn_scan_id').val();

    if ($('#labtype').val() == 0) {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select test type');
        $('#SelFacilityId').focus();
        $('#SelFacilityId').val('0');
        return false;
    }

    if ($('#report').val() == '') {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter the test name');
        $('#report').focus();
        $('#report').val('');
        return false;
    }

    $('#Add_Lab_record').show();
    $('#Update_Lab_record').hide();


    var sms = {
        Dml_Indicator: 'UU',
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        lab_prescription: $('#report').val(),
        lab_type: $('#labtype').val(),
        prescription_scan_id: $('#hdn_scan_id').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            //loadlab_prescription();
            var tr = '';
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    loadlab_prescription();

                    //var data = JSON.parse(data);
                    //$('#DiagnosticsTestTable').empty();
                    //for (var i = 0; i < data.length; i++) {
                    //    tr = tr + "<tr><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger   btn-sm btn-add' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    //}

                    //$('#DiagnosticsTestTable').html(tr);
                }
                $('#report').val('');
            }
            else {
                console.log(data);
            }
        }
    });
}

function procedure_print() {
    window.open('/PatientDashboard/procedure?visitreportid=' + $('#VisitReportID').val(), "_blank");
}

$('#btnProCls').click(function () {
    $('#DiagnosticsTestTable').empty();

});
//procedure end

//quickentry start
function quickentry(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time, doctor_id, age, gender) {
    debugger;
    LoadCasesheetConfiguration(doctor_id);

    quickentry_close_berfore();
    $('#da-load-quickentry').show();
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);

    if ($('#HCasesheetType').val() == 4) {
        $('#div_txtComplaintsQ').hide();
        $('#div_txtHbA1cQ').hide();
        $('#div_ACR').hide();
        $('#div_fasting').hide();
        $('#div_Postprandial_blood').hide();
        $('#div_Random_blood').hide();
    }
    else {
        $('#div_txtComplaintsQ').show();
        $('#div_txtHbA1cQ').show();
        $('#div_ACR').show();
        $('#div_fasting').show();
        $('#div_Postprandial_blood').show();
        $('#div_Random_blood').show();
    }


    var gen = "";
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);
    VisitreportId();
    //LoadPatientGeneralInformation();
    var labval = {
        Dml_Indicator: 'SS',
        patient_id: patient_id,
        slot_time: slot_start_time
    }

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

                if (data.msg == "Success") {
                    var data = data.data;
                    if (data.length > 0) {
                        if (data[0].VVisit_report_id == '' || data[0].VVisit_report_id == null) {

                            //var hieghtdb = data[0].patient_height + '.' + data[0].patient_height_metric;
                            //var hieghtout = Math.round(hieghtdb / 0.032808);

                            var hieghtdb = parseInt(data[0].patient_height * 12) + parseInt(data[0].patient_height_metric);
                            var hieghtout = Math.round(hieghtdb * 2.54);

                            hieghtout = isNaN(hieghtout) ? '' : hieghtout;
                            $('#txtheightQ').val(hieghtout);
                        }
                        else {

                            for (var i = 0; i < data.length; i++) {
                                $('#txtComplaintsQ').val(data[0].current_complaints);
                                $('#txtPulseRateQ').val(data[0].pulse_rate);
                                $('#txtCVSQ').val(data[0].cvs);
                                $('#txtRSQ').val(data[0].rs);
                                $('#txtABSQ').val(data[0].ABS);
                                $('#txtCNSQ').val(data[0].CNS);
                                $('#txtDiaQ').val(data[0].dia);
                                $('#txtSysQ').val(data[0].sys);
                                $('#txtTemperatureQ').val(data[0].temperature);
                                $('#txtHbA1cQ').val(data[0].patient_hbac_record_value);
                                $('#txtSpo2Q').val(data[0].spo2);
                                $('#txtWeightQ').val(data[0].patient_weight);
                                $('input[name="optradioConsciences"][value="' + data[0].level_of_conscience + '"]').prop('checked', true);
                                var ACR = data[0].ACR;
                                $('#acr1Q').val(ACR)
                                $('a[data-toggle=acr1Q][data-title="' + ACR + '"]').removeClass('not-active');
                                $('a[data-toggle=acr1Q][data-title="' + ACR + '"]').addClass('active');
                                if (data[i].patient_blood_sugar_type == 1) {
                                    $('#txtBloodsugarV_1Q').val(data[i].patient_blood_sugar_value);
                                    $('#txtBloodsugarT_1Q').val(data[i].patient_blood_sugar_unit);
                                }
                                if (data[i].patient_blood_sugar_type == 2) {
                                    $('#txtBloodsugarV_2Q').val(data[i].patient_blood_sugar_value);
                                    $('#txtBloodsugarT_2Q').val(data[i].patient_blood_sugar_unit);
                                }
                                if (data[i].patient_blood_sugar_type == 3) {
                                    $('#txtBloodsugarV_3Q').val(data[i].patient_blood_sugar_value);
                                    $('#txtBloodsugarT_3Q').val(data[i].patient_blood_sugar_unit);
                                }

                           
                              
                                $('#txtTimetoOPD').val(data[0].Time_of_arrival_OPD);
                                if (data[0].Is_Allergies == 1) {
                                    $('a[data-toggle=ChkAllergiesifany][data-title="1"]').removeClass('not-active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="1"]').addClass('active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="0"]').removeClass('active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="0"]').addClass('not-active');
                                    $('#div_Allergies').show();
                                    $('#Specific_Allergies').val(data[0].Specific_Allergies);
                                }
                                else {
                                    $('a[data-toggle=ChkAllergiesifany][data-title="1"]').removeClass('active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="1"]').addClass('not-active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="0"]').removeClass('not-active');
                                    $('a[data-toggle=ChkAllergiesifany][data-title="0"]').addClass('active');
                                }
                                $('#ChkAllergiesifany').val(data[0].Is_Allergies);
                            
                                if (data[0].Is_AnyLanguageBarrior == 1) {
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="1"]').removeClass('not-active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="1"]').addClass('active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="0"]').removeClass('active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="0"]').addClass('not-active');
                                    $('#div_languagecordinator').show();
                                    LoadUser(data[0].Language_Cordinator)
                                }
                                else {
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="1"]').removeClass('active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="1"]').addClass('not-active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="0"]').removeClass('not-active');
                                    $('a[data-toggle=ChkAnylanguagebarrier][data-title="0"]').addClass('active');
                                }
                                $('#ChkAnylanguagebarrier').val(data[0].Is_AnyLanguageBarrior);


                                   if (data[0].Is_AlcoholIntake == 1) {
                                       $('a[data-toggle=ChkAlcoholintake][data-title="1"]').removeClass('not-active');
                                       $('a[data-toggle=ChkAlcoholintake][data-title="1"]').addClass('active');
                                       $('a[data-toggle=ChkAlcoholintake][data-title="0"]').removeClass('active');
                                       $('a[data-toggle=ChkAlcoholintake][data-title="0"]').addClass('not-active');
                                   }
                                    else {
                                       $('a[data-toggle=ChkAlcoholintake][data-title="1"]').removeClass('active');
                                        $('a[data-toggle=ChkAlcoholintake][data-title="1"]').addClass('not-active');
                                        $('a[data-toggle=ChkAlcoholintake][data-title="0"]').removeClass('not-active');
                                        $('a[data-toggle=ChkAlcoholintake][data-title="0"]').addClass('active');
                                    }
                                   $('#ChkAlcoholintake').val(data[0].Is_AlcoholIntake);


                                   if (data[0].Is_SubstanceAbuse == 1) {
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="1"]').removeClass('not-active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="1"]').addClass('active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="0"]').removeClass('active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="0"]').addClass('not-active');
                                   }
                                   else {
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="1"]').removeClass('active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="1"]').addClass('not-active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="0"]').removeClass('not-active');
                                       $('a[data-toggle=ChkSubstanceabuse][data-title="0"]').addClass('active');
                                   }
                                   $('#ChkSubstanceabuse').val(data[0].Is_SubstanceAbuse);
                               
                                   if (data[0].Is_Smoking == 1) {
                                       $('a[data-toggle=ChkSmoking][data-title="1"]').removeClass('not-active');
                                       $('a[data-toggle=ChkSmoking][data-title="1"]').addClass('active');
                                       $('a[data-toggle=ChkSmoking][data-title="0"]').removeClass('active');
                                       $('a[data-toggle=ChkSmoking][data-title="0"]').addClass('not-active');
                                   }
                                   else {
                                       $('a[data-toggle=ChkSmoking][data-title="1"]').removeClass('active');
                                       $('a[data-toggle=ChkSmoking][data-title="1"]').addClass('not-active');
                                       $('a[data-toggle=ChkSmoking][data-title="0"]').removeClass('not-active');
                                       $('a[data-toggle=ChkSmoking][data-title="0"]').addClass('active');
                                   }
                                   $('#ChkSmoking').val(data[0].Is_Smoking);

                                   if (data[0].Is_PainScreening == 1) {
                                       $('a[data-toggle=ChkPainscreening][data-title="1"]').removeClass('not-active');
                                       $('a[data-toggle=ChkPainscreening][data-title="1"]').addClass('active');
                                       $('a[data-toggle=ChkPainscreening][data-title="0"]').removeClass('active');
                                       $('a[data-toggle=ChkPainscreening][data-title="0"]').addClass('not-active');

                                       $('#div_painscore').show();
                                       $('#ChkPainscreeningScore').val(data[0].PainScreening_Score);
                                   }
                                   else {
                                       $('a[data-toggle=ChkPainscreening][data-title="1"]').removeClass('active');
                                       $('a[data-toggle=ChkPainscreening][data-title="1"]').addClass('not-active');
                                       $('a[data-toggle=ChkPainscreening][data-title="0"]').removeClass('not-active');
                                       $('a[data-toggle=ChkPainscreening][data-title="0"]').addClass('active');
                                   }
                                   $('#ChkPainscreening').val(data[0].Is_PainScreening);



                                   if (data[0].Is_spl_religious == 1) {
                                    $('a[data-toggle=Chkspecialreligious][data-title="1"]').removeClass('not-active');
                                    $('a[data-toggle=Chkspecialreligious][data-title="1"]').addClass('active');
                                    $('a[data-toggle=Chkspecialreligious][data-title="0"]').removeClass('active');
                                    $('a[data-toggle=Chkspecialreligious][data-title="0"]').addClass('not-active');

                                    $('#div_special_details').show();
                                    $('#specialreligiousdetails').val(data[0].SplReligious_SpecificDetails);
                                }
                            else {
                                 $('a[data-toggle=Chkspecialreligious][data-title="1"]').removeClass('active');
                                 $('a[data-toggle=Chkspecialreligious][data-title="1"]').addClass('not-active');
                                 $('a[data-toggle=Chkspecialreligious][data-title="0"]').removeClass('not-active');
                                $('a[data-toggle=Chkspecialreligious][data-title="0"]').addClass('active');
                                 }
                                   $('#Chkspecialreligious').val(data[0].Is_spl_religious);

                                 //$('#Duration').val(data[0].Duration);
                                //$('#Location').val(data[0].Location);
                                $('input[name="optradioPsychosocial_assessment"][value="' + data[0].Is_Pshychosocial_Assessment + '"]').prop('checked', true);
                                //$('input[name="optradioPaincharacter"][value="' + data[0].Is_Pain_Character + '"]').prop('checked', true);
                                $('input[name="optradionutri_scr_appetie"][value="' + data[0].Is_Nutritional_Screening_Appetie + '"]').prop('checked', true);
                                $('input[name="optradionutri_scr_weight"][value="' + data[0].Is_Nutritional_Screening_weight + '"]').prop('checked', true);
                                //$('input[name="optradiofall_risk"][value="' + data[0].Is_Fallrisks_Screeningforadults + '"]').prop('checked', true);



                                //var hieghtdb = data[0].patient_height + '.' + data[0].patient_height_metric;
                                //var hieghtout = Math.round(hieghtdb / 0.032808);

                                var hieghtdb = parseInt(data[0].patient_height * 12) + parseInt(data[0].patient_height_metric);
                                var hieghtout = Math.round(hieghtdb * 2.54);

                                hieghtout = isNaN(hieghtout) ? '' : hieghtout;
                                $('#txtheightQ').val(hieghtout);

                                debugger;
                                $('#emoNPDRradio').val(data[0].vas);
                                $('a[data-toggle=emoNPDRradio][data-title="' + data[0].vas + '"]').removeClass('not-active');
                                $('a[data-toggle=emoNPDRradio][data-title="' + data[0].vas + '"]').addClass('active');
                                emoji(data[0].vas);

                                var paincharacter = data[0].vaspaincharacter;

                                if (paincharacter != null && paincharacter != "") {

                                    var paincharactersplit = paincharacter.split(',');

                                    for (i = 0; i < paincharactersplit.length; i++) {

                                        $("input[name='optionspc'][value=" + paincharactersplit[i] + "]").click();

                                    }

                                }
                                var frsfa = data[0].vasfullrisk;

                                if (frsfa != null && frsfa != "") {

                                    var frsfasplit = frsfa.split(',');

                                    for (i = 0; i < frsfasplit.length; i++) {

                                        $("input[name='optionsfrsfa'][value=" + frsfasplit[i] + "]").click();

                                    }

                                }
                                $('#txtvasduration').val(data[0].vasduration);
                                $('#txtvaslocation').val(data[0].vaslocation);
                            }
                        }
                    }

                }
                else {
                    console.log(data);
                }
            }
            $('.da-load-quickentry').hide();
            debugger;
            LoadPatientGeneralInformation();
            
        }
    });
    quickentry_lab(patient_id, slot_start_time);
}


//function LoadPatientGeneralInformation() {
//    
//    var doctorData = {
//        Dml_Indicator: 'GS'
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/CaseStudy/Patient_General_Information',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(doctorData),
//        success: function (data) {
//            if (jQuery.isEmptyObject((data))) {

//            }
//            else {
//                var data1 = JSON.parse(data);
//                var row = '';
//                var j = 0;
//                $('#PatientGeneralInformationBody').empty();
//                if (data1.length > 0) {
//                    for (var i = 0; i < data1.length; i++) {
//                        row = row + '<div class="col-xs-12 col-md-6"><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><label  for="check_' + (i + 1) + '">' + data1[i].type + '</label> <input type="checkbox" style="float:right;" id="check_' + (i + 1) + '" name="check_' + (i + 1) + '" value="' + data1[i].id + '"> </div><div><input type="text" class="form-control" id="GeneralInformation_' + (i + 1) + '"></div></div>'
//                        j++;
//                    }
//                }
//                $('#totalInfoCount').val(data1.length);
//                $('#PatientGeneralInformationBody').html(row);

//                var doctorData = {
//                    patient_id: $('#Hdnpatient_id').val(),
//                    Dml_Indicator: 'S'
//                }
//                $.ajax({
//                    async: true,
//                    type: 'POST',
//                    url: '/CaseStudy/Patient_General_Information',
//                    contentType: 'application/json; charset=UTF-8',
//                    data: JSON.stringify(doctorData),
//                    success: function (data) {
//                        console.log(data);
//                        if (jQuery.isEmptyObject((data))) {

//                        }
//                        else {
//                            var data1 = JSON.parse(data);
//                            var count = $('#totalInfoCount').val();
//                            console.log(count);
//                            if (data1.length > 0) {
//                                if (count > 0) {
//                                    for (var j = 0; j < count; j++) {
//                                        for (var i = 0; i < data1.length; i++) {
//                                            if ($('#check_' + (j + 1)).val() == data1[i].type_id) {
//                                                $('#check_' + (j + 1)).prop("checked", data1[i].is_active);
//                                                $('#GeneralInformation_' + (j + 1)).val(data1[i].type_value)
//                                            }

//                                        }
//                                    }
//                                }
//                            }
//                            LoadObservedNutrition();
//                        }

//                    }
//                });

//            }
//        }
//    });
//}

//function LoadObservedNutrition() {

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

//            }
//            else {
//                var data1 = JSON.parse(data);
//                var row = '';
//                var type = '';

//                var j = 0;

//                $('#PatientObservedNutritionBody').empty();
//                if (data1.Table.length > 0) {
//                    console.log(data1.Table);
//                    $('#totalObservedCount').val(data1.Table.length);
//                    for (var i = 0; i < data1.Table.length; i++) {

//                        var doctorData = {
//                            Dml_Indicator: 'MSD',
//                            type_id: data1.Table[i].id
//                        }
//                        $.ajax({
//                            async: true,
//                            type: 'POST',
//                            url: '/CaseStudy/Patient_Observed_Nutrition',
//                            contentType: 'application/json; charset=UTF-8',
//                            data: JSON.stringify(doctorData),
//                            success: function (data) {
//                                if (jQuery.isEmptyObject((data))) {

//                                }
//                                else {
//                                    
//                                    var options = '';
//                                    var type = '';
//                                    var data2 = JSON.parse(data);

//                                    if (data2.Table.length > 0) {
//                                        j++;
//                                        for (var k = 0; k < data2.Table.length; k++) {
//                                            type = '<div class="col-xs-12" id="ObservedType_' + (j) + '"><p class="cs-on-head">' + data2.Table[0].type + '<p></div><span id="ObservedTypeID_' + (j) + '" hidden>' + data2.Table[0].type_id + '</span>'
//                                            options = options + '<div class="col-md-12 cus-rbtn"><div class="form-check"><label class="form-check-label"><input type="radio" class="form-check-input" name="optradioObserved_' + j + '" value=' + data2.Table[k].id + '><span>' + data2.Table[k].type_name + '</span></label></div></div>'
//                                        }

//                                        row = type + options;
//                                        $('#PatientObservedNutritionBody').append(row);


//                                    }
//                                    LoadObservedNutritiononVisitID();
//                                }

//                            }
//                        });


//                    }
//                    //

//                }
//            }
//        }
//    });
//}

//function LoadObservedNutritiononVisitID() {
//    //Load Patient Observed nutrition
//    var doctorData = {
//        Dml_Indicator: 'S',
//        Patient_id: $('#Hdnpatient_id').val(),
//        visit_report_id: $('#VisitReportID').val()
//    }
//    console.log(doctorData);
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/CaseStudy/Patient_Observed_Nutrition',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(doctorData),
//        success: function (data) {
//            if (jQuery.isEmptyObject((data))) {

//            }
//            else {
//                
//                var data1 = JSON.parse(data);
//                console.log(data1);
//                var row = '';
//                var count = $('#totalObservedCount').val();
//                if (data1.Table.length > 0) {
//                    if (count > 0) {
//                        for (var j = 0; j < count; j++) {
//                            for (var i = 0; i < data1.Table.length; i++) {
//                                if ($('#ObservedTypeID_' + (j + 1)).html() == data1.Table[i].type_id) {
//                                    $('input[name="optradioObserved_' + (j + 1) + '"][value="' + data1.Table[i].observed_nutrition_id + '"]').prop('checked', true);
//                                }

//                            }
//                        }
//                    }
//                }
//            }
//        }
//    });
//}
//function SaveGeneralInformation(saveval) {
//    
//    var count = $('#totalInfoCount1').val();
//    if(count=='' ||count==null){
//    //if ($('#totalInfoCount1').val() == '' || $('#totalInfoCount1').val() == null) {
//        return false;
//    }
//    
//    var count = $('#totalInfoCount1').val();
//    console.log(count);
//    var k = 0;
//    for (var i = 0; i < count; i++) {
//        var typeValue = $('#GeneralInformation_' + (i + 1)).val();
//        var typeId = $('#check_' + (i + 1)).val();
//        var isActive = ($('#check_' + (i + 1)).prop('checked') == true) ? "1" : "0";
//        var doctorData = {
//            patient_id: $('#Hdnpatient_id').val(),
//            type_id: typeId,
//            type_value: typeValue,
//            Dml_Indicator: 'I',
//            is_active: isActive,
//            created_by: $('#pop_doctor_id').val()
//        }
//        console.log(doctorData);
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/CaseStudy/Patient_General_Information',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(doctorData),
//            success: function (data) {
//                k++;
//                if (k == count) {
//                    SaveObservedNutrition(saveval, k);
//                }
//                if (jQuery.isEmptyObject((data))) {

//                }
//                else {

//                }
//            }
//        });
//    }
//}

//function SaveObservedNutrition(saveval, k) {
//    if ($('#totalObservedCount').val() == '' || $('#totalObservedCount').val() == null) {
//        return false;
//    }
//    var count = $('#totalObservedCount').val();
//    var j = 0;

//    for (var i = 0; i < count; i++) {
//        var type_id = $('#ObservedTypeID_' + (i + 1)).html();
//        var observedID = $('input[name="optradioObserved_' + (i + 1) + '"]:checked').val();
//        if (observedID != null && observedID != '') {
//            var doctorData = {
//                Dml_Indicator: 'I',
//                Patient_id: $('#Hdnpatient_id').val(),
//                observed_nutrition_id: observedID,
//                visit_report_id: $('#VisitReportID').val(),
//                type_id: type_id
//            }
//            $.ajax({
//                async: true,
//                type: 'POST',
//                url: '/CaseStudy/Patient_Observed_Nutrition',
//                contentType: 'application/json; charset=UTF-8',
//                data: JSON.stringify(doctorData),
//                success: function (data) {
//                    j++;
//                    if (j == count) {
//                        quickentry_save('1');
//                        if (saveval == 2) {
//                            setTimeout(function () {
//                                $('.close').click();
//                            }, 5000);
//                            $('.da-load-quickentry').hide();
//                        }
//                        else {
//                            $('.close').click();
//                            $('.da-load-quickentry').hide();
//                        }
//                    }
//                    if (jQuery.isEmptyObject((data))) {
//                        $('.da-load-quickentry').hide();
//                    }
//                    else {
//                        $('.da-load-quickentry').hide();
//                    }
//                }
//            });
//        }
//    }
//}
function LoadPatientGeneralInformation() {
    debugger;
    var doctorData = {
        Dml_Indicator: 'GS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Patient_General_Information',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var row = '';
                    var j = 0;
                    let arr = []
                    arr = data1.map((item) =>item.header);
                    let uniqueArray = [];
                    $.each(arr, function (index, value) {
                        if ($.inArray(value, uniqueArray) === -1) {
                            uniqueArray.push(value);
                        }
                    });
                    $('#PatientGeneralInformationBody').empty();
                    if (data1.length > 0) {
                        for (var q = 0; q < uniqueArray.length; q++) {
                            var filArr = data1.filter((item) =>item.header == uniqueArray[q]);
                            row = row + '<div><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 mt10" style="font-size:16px; font-weight:900;color:#3d7be3;">' + uniqueArray[q] + '</div>';
                            for (var i = 0; i < filArr.length; i++) {
                                if (filArr[i].type == "NONE") {
                                    row = row + '<div class="col-xs-12 col-md-6"><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><label  for="check_' + (j + 1) + '">' + filArr[i].type + '</label> <input type="checkbox" style="float:right;" id="check_' + (j + 1) + '" name="check_' + (j + 1) + '" value="' + filArr[i].id + '" onchange=premorbic(' + data1.length + ');> </div><div><input type="text" class="forms_field" id="GeneralInformation_' + (j + 1) + '"></div></div>'
                                }
                                else {
                                    row = row + '<div class="col-xs-12 col-md-6"><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><label  for="check_' + (j + 1) + '">' + filArr[i].type + '</label> <input type="checkbox" style="float:right;" id="check_' + (j + 1) + '" name="check_' + (j + 1) + '" value="' + filArr[i].id + '"> </div><div><input type="text" class="forms_field" id="GeneralInformation_' + (j + 1) + '"></div></div>'
                                }
                                j++;
                            }
                            row = row + '</div>'
                        }

                    }
                    $('#totalInfoCount').val(j);
                    $('#PatientGeneralInformationBody').html(row);

                    var doctorData = {
                        patient_id: $('#Hdnpatient_id').val(),
                        Dml_Indicator: 'S'
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/CaseStudy/Patient_General_Information',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(doctorData),
                        success: function (data) {
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                var data1 = data1.data;
                                if (jQuery.isEmptyObject((data1))) {

                                }
                                else {
                                    console.log(data1);

                                    var count = $('#totalInfoCount').val();
                                    if (data1.length > 0) {
                                        if (count > 0) {
                                            for (var j = 0; j < count; j++) {
                                                for (var i = 0; i < data1.length; i++) {
                                                    //if ($('#check_' + (j + 1)).val() == data1[i].type_id) {
                                                    //    $('#check_' + (j + 1)).prop("checked", data1[i].is_active);
                                                    //    $('#GeneralInformation_' + (j + 1)).val(data1[i].type_value)
                                                    //}
                                                    if ($('#check_' + (j + 1)).val() == data1[i].type_id) {
                                                        //if ($('#check_' + (j + 1)).val() == 11 && data1[i].is_active == true) {
                                                        //    $('#check_' + (j + 1)).prop("checked", data1[i].is_active);
                                                        //    $('#GeneralInformation_' + (j + 1)).val(data1[i].type_value)
                                                        //    for (var i = 1; i < data1.length; i++) {

                                                        //        $('#check_' + (i)).prop("disabled", true);
                                                        //        $('#check_' + (i)).prop("checked", false);
                                                        //        $('#GeneralInformation_' + (i)).attr("disabled", "disabled");
                                                        //        $('#GeneralInformation_' + (i)).val('');
                                                        //    }


                                                        //}
                                                        //else {
                                                        debugger;
                                                        $('#check_' + (j + 1)).prop("checked", data1[i].is_active);
                                                        $('#GeneralInformation_' + (j + 1)).val(data1[i].type_value);
                                                        //}
                                                    }

                                                }
                                            }
                                        }
                                    }

                                }

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

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
function premorbic(len) {
    if ($("#check_11").prop("checked") == true) {
        for (var i = 1; i < len; i++) {

            $('#check_' + (i)).prop("disabled", true);
            $('#check_' + (i)).prop("checked", false);
            $('#GeneralInformation_' + (i)).attr("disabled", "disabled");
            $('#GeneralInformation_' + (i)).val('');
        }
    }
    else {
        for (var i = 1; i < len; i++) {
            if ($('#check_' + (i)).prop("disabled") == true) {
                $('#check_' + (i)).prop("disabled", false);
                $('#GeneralInformation_' + (i)).removeAttr("disabled");
            }
        }
    }
}

function LoadObservedNutrition() {
    var doctorData = {
        Dml_Indicator: 'MS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Patient_Observed_Nutrition',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var row = '';
                    var type = '';

                    var j = 0;

                    $('#PatientObservedNutritionBody').empty();
                    if (data1.Table.length > 0) {
                        $('#totalObservedCount').val(data1.Table.length);
                        for (var i = 0; i < data1.Table.length; i++) {

                            var doctorData = {
                                Dml_Indicator: 'MSD',
                                type_id: data1.Table[i].id
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/CaseStudy/Patient_Observed_Nutrition',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(doctorData),
                                success: function (data) {
                                    var data2 = JSON.parse(data);
                                    if (data2.msg == "Success") {
                                        var data2 = data2.data;
                                        if (jQuery.isEmptyObject((data2))) {

                                        }
                                        else {
                                            var options = '';
                                            var type = '';


                                            if (data2.Table.length > 0) {
                                                j++;
                                                for (var k = 0; k < data2.Table.length; k++) {
                                                    type = '<div class="col-xs-12" id="ObservedType_' + (j) + '"><h5 class="cs-on-head" style="font-weight:600;">' + data2.Table[0].type + '</h5></div><span id="ObservedTypeID_' + (j) + '" hidden>' + data2.Table[0].type_id + '</span>'
                                                    options = options + '<div class="col-md-12 cus-rbtn"><div class="form-check"><label class="form-check-label"><input type="radio" class="form-check-input" name="optradioObserved_' + j + '" value=' + data2.Table[k].id + '><span>' + data2.Table[k].type_name + '</span></label></div></div>'
                                                }
                                                row = type + options;
                                                $('#PatientObservedNutritionBody').append(row);
                                            }
                                            LoadObservedNutritionVisitID();
                                        }
                                    }
                                    else {
                                        console.log(data2);
                                    }
                                }
                            });
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function LoadObservedNutritionVisitID() {
    //Load Patient Observed nutrition
    var doctorData = {
        Dml_Indicator: 'S',
        Patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val()
    }
    console.log(doctorData);
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Patient_Observed_Nutrition',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var row = '';
                    var count = $('#totalObservedCount').val();
                    if (data1.Table.length > 0) {
                        if (count > 0) {
                            for (var j = 0; j < count; j++) {
                                for (var i = 0; i < data1.Table.length; i++) {
                                    if ($('#ObservedTypeID_' + (j + 1)).html() == data1.Table[i].type_id) {
                                        $('input[name="optradioObserved_' + (j + 1) + '"][value="' + data1.Table[i].observed_nutrition_id + '"]').prop('checked', true);
                                    }

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


function SaveGeneralInformation() {
    debugger;
    if ($('#divGeneralInformation').css('display') != 'none' && ($('#totalInfoCount').val() != '' && $('#totalInfoCount').val() != null)) {
        if ($('#totalInfoCount').val() == '' || $('#totalInfoCount').val() == null) {
            return false;
        }
        var j = 0;
        var count = $('#totalInfoCount').val();
        var generalInfoArray = new Array();

        for (var i = 0; i < count; i++) {

            var generalInfo = {};

            var typeValue = $('#GeneralInformation_' + (i + 1)).val();
            var typeId = $('#check_' + (i + 1)).val();
            var isActive = ($('#check_' + (i + 1)).prop('checked') == true) ? "1" : "0";

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.type_id = typeId,
            generalInfo.type_value = typeValue,
            generalInfo.is_active = isActive,
            generalInfo.created_by = $('#doctorId').val(),
            generalInfo.Dml_Indicator = 'I'

            generalInfoArray.push(generalInfo);

        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Patient_General_Information_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(generalInfoArray),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg = "Success") {

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

    //for (var i = 0; i < count; i++) {

    //    var typeValue = $('#GeneralInformation_' + (i + 1)).val();
    //    var typeId = $('#check_' + (i + 1)).val();
    //    var isActive = ($('#check_' + (i + 1)).prop('checked') == true) ? "1" : "0";
    //    var doctorData = {
    //        patient_id: $('#Hdnpatient_id').val(),
    //        type_id: typeId,
    //        type_value: typeValue,
    //        Dml_Indicator: 'I',
    //        is_active: isActive,
    //        created_by: $('#pop_doctor_id').val()
    //    }
    //    console.log(doctorData);
    //    $.ajax({
    //        async: true,
    //        type: 'POST',
    //        url: '/CaseStudy/Patient_General_Information',
    //        contentType: 'application/json; charset=UTF-8',
    //        data: JSON.stringify(doctorData),
    //        success: function (data) {
    //            var data = JSON.parse(data);
    //            if (data.msg = "Success") {
    //                j++;
    //                if (count == j) {
    //                    
    //                    SaveObservedNutrition();
    //                }
    //            }
    //            else {
    //                console.log(data);
    //            }
    //        }
    //    });
    //}


}


function SaveObservedNutrition() {

    if ($('#divObservedNutrition').css('display') != 'none' && ($('#totalObservedCount').val() != '' && $('#totalObservedCount').val() != null)) {
        if ($('#totalObservedCount').val() == '' || $('#totalObservedCount').val() == null) {
            return false;
        }
        var j = 0;
        var count = $('#totalObservedCount').val();
        var valCount = 0;
        var observedNutritionArray = new Array();

        for (var i = 0; i < count; i++) {

            var type_id = $('#ObservedTypeID_' + (i + 1)).html();
            var observedID = $('input[name="optradioObserved_' + (i + 1) + '"]:checked').val();
            if (observedID != null && observedID != '') {

                var observedInfo = {};

                observedInfo.Patient_id = $('#Hdnpatient_id').val();
                observedInfo.type_id = type_id,
                    observedInfo.observed_nutrition_id = observedID,
                    observedInfo.visit_report_id = $('#VisitReportID').val(),
                    observedInfo.created_by = $('#doctorId').val(),
                    observedInfo.Dml_Indicator = 'I'

                observedNutritionArray.push(observedInfo);

                valCount++;
            }
            else {
                continue;
            }
        }

        if (valCount > 0) {
            $.ajax({
                async: true,
                type: 'POST',
                url: '/CaseStudy/Patient_Observed_Nutrition_Ins',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(observedNutritionArray),
                success: function (data) {

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

                        quickentry_save('1');

                    }
                    else {
                        console.log(data);
                    }
                }
            });
        }
        else {
            quickentry_save('1');
        }

        //for (var i = 0; i < count; i++) {
        //    var type_id = $('#ObservedTypeID_' + (i + 1)).html();
        //    var observedID = $('input[name="optradioObserved_' + (i + 1) + '"]:checked').val();
        //    if (observedID != null && observedID != '') {
        //        valCount++;
        //        var doctorData = {
        //            Dml_Indicator: 'I',
        //            Patient_id: $('#Hdnpatient_id').val(),
        //            observed_nutrition_id: observedID,
        //            visit_report_id: $('#VisitReportID').val(),
        //            type_id: type_id
        //        }
        //        console.log(doctorData);
        //        $.ajax({
        //            async: true,
        //            type: 'POST',
        //            url: '/CaseStudy/Patient_Observed_Nutrition',
        //            contentType: 'application/json; charset=UTF-8',
        //            data: JSON.stringify(doctorData),
        //            success: function (data) {
        //                
        //                var data = JSON.parse(data);
        //                if (data.msg == "Success") {
        //                    j++;
        //                    if (valCount == j) {
        //                        quickentry_save('1');
        //                        //diagnosis();
        //                    }
        //                }
        //                else {
        //                    console.log(data);
        //                }
        //            }
        //        });
        //    }
        //    else {
        //        continue;
        //    }
        //}
    }
    else {
        quickentry_save('1');
    }
    if (valCount == 0) {
        //diagnosis();
    }
}




function quickentry_close_berfore() {
    $('a[data-toggle=txtGlycemic]').addClass('not-active');
    $('a[data-toggle=txtGlycemic]').removeClass('active');

    $('a[data-toggle=Chknepropathy]').addClass('not-active');
    $('a[data-toggle=Chknepropathy]').removeClass('active');

    $('a[data-toggle=ChkDyslipidemia]').addClass('not-active');
    $('a[data-toggle=ChkDyslipidemia]').removeClass('active');

    $('a[data-toggle=R_tmt]').addClass('not-active');
    $('a[data-toggle=R_tmt]').removeClass('active');

    $('a[data-toggle=chkANeuropathy]').addClass('not-active');
    $('a[data-toggle=chkANeuropathy]').removeClass('active');

    $('a[data-toggle=per_neu]').addClass('not-active');
    $('a[data-toggle=per_neu]').removeClass('active');

    $('a[data-toggle=AB_index]').addClass('not-active');
    $('a[data-toggle=AB_index]').removeClass('active');

    $('a[data-toggle=chkLiver]').addClass('not-active');
    $('a[data-toggle=chkLiver]').removeClass('active');

    $('a[data-toggle=chkGS]').addClass('not-active');
    $('a[data-toggle=chkGS]').removeClass('active');

    $('a[data-toggle=acr1Q]').addClass('not-active');
    $('a[data-toggle=acr1Q]').removeClass('active');
}

$('#btnquickentryv').click(function () {
    debugger;
    $('.da-load-quickentry').show();
    SaveGeneralInformation();
    //SaveGeneralInformation(saveval);
    //VisitreportId();
});

function quickentry_save(saveval) {
    debugger;
    var height = $('#txtheightQ').val();
    var heightdb = height * 0.032808;

    heightdb = heightdb.toFixed(1);
    var heightFT = '', heightIn = '';

    var heightdbs = heightdb.split('.');
    if (heightdbs.length > 1) {
        heightFT = heightdbs[0];
        heightIn = heightdbs[1];
    }
    else {
        heightFT = heightdbs[0];
        heightIn = '0';
    }
    var value_1 = '', value_2 = '', value_3 = '';
    if ($('#txtBloodsugarV_1Q').val() != '' || $('#txtBloodsugarV_1Q').val() != null) {
        value_1 = 1;
    }
    if ($('#txtBloodsugarV_2Q').val() != '' || $('#txtBloodsugarV_2Q').val() != null) {
        value_2 = 2;
    }
    if ($('#txtBloodsugarV_3Q').val() != '' || $('#txtBloodsugarV_3Q').val() != null) {
        value_3 = 3;
    }
    var bp_flag_type;
    var Sys = $('#txtSysQ').val();
    if (Sys < 90) {
        bp_flag_type = 1;
    }
    else if (Sys >= 90 && Sys < 110) {
        bp_flag_type = 2;
    }
    else if (Sys >= 110 && Sys < 130) {
        bp_flag_type = 3;
    }
    else if (Sys >= 130 && Sys < 140) {
        bp_flag_type = 4;
    }
    else if (Sys >= 140 && Sys < 160) {
        bp_flag_type = 5;
    }
    else if (Sys >= 160 && Sys < 180) {
        bp_flag_type = 6;
    }
    else {
        bp_flag_type = 7;
    }
    var time = ''
    if ($("#txtTimetoOPD").val() != '') {
        time = $("#txtTimetoOPD").val();
    }
    else {
        time = "00:00:00.000"
    }
  //  var time = $("#txtTimetoOPD").val();
    var OPD_Time = moment(time, 'hh:mm A').format('HH:mm');

    const checkboxes = document.querySelectorAll('input[name="optionspc"]:checked');
    let paincharacter = [];
    checkboxes.forEach((checkbox) => {
        paincharacter.push(checkbox.value);
    });
    var paincharacter1 = paincharacter.toString();
    const checkboxesfrsfa = document.querySelectorAll('input[name="optionsfrsfa"]:checked');
    let frsfa = [];
    checkboxesfrsfa.forEach((checkbox) => {
        frsfa.push(checkbox.value);
    });
    var frsfa1 = frsfa.toString();

    var labval = {
        current_complaints: $('#txtComplaintsQ').val(),
        pulse_rate: $('#txtPulseRateQ').val(),
        cvs: $('#txtCVSQ').val(),
        rs: $('#txtRSQ').val(),
        abs: $('#txtABSQ').val(),
        cns: $('#txtCNSQ').val(),
        patient_bp_min: $('#txtDiaQ').val(),
        patient_bp_max: $('#txtSysQ').val(),
        patient_blood_sugar_value_1: $('#txtBloodsugarV_1Q').val(),
        patient_blood_sugar_unit_1: $('#txtBloodsugarT_1Q').val(),
        patient_blood_sugar_type_1: value_1,
        patient_blood_sugar_value_2: $('#txtBloodsugarV_2Q').val(),
        patient_blood_sugar_unit_2: $('#txtBloodsugarT_2Q').val(),
        patient_blood_sugar_type_2: value_2,
        patient_blood_sugar_value_3: $('#txtBloodsugarV_3Q').val(),
        patient_blood_sugar_unit_3: $('#txtBloodsugarT_3Q').val(),
        patient_blood_sugar_type_3: value_3,
        patient_hbac_record_value: $('#txtHbA1cQ').val(),
        ACR: $('#acr1Q').val(),
        Dml_Indicator: 'I',
        visit_report_id: $('#VisitReportID').val(),
        bp_flag_type: bp_flag_type,
        patient_id: $('#Hdnpatient_id').val(),
        created_by: $('#HiddenDoctorID').val(),
        spo2: $('#txtSpo2Q').val(),
        patient_weight: $('#txtWeightQ').val(),
        temperature: $('#txtTemperatureQ').val(),
        level_of_conscience: $('input:radio[name=optradioConsciences]:checked').val(),
        patient_height: heightFT,
        patient_height_metric: heightIn,
        Time_of_arrival_OPD: OPD_Time,
        Is_Allergies: $('#ChkAllergiesifany').val(),
        Specific_Allergies: $('#Specific_Allergies').val(),
        Is_AnyLanguageBarrior:$('#ChkAnylanguagebarrier').val(),
        Language_Cordinator:$('#SelLanguageCordinator').val(),
        Is_AlcoholIntake:$('#ChkAlcoholintake').val(),
        Is_SubstanceAbuse:$('#ChkSubstanceabuse').val(),
        Is_Smoking:$('#ChkSmoking').val(),
        Is_PainScreening: $('#ChkPainscreening').val(),
        PainScreening_Score: $('#ChkPainscreeningScore').val(),
        Is_spl_religious: $('#Chkspecialreligious').val(),
        SplReligious_SpecificDetails: $('#specialreligiousdetails').val(),
        //Duration: $('#Duration').val(),
        //Location: $('#Location').val(),

        Is_Pshychosocial_Assessment:$('input:radio[name=optradioPsychosocial_assessment]:checked').val(),
        //Is_Pain_Character:$('input:radio[name=optradioPaincharacter]:checked').val(),
        Is_Nutritional_Screening_Appetie: $('input:radio[name=optradionutri_scr_appetie]:checked').val(),
        Is_Nutritional_Screening_weight: $('input:radio[name=optradionutri_scr_weight]:checked').val(),
        //Is_Fallrisks_Screeningforadults: $('input:radio[name=optradiofall_risk]:checked').val(),

        vas: $('#emoNPDRradio').val(),
        vasduration: $('#txtvasduration').val(),
        vaslocation: $('#txtvaslocation').val(),
        vaspaincharacter: paincharacter1,
        vasfullrisk: frsfa1
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Quick_entry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            $('.close').click();
            $('.da-load-quickentry').hide();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    //if (data.length > 2) {
                    //}
                }
                if (saveval == 2) {
                    setTimeout(function () {
                        $('.close').click();
                    }, 5000);
                }
                else {
                    $('.close').click();
                }

                //$('#txtComplaints').val($('#txtComplaintsQ').val());
                //$('#txtPulseRate').val($('#txtPulseRateQ').val());
                //$('#txtCVS').val($('#txtCVSQ').val());
                //$('#txtRS').val($('#txtRSQ').val());
                //$('#txtABS').val($('#txtABSQ').val());
                //$('#txtCNS').val($('#txtCNSQ').val());
                //$('#txtDia').val($('#txtDiaQ').val());
                //$('#txtSys').val($('#txtSysQ').val());
                //$('#txtBloodsugarV_1').val($('#txtBloodsugarV_1Q').val());
                //$('#txtBloodsugarT_1').val($('#txtBloodsugarT_1Q').val());
                //$('#txtBloodsugarV_2').val($('#txtBloodsugarV_2Q').val());
                //$('#txtBloodsugarT_2').val($('#txtBloodsugarT_2Q').val());
                //$('#txtBloodsugarV_3').val($('#txtBloodsugarV_3Q').val());
                //$('#txtBloodsugarT_3Q').val($('#txtBloodsugarT_3Q').val());
                //$('#txtHbA1c').val($('#txtHbA1cQ').val());
                //$('#acr1').val($('#acr1Q').val());
                //$('a[data-toggle=acr1][data-title="' + $('#acr1').val() + '"]').removeClass('not-active');
                //$('a[data-toggle=acr1][data-title="' + $('#acr1').val() + '"]').addClass('active');
                $('a[data-toggle=acr1Q]').addClass('not-active');
                $('a[data-toggle=acr1Q]').removeClass('active');
                //SaveGeneralInformation(saveval);
                //SaveGeneralInformation();
                toastr.success("Vitals Saved Successfully...!!!")
            }
            else {
                console.log(data);
            }

        }
    });

}

function VisitreportId() {

    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: '15'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            console.log(data);
            var data = JSON.parse(data);
            if (data.msg = "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    console.log(data);
                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        console.log(VisitReportID);
                        //quickentry_save('1');
                    }


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

    });
}

$('#btnquickentryl').click(function () {
    VisitreportId_lab();
});

function VisitreportId_lab() {
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: '15'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {

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

            }
            else {
                var data = JSON.parse(data);
                if (data.Table.length > 0) {
                    var VisitReportID = (data.Table[0].VisitReport_id);
                    $('#VisitReportID').val(VisitReportID);
                    labtest();
                    quickentry_save('2');
                }

            }
        }
    });
}

function labtest() {
    $('.da-load-quickentry').show();
    if ($('#txtnotes').val() == '' && $('#txtHypoglycemic').val() == '' && $('#txtGlycemic').val() == 0 && $('#txtCVS').val() == '' && $('#txtABS').val() == '' && $('#txtRS').val() == '' && $('#txtCNS').val() == '' && $('#ChkHeartSound').prop('checked') == false && $('#ChkMurmurs').prop('checked') == false && $('#ChkReducedAir').prop('checked') == false && $('#ChkCrackles').prop('checked') == false && $('#ChkBowelSounds').prop('checked') == false && $('#ChkOrganomegaly').prop('checked') == false && $('#ChkTremors').prop('checked') == false && $('#ChkCognitive').prop('checked') == false) {
    }
    else {
        var Glycemic_variability = $("input[name='txtGlycemic']").val();

        var heart_sound, murmurs, reduce_air_entry, bowel_sounds, organomeglay, tremors_weakness, cognitive_imparement;
        if ($('#ChkHeartSound').prop('checked')) {
            heart_sound = 1;
        } else {
            heart_sound = 0;
        }
        if ($('#ChkMurmurs').prop('checked')) {
            murmurs = 1
        } else {
            murmurs = 0
        }
        if ($('#ChkReducedAir').prop('checked')) {
            reduce_air_entry = 1
        } else {
            reduce_air_entry = 0
        }
        if ($('#ChkCrackles').prop('checked')) {
            crackles = 1
        } else {
            crackles = 0
        }
        if ($('#ChkBowelSounds').prop('checked')) {
            bowel_sounds = 1
        } else {
            bowel_sounds = 0
        }
        if ($('#ChkOrganomegaly').prop('checked')) {
            organomeglay = 1
        } else {
            organomeglay = 0
        }
        if ($('#ChkTremors').prop('checked')) {
            tremors_weakness = 1
        } else {
            tremors_weakness = 0
        }
        if ($('#ChkCognitive').prop('checked')) {
            cognitive_imparement = 1
        } else {
            cognitive_imparement = 0
        }
        var Dml_Indicator = 'QI';

        var ObservationData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            hypoglycemia_episodes: $('#txtHypoglycemic').val(),
            glycemic_variability: Glycemic_variability,
            cvs: $('#txtCVS').val(),
            heart_sound: heart_sound,
            murmurs: murmurs,
            rs: $('#txtRS').val(),
            reduce_air_entry: reduce_air_entry,
            crackles: crackles,
            ABS: $('#txtABS').val(),
            bowel_sounds: bowel_sounds,
            organomeglay: organomeglay,
            CNS: $('#txtCNS').val(),
            tremors_weakness: tremors_weakness,
            cognitive_imparement: cognitive_imparement,
            patient_id: $('#Hdnpatient_id').val(),
            created_by: $('#pop_doctor_id').val(),
            note: $('#txtnotes').val(),
        }

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

                }
                else {
                    var data = JSON.parse(data);
                    if (data.length > 0) {
                        if (data[0].StringMsg == "success") {

                        }
                    }

                }
            }
        });
    }
    //complaints end point

    //Glycemic Parameters start point

    if ($('#txtfastingInsulin').val() == '' && $('#txtWBC').val() == '' && $('#txtHB').val() == '' && $('#txtPlatelets').val() == '' && $('#txtnotes_glycemic').val() == '') {

    }
    else {


        Dml_Indicator = 'IQ';

        var GlycemicData = {

            Dml_Indicator: Dml_Indicator,

            visit_report_id: $('#VisitReportID').val(),
            set_by: $('#doctorId').val(),
            created_by: $('#doctorId').val(),
            patient_id: $('#Hdnpatient_id').val(),
            hemoglobin: $('#txtHB').val(),
            patient_hbac_record_value: $('#txtHbA1c').val(),
            fasting_insulin: $('#txtfastingInsulin').val(),
            fasting_inslin_unit: $('#txtfastingInsulin_T').val(),
            WBC: $('#txtWBC').val(),
            patient_blood_group: $('#Selbloodgroup').val(),
            patient_id: $('#Hdnpatient_id').val(),
            platelet: $('#txtPlatelets').val(),
            note: $('#txtnotes_glycemic').val()
        }



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

                }
                else {
                    if (data[0].StringMsg == "success") {

                    }
                }
            }
        });
    }
    //Glycemic Parameters end point

    //Renal start point
    if ($('#txtUrea').val() == '' && $('#txtCreatinine').val() == '' && $('#txtCKD').val() == '' && $('#txtSodium').val() == '' && $('#txtCalcium').val() == '' && $('#txtPotassium').val() == '' && $('#txtPhosphorus').val() == '' && $('#txtChlorine').val() == '' && $('#txtMagnesium').val() == '' && $('#txtBiCrabonate').val() == '' && $('#txtnotes_renal').val() == '') {

    }
    else {
        var ACR = $("input[name='acr1']").val();

        var nephropathy = $('#Chknepropathy').val()

        var Dml_Indicator = 'QI';
        $("#btnRenal").html('Update & Next')
        var egfr = $('#txtEGFR').val();
        var egfr_value = egfr.split('ml');
        egfr = egfr_value[0];

        var RenalData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            nephropathy: nephropathy,
            Urea: $('#txtUrea').val(),
            urea_unit: '1',
            egfr_value: egfr,
            creatinine: $('#txtCreatinine').val(),
            Creatinine_unit: $('#SelCreatinine').val(),
            stage_CKD: $('#txtCKDVal').val(),
            Sodium: $('#txtSodium').val(),
            sodium_unit: $('#SelSodium').val(),
            Potassium: $('#txtPotassium').val(),
            potassium_unit: $('#SelPotassium').val(),
            Chlorine: $('#txtChlorine').val(),
            chlorine_unit: $('#SelChlorine').val(),

            BiCarbonate: $('#txtBiCrabonate').val(),
            Bicarbonate_unit: $('#SelBicrabonate').val(),
            Urine_routine: '',

            serium_calcium: $('#txtCalcium').val(),
            Calcium_unit: $('#SelCalcium').val(),

            serium_phosphorous: $('#txtPhosphorus').val(),
            Phosphorus_unit: $('#SelPhosphorus').val(),

            serium_magnesium: $('#txtMagnesium').val(),
            Magnesium_unit: $('#SelMagnesium').val(),
            note: $('#txtnotes_renal').val()
        }

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

                }
                else {
                    if (data[0].StringMsg == "success") {

                    }
                }
            }
        });
    }

    //Renal end point

    //cholestral start point

    if ($('#txtTCholesterol').val() == '' && $('#txtVLDL').val() == '' && $('#txtLDL').val() == '' && $('#txtTriglycerides').val() == '' && $('#txtHDL').val() == '' && $('#txtHDLRatio').val() == '' && $('#txtnotes_cholesterol').val() == '') {

    }
    else {

        var dyslipedemia = $('#ChkDyslipidemia').val();

        var Dml_Indicator = "I";

        var cholestrol = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            LDL: $('#txtLDL').val(),
            LDL_unit: $('#SelLDL').val(),
            HDL: $('#txtHDL').val(),
            HDL_unit: $('#SeltxtHDL').val(),
            Total_Cholestrol: $('#txtTCholesterol').val(),
            Total_cholestrol_unit: $('#SelTCholesterol').val(),
            Triglycerides: $('#txtTriglycerides').val(),
            Triglycerides_unit: $('#SelTriglycerides').val(),
            VLDL: $('#txtVLDL').val(),
            VLDL_unit: $('#SelVLDL').val(),
            T_cholestrol_Hdl_ratio: $('#txtHDLRatio').val(),
            dyslipedemia: dyslipedemia,
            note: $('#txtnotes_cholesterol').val()
        }

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

                }
                else {
                    if (data[0].StringMsg == "success") {

                    }
                }
            }
        });
    }
    //cholestral start end

    //cardiac start point
    if ($('#txtecg').val() == '' && $('#txtecho').val() == '' && ($('#R_tmt').val == '' || $('#R_tmt').val == 0) && $('#Chkecg').prop('checked') == false && $('#Selecho').prop('checked') == false && $('#txtnotes_cardiac').val() == '') {

    }
    else {

        var TMT_test = $("input[name='R_tmt']").val();

        var ecg_abnormal = '0', echo_abnormal = '0', ON_Hypertension_drugs = '0', ON_statin = '0', ON_Aspirin_Theraphy = '0'
        if ($('#Chkecg').prop('checked')) {
            ecg_abnormal = '1';
        }
        if ($('#Selecho').prop('checked')) {
            echo_abnormal = '1';
        }

        Dml_Indicator = 'IQ';
        var Cardiac = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            ECG: $('#txtecg').val(),
            ecg_abnormal: ecg_abnormal,
            ECHO: $('#txtecho').val(),
            echo_abnormal: echo_abnormal,
            TMT_test: TMT_test,
            note: $('#txtnotes_cardiac').val()
        }


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

                }
                else {
                }
            }
        });
    }
    //cardiac end point

    //Neuropathy start point
    if (($('#per_neu').val == '' || $('#per_neu').val == 0) && ($('#chkANeuropathy').val() == '' || $('#chkANeuropathy').val() == 0) && $('#txtDoppler').val() == '' && $('#AB_index').val() == '' && $('#txtnotes_neuropathy').val() == '') {

    }
    else {
        var peripharal_neuhropathy = $("input[name='per_neu']").val();
        var AB_index = $("input[name='AB_index']").val();
        var ANeuropathy = $('#chkANeuropathy').val();

        Dml_Indicator = 'I';
        var cholestrol = {
            visit_report_id: $('#VisitReportID').val(),
            peripharal_neuhropathy: peripharal_neuhropathy,
            autonomic_neuropathy: ANeuropathy,
            autonomic_neuropathy_set_by: $('#pop_doctor_id').val(),
            AB_index: AB_index,
            doppler_note: $('#txtDoppler').val(),
            note: $('#txtnotes_neuropathy').val(),
            Dml_Indicator: Dml_Indicator,
            patient_id: $('#Hdnpatient_id').val()
        }

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

                }
                else {

                }
            }
        });
    }

    //Neuropathy end point

    //Thyroid start point
    if ($('#txtT3').val() == '' && $('#txtT4').val() == '' && $('#txtTSH').val() == '' && $('#txtnotes_thyroid').val() == '') {

    }
    else {
        var Dml_Indicator;
        Dml_Indicator = 'I';
        var cholestrols = {
            visit_report_id: $('#VisitReportID').val(),
            Free_T3: $('#txtT3').val(),
            Free_T3_unit: $('#SelT3').val(),
            Free_T4: $('#txtT4').val(),
            Free_T4_unit: $('#SelT4').val(),
            TSH: $('#txtTSH').val(),
            TSH_unit: $('#SelTSH').val(),
            note: $('#txtnotes_thyroid').val(),
            Dml_Indicator: Dml_Indicator
        }

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

                }
                else {
                }
            }
        });
    }
    //Thyroid end point

    //ultrasound start point 
    if ($('#txtNotes').val() == '' && $('#txtUNotes').val() == '' && ($('#chkLiver').val == '' || $('#chkLiver').val == 0) && ($('#chkGS').val == '' || $('#chkGS').val == 0)) {

    }
    else {
        var fatty_lives = $('#chkLiver').val(),
            GS_Calculus = $('#chkGS').val();
        var Dml_Indicator;

        Dml_Indicator = 'I';

        var UltraSound = {
            visit_report_id: $('#VisitReportID').val(),
            notes: $('#txtNotes').val(),
            fatty_lives: fatty_lives,
            GS_Calculus: GS_Calculus,
            UNOTES: $('#txtUNotes').val(),
            Dml_Indicator: Dml_Indicator
        }

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

                }
                else {
                }


            }
        });
    }
    // ultrasound end point
    setTimeout(function () {
        quickentry_close();
        $('.da-load-quickentry').hide();
    }, 5000);


}

function LC_CreatinineCal() {
    var gender = $('#gender').val();
    var age = '0';
    if ($('#Dage').val() == '' || $('#Dage').val() == null) {
        age = $('#age').val();
    }
    else {
        age = $('#Dage').val();
    }
    if (gender == "" || age == "") {
        $('#PtxtEGFR').html('Age / Gender value missing. Enter calculted eGFR');
        $('#PtxtEGFR').show();
        $('#PtxtEGFR').fadeOut(8000);
        $('#txtEGFR').focus();
        return false;
    }
    var Creatinine = $.trim($('#LC_txtCreatinine').val());
    var Creatinineunit = $('#LC_SelCreatinine').val();
    if (Creatinine == '') {
    }
    else {
        if (Creatinineunit == 2) {
            Creatinine = (Creatinine * 88.4);
        }
        var genderval = 1;
        if (gender == 2) {
            genderval = 0.742;
        }
        else if (gender == 1) {
            genderval = 1;
        }
        var aa = Math.round(186 * Math.pow((Creatinine / 88.4), -1.154) * Math.pow(age, -0.203) * genderval);
        if (aa == "Infinity") {
            aa = "-";
        }
        $('#LC_txtEGFR').val(aa + ' ml/min/1.73m2');
        $('#txtCKDVal').val(aa);

        if (aa >= 90) {
            $('#LC_txtCKD').val('Stage 1');
        }
        if (aa >= 60 && aa <= 89) {
            $('#LC_txtCKD').val('Stage 2');
        }
        if (aa >= 45 && aa <= 59) {
            $('#LC_txtCKD').val('Stage 3A');
        }
        if (aa >= 30 && aa <= 44) {
            $('#LC_txtCKD').val('Stage 3B');
        }
        if (aa >= 15 && aa <= 29) {
            $('#LC_txtCKD').val('Stage 4');
        }
        if (aa < 15) {
            $('#LC_txtCKD').val('Stage 5');
        }
        var DCKD = $('#LC_txtCKD').val();
        $('#DKindly').html(DCKD);
    }
}
function quickentry_lab(patient_id, slot_start_time) {
    $('.da-load-quickentry').show();
    var labval = {
        patient_id: patient_id,
        slot_time: slot_start_time
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Quick_entry_lab_test_select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            $('.da-load-quickentry').hide();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {


                    if (data.Table.length > 0) {
                        $('#txtComplaints').val(data.Table[0].current_complaints);
                        $('#txtHypoglycemic').val(data.Table[0].hypoglycemia_episodes);
                        var glycemic_variability = data.Table[0].glycemic_variability;
                        $('#txtGlycemic').val(glycemic_variability);
                        $('a[data-toggle=txtGlycemic][data-title="' + glycemic_variability + '"]').addClass('active');
                        $('#txtCVS').val(data.Table[0].cvs);
                        var heart_sound = data.Table[0].heart_sound;
                        if (heart_sound == 1) {
                            $('#ChkHeartSound').prop('checked', true);
                        }
                        if (data.Table[0].murmurs == 1) {
                            $('#ChkMurmurs').prop('checked', true);
                        }

                        $('#txtABS').val(data.Table[0].ABS);
                        if (data.Table[0].bowel_sounds == 1) {
                            $('#ChkBowelSounds').prop('checked', true);
                        }
                        if (data.Table[0].organomeglay == 1) {
                            $('#ChkOrganomegaly').prop('checked', true);
                        }

                        $('#txtRS').val(data.Table[0].rs);
                        if (data.Table[0].reduce_air_entry == 1) {
                            $('#ChkReducedAir').prop('checked', true);
                        }
                        if (data.Table[0].crackles == 1) {
                            $('#ChkCrackles').prop('checked', true);
                        }

                        $('#txtCNS').val(data.Table[0].CNS);

                        if (data.Table[0].tremors_weakness == 1) {
                            $('#ChkTremors').prop('checked', true);
                        }
                        if (data.Table[0].cognitive_imparement == 1) {
                            $('#ChkCognitive').prop('checked', true);
                        }

                        $('#txtnotes').val(data.Table[0].note);
                        $('#txtSPO2').val(data.Table[0].spo2);
                    }
                    if (data.Table1.length > 0) {
                        $('#txtHB').val(data.Table1[0].hemoglobin);
                        $('#txtfastingInsulin').val(data.Table1[0].fasting_insulin);
                        $('#txtfastingInsulin_T').val(data.Table1[0].fasting_inslin_unit);
                        $('#txtnotes_glycemic').val(data.Table1[0].note);
                        $('#txtWBC').val(data.Table1[0].WBC);
                        $('#txtPlatelets').val(data.Table1[0].platelet);
                    }
                    if (data.Table2.length > 0) {
                        $('#txtHbA1c').val(data.Table2[0].patient_hbac_record_value);
                    }
                    if (data.Table3.length > 0) {

                        $('#txtUrea').val(data.Table3[0].Urea);
                        $('#SelUrea').val(data.Table3[0].urea_unit);
                        $('#txtCreatinine').val(data.Table3[0].creatinine);
                        $('#SelCreatinine').val(data.Table3[0].Creatinine_unit);
                        $('#txtEGFR').val(data.Table3[0].egfr_value);
                        $('#txtSodium').val(data.Table3[0].Sodium);
                        $('#SelSodium').val(data.Table3[0].sodium_unit);
                        $('#txtPotassium').val(data.Table3[0].Potassium);
                        $('#SelPotassium').val(data.Table3[0].potassium_unit);
                        $('#txtChlorine').val(data.Table3[0].Chlorine);
                        $('#SelChlorine').val(data.Table3[0].chlorine_unit);
                        $('#txtBiCrabonate').val(data.Table3[0].BiCarbonate);
                        $('#SelBicrabonate').val(data.Table3[0].Bicarbonate_unit);
                        $('#txtCalcium').val(data.Table3[0].serium_calcium);
                        $('#SelCalcium').val(data.Table3[0].Calcium_unit);
                        $('#txtPhosphorus').val(data.Table3[0].serium_phosphorous);
                        $('#SelPhosphorus').val(data.Table3[0].Phosphorus_unit);
                        $('#txtMagnesium').val(data.Table3[0].serium_magnesium);
                        $('#SelMagnesium').val(data.Table3[0].Magnesium_unit);
                        $('#txtnotes_renal').val(data.Table3[0].note);
                    }
                    if (data.Table4.length > 0) {
                        var ACR = data.Table4[0].ACR;
                        $('#acr1').val(ACR);
                        $('a[data-toggle=acr1][data-title="' + ACR + '"]').removeClass('not-active');
                        $('a[data-toggle=acr1][data-title="' + ACR + '"]').addClass('active');
                        var Chknepropathy = data.Table4[0].nephropathy;

                        $('#Chknepropathy').val(Chknepropathy);
                        $('a[data-toggle=Chknepropathy][data-title="' + Chknepropathy + '"]').addClass('active');

                        var txtCKDVal = data.Table4[0].stage_CKD;
                        $('#txtCKDVal').val(txtCKDVal);
                        if (txtCKDVal >= 90) {
                            $('#txtCKD').val('Stage 1');
                        }
                        if (txtCKDVal >= 60 && txtCKDVal <= 89) {
                            $('#txtCKD').val('Stage 2');
                        }
                        if (txtCKDVal >= 45 && txtCKDVal <= 59) {
                            $('#txtCKD').val('Stage 3A');
                        }
                        if (txtCKDVal >= 30 && txtCKDVal <= 44) {
                            $('#txtCKD').val('Stage 3B');
                        }
                        if (txtCKDVal >= 15 && txtCKDVal <= 29) {
                            $('#txtCKD').val('Stage 4');
                        }
                        if (txtCKDVal < 15) {
                            $('#txtCKD').val('Stage 5');
                        }
                    }

                    if (data.Table5.length > 0) {
                        $('#txtLDL').val(data.Table5[0].LDL);
                        $('#SelLDL').val(data.Table5[0].LDL_unit);
                        $('#txtTCholesterol').val(data.Table5[0].Total_Cholestrol);
                        $('#SelTCholesterol').val(data.Table5[0].Total_cholestrol_unit);
                        $('#txtVLDL').val(data.Table5[0].VLDL);
                        $('#SelVLDL').val(data.Table5[0].VLDL_unit);
                        $('#txtHDL').val(data.Table5[0].HDL);
                        $('#SeltxtHDL').val(data.Table5[0].HDL_unit);
                        $('#txtTriglycerides').val(data.Table5[0].Triglycerides);
                        $('#SelTriglycerides').val(data.Table5[0].Triglycerides_unit);
                        $('#txtHDLRatio').val(data.Table5[0].T_cholestrol_Hdl_ratio);
                        $('#txtnotes_cholesterol').val(data.Table5[0].note);
                    }
                    if (data.Table6.length > 0) {

                        var ChkDyslipidemia = data.Table6[0].dyslipedemia;

                        $('#ChkDyslipidemia').val(ChkDyslipidemia);
                        $('a[data-toggle=ChkDyslipidemia][data-title="' + ChkDyslipidemia + '"]').addClass('active');
                    }
                    if (data.Table7.length > 0) {
                        $('#txtecg').val(data.Table7[0].ECG);
                        $('#txtecho').val(data.Table7[0].ECHO);
                        var R_tmt = (data.Table7[0].TMT_test);
                        var ecg_abnormal = (data.Table7[0].ecg_abnormal);
                        var echo_abnormal = (data.Table7[0].echo_abnormal);
                        $('#txtnotes_cardiac').val(data.Table7[0].note);
                        $('#R_tmt').val(R_tmt);
                        $('a[data-toggle=R_tmt][data-title="' + R_tmt + '"]').addClass('active');
                        if (ecg_abnormal == '1') {
                            $("#Chkecg").prop('checked', true);
                        }
                        if (echo_abnormal == '1') {
                            $("#Selecho").prop('checked', true);
                        }
                        var txtDrugs = data.Table7[0].ON_Hypertension_drugs;
                        var txtStatin = data.Table7[0].ON_statin;
                        var txtTherapy = data.Table7[0].ON_Aspirin_Theraphy;

                        if (txtDrugs == "1") {
                            $("#txtDrugs").prop('checked', true).change();
                        }
                        else {
                            $("#txtDrugs").prop('checked', false).change();
                        }
                        if (txtStatin == "1") {
                            $("#txtStatin").prop('checked', true).change();
                        }
                        else {
                            $("#txtStatin").prop('checked', false).change();
                        }
                        if (txtTherapy == "1") {
                            $("#txtTherapy").prop('checked', true).change();
                        }
                        else {
                            $("#txtTherapy").prop('checked', false).change();
                        }
                    }
                    if (data.Table8.length > 0) {
                        var chkANeuropathy = (data.Table8[0].autonomic_neuropathy);
                        $('#chkANeuropathy').val(chkANeuropathy);
                        $('a[data-toggle=chkANeuropathy][data-title="' + chkANeuropathy + '"]').addClass('active');
                    }
                    if (data.Table9.length > 0) {

                        $('#txtDoppler').val(data.Table9[0].doppler_note);
                        $('#txtnotes_neuropathy').val(data.Table9[0].note);
                        var PeripheralNeuropathy = data.Table9[0].peripharal_neuhropathy;
                        var ABIndex = data.Table9[0].AB_index;

                        $('#per_neu').val(PeripheralNeuropathy);
                        $('a[data-toggle=per_neu][data-title="' + PeripheralNeuropathy + '"]').addClass('active');

                        $('#AB_index').val(ABIndex);
                        $('a[data-toggle=AB_index][data-title="' + ABIndex + '"]').addClass('active');
                    }

                    if (data.Table10.length > 0) {
                        $('#txtT3').val(data.Table10[0].Free_T3);
                        $('#txtT4').val(data.Table10[0].Free_T4);
                        $('#txtTSH').val(data.Table10[0].TSH);
                        $('#txtnotes_thyroid').val(data.Table10[0].note);
                    }
                    if (data.Table11.length > 0) {
                        $('#txtNotes').val(data.Table11[0].notes);
                        var chkLiver = (data.Table11[0].fatty_lives);
                        var chkGS = (data.Table11[0].GS_Calculus);
                        $('#txtUNotes').val(data.Table11[0].USNotes);
                        $('#chkLiver').val(chkLiver);
                        $('a[data-toggle=chkLiver][data-title="' + chkLiver + '"]').addClass('active');

                        $('#chkGS').val(chkGS);
                        $('a[data-toggle=chkGS][data-title="' + chkGS + '"]').addClass('active');
                    }

                    if (data.Table12.length > 0) {
                        $('#Selbloodgroup').val(data.Table12[0].patient_blood_group);
                    }
                    if (data.Table13.length > 0) {
                        $('#Dage').val(data.Table13[0].Dage);
                        $('#age').val(data.Table13[0].age);
                        $('#gender').val(data.Table13[0].gender);
                    }

                }
                $('.da-load-quickentry').hide();
            }

            else {
                console.log(data);
            }
        }

    });
}



function quickentry_close() {
    $('a[data-toggle=txtGlycemic]').addClass('not-active');
    $('a[data-toggle=txtGlycemic]').removeClass('active');

    $('a[data-toggle=Chknepropathy]').addClass('not-active');
    $('a[data-toggle=Chknepropathy]').removeClass('active');

    $('a[data-toggle=ChkDyslipidemia]').addClass('not-active');
    $('a[data-toggle=ChkDyslipidemia]').removeClass('active');

    $('a[data-toggle=R_tmt]').addClass('not-active');
    $('a[data-toggle=R_tmt]').removeClass('active');

    $('a[data-toggle=chkANeuropathy]').addClass('not-active');
    $('a[data-toggle=chkANeuropathy]').removeClass('active');

    $('a[data-toggle=per_neu]').addClass('not-active');
    $('a[data-toggle=per_neu]').removeClass('active');

    $('a[data-toggle=AB_index]').addClass('not-active');
    $('a[data-toggle=AB_index]').removeClass('active');

    $('a[data-toggle=chkLiver]').addClass('not-active');
    $('a[data-toggle=chkLiver]').removeClass('active');

    $('a[data-toggle=chkGS]').addClass('not-active');
    $('a[data-toggle=chkGS]').removeClass('active');

    $('a[data-toggle=acr1Q]').addClass('not-active');
    $('a[data-toggle=acr1Q]').removeClass('active');
    $('.close').click();
}

//quickentry end



//lab test start

function full_lab_test_old(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time) {
    $('.da-load-lab_test').show();
    //alert('ds');
    $('#LC_txtfastingInsulin_T,#LC_txtBloodsugarT_1,#LC_txtBloodsugarT_2,#LC_txtBloodsugarT_3,#LC_txtBloodsugarT_4,#LC_txtBloodsugarT_5,LC_txtBloodsugarT_6,#LC_txtBloodsugarT_7,#LC_txtBloodsugarT_8,#LC_SelTCholesterol,#LC_SelLDL,#LC_SelVLDL,#LC_SelTriglycerides,#LC_SeltxtHDL,#LC_SelT3,#LC_SelT3,#LC_SelTSH,#LC_SelT4,#LC_SelT4').val('1');
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('.da-load-lab_test').hide();

    var labval = {
        Dml_Indicator: 'S',
    }

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

            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data = JSON.parse(data);
                if (data.length > 0) {
                    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
                    var tr = '', j = 1;
                    var a = data.length;
                    var trval = '<thead><tr><th>Category</th><th class="none"><table class="nchild"><tr class="lt-hm-show-head"><td class="col-md-2"> Unit </td></tr></table></th></tr></thead>'
                        + '<tbody><tr class="odd parent"><td>Category 3</td><td><table class="nchild"><tr><td class="col-md-3"> Hb </td><td class="col-md-2"> <input type="text" class="sm-field" name="obs_val" id="obs_val1" /> </td><td class="col-md-5">8-12</td><td class="col-md-2">anirudh backend</td></tr><tr><td> Hb </td><td> <input type="text" class="sm-field" name="obs_val" id="obs_val2" /> </td><td>8-12</td><td>mmhg</td></tr>'
                        + '<tr><td> Hb </td><td> <input type="text" class="sm-field" name="obs_val" id="obs_val3" /></td><td>8-12</td><td>mmhg</td></tr></table></td></tr>'
                        + '<tr> <td>Category 4</td> <td><table class="nchild"><tr><td class="col-md-3"> Hb </td><td class="col-md-2"> <input type="text" class="sm-field" name="obs_val" id="obs_val4" /> </td><td class="col-md-5">8-12</td>'
                        + '<td class="col-md-2">	Anands</td></tr><tr><td> Hb </td><td> <input type="text" class="sm-field" name="obs_val" id="obs_val5" /> </td><td>	mmhg</td><td>mmhg</td>'
                        + '</tr><tr><td> Hb </td><td> <input type="text" class="sm-field" name="obs_val" id="obs_val6" /> </td><td>8-12</td><td>mmhg</td></tr></table></td></tr></tbody >';

                    for (var i = 0; i < data.length; i++) {
                        if (i == 0) {
                            tr = tr + '<thead><tr><th>Category</th><th class="none"><table class="nchild"><tr class="lt-hm-show-head"><td class="col-md-3">test</td><td class="col-md-2">Observed</td><td class="col-md-5"> Ref</td><td class="col-md-2"> Unit </td></tr></table></th></tr></thead><tbody>'
                            tr = tr + '<tr><td>' + data[i].parameter_group + '</td><td><table class="nchild">'
                        }
                        tr = tr + '<tr><td class="col-md-3">' + data[i].parameter_name + '</td><td class="col-md-2"><input type="text" class="sm-field" name="obs_val" id="' + data[i].parameter_id + '"/></td><td class="col-md-5">' + data[i].reference_value + '</td><td class="col-md-2">' + data[i].unit + '</td></tr>';
                        if (a == j) {

                            if (data[i].parameter_group != data[i].parameter_group) {
                                tr = tr + '</table></td></tr>';
                                tr = tr + '<tr><td>' + data[i].parameter_group + '</td><td><table class="nchild">'
                            }
                        }
                        else {
                            if (data[i].parameter_group != data[j].parameter_group) {
                                tr = tr + '</table></td></tr>';
                                tr = tr + '<tr><td>' + data[j].parameter_group + '</td><td><table class="nchild">'
                            }
                        }

                        j++;
                    }
                }
                var end = '</table></td></tr></tbody>';
                $.when($('#labParameters').html(tr)).then(sp());
                var labval = {
                    Dml_Indicator: 'SS',
                    patient_id: patient_id,
                    slot_time: slot_start_time
                }

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

                            if (data.length > 0) {
                                if (data[0].VVisit_report_id == '' || data[0].VVisit_report_id == null) {

                                }
                                else {
                                    for (var i = 0; i < data.length; i++) {
                                        $('#' + data[i].parameter_id).val(data[i].parameter_value);
                                    }
                                }
                            }

                        }
                    }
                });
            }
        }
    });
}

var aa = 1;
function sp() {

    aa++;
    var row_id = [];
    var table = $('#labParameters').DataTable({
        'columnDefs': [
            {

                'targets': [1, 2],
                'render': function (data, type, row, meta) {
                    if (type === 'display') {

                        alert('hello2');
                        var api = new $.fn.dataTable.Api(meta.settings);

                        var $el = $('input, select, textarea', api.cell({ row: meta.row, column: meta.col }).node());

                        var $html = $(data).wrap('<div/>').parent();

                        if ($el.prop('tagName') === 'INPUT') {

                            if (row_id.length > 0) {
                                var myNewArray = row_id.filter(function (elem, index, self) {
                                    return index === self.indexOf(elem);
                                });
                                $.each(myNewArray, function (i, val) {
                                    console.log(val, $el.val());
                                    $('#' + val.class, $html).attr('value', val.value);

                                })
                            }


                            if ($el.prop('checked')) {
                                $('input', $html).attr('checked', 'checked');

                            }
                        } else if ($el.prop('tagName') === 'TEXTAREA') {
                            $('textarea', $html).html($el.val());

                        } else if ($el.prop('tagName') === 'SELECT') {
                            $('option:selected', $html).removeAttr('selected');
                            $('option', $html).filter(function () {
                                return ($(this).attr('value') === $el.val());
                            }).attr('selected', 'selected');
                        }

                        data = $html.html();
                    }

                    return data;
                }
            }
        ],

        'responsive': true
    });


    // Update original input/select on change in child row

    row_id = [];
    $('#labParameters tbody').on('change', '.child input', function (e) {
        var $el = $(this);
        var cls = $el.attr('id')
        row_id.push({ 'class': cls, 'value': $el.val() });

        var rowIdx = $el.closest('ul').data('dtr-index');
        var colIdx = $el.closest('li').data('dtr-index');
        //console.log(row);
        var cell = table.cell({ row: rowIdx, column: colIdx }).node();


        $("input", cell).val($el.val());
        console.log($el.val());

        if ($el.is(':checked')) {

            $('input', rowIdx).prop('checked', true);
        } else {
            $('input', rowIdx).removeProp('checked');
        }
    });
    // Handle click on "Expand All" button
    $('#btn-show-all-children').on('click', function () {
        // Expand row details
        table.rows(':not(.parent)').nodes().to$().find('td:first-child').trigger('click');
    });

    // Handle click on "Collapse All" button
    $('#btn-hide-all-children').on('click', function () {
        // Collapse row details
        table.rows('.parent').nodes().to$().find('td:first-child').trigger('click');
    });
    // Input focus show all tabs
    $('#labParametersListTableInput').focus(function () {
        // Collapse row details
        table.rows(':not(.parent)').nodes().to$().find('td:first-child').trigger('click');
    });
}


$('#btnMasterlabtest').click(function () {
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: '15'
    }

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

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        $('#labParameters tr input[type=text]').each(function () {
                            if ($(this).val() != '' && $(this).val() != '') {
                                var id = $(this).attr('id');
                                var val = $(this).val();
                                var labval = {
                                    visit_report_id: $('#VisitReportID').val(),
                                    parameter_value: val,
                                    parameter_id: id,
                                    Dml_Indicator: 'I',
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/caseStudy/master_lab_test',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(labval),
                                    success: function (data) {
                                        var data = JSON.parse(data);
                                        if (data.msg == "Success") {
                                            var data = data.data;
                                            if (jQuery.isEmptyObject((data))) {
                                            }
                                            else {
                                            }
                                        }
                                        else {
                                            console.log(data);
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});
//lab test end


//payment start
function collectpayment(patient_id, patient_first_name, patient_phone_number, photoSrc, visit_report_id, slottime, doctor_id, age, gender) {
    var gen = "";
    $('#cpi_activeInvoice_body').empty();
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);
    $('#Hdnpatient_id').val(patient_id);
    $('#PVisitReportID').val(visit_report_id);
    $('#Hdnappointment_date').val(slottime);
    $('#pop_doctor_id').val(doctor_id);

    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: '15'
    }

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

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#PVisitReportID').val(VisitReportID);
                        payment_val();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function payment_val() {
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();

    $('#InvoiceDate').val(output);
    var GetRight = {
        Dml_Indicator: 'RS',
        doctor_user_role_id: $('#hiddenRole_id').val(),
        doctor_user_module_id: '16'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/DoctorRight',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(GetRight),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var roleRight = '';
                    $.each(data1, function (i, emp) {
                        roleRight = emp.doctor_user_role_rights;
                    });

                    if (roleRight == 1) {
                        var InvoiceId = {
                            Patient_id: $('#Hdnpatient_id').val(),
                            doctor_id: $('#HiddenDoctorID').val(),
                            Dml_Indicator: 'IS'
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/caseStudy/invoice_payment',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(InvoiceId),
                            success: function (data) {

                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    console.log(data);
                                    var data = data.data;
                                    if (jQuery.isEmptyObject((data))) {
                                    }
                                    else {

                                        if (data.length > 0) {
                                            $('#InvoiceId').val(data[0].InvoiceId);
                                            $('#CpiInvoiceTotal').html(parseFloat(data[0].invoice_total) - parseFloat(data[0].invoice_payment));
                                            $('#CpiInvoicePayment').html(data[0].invoice_payment);
                                            $('#CpiInvoiceTotal_amt').html(data[0].invoice_total);
                                        }
                                    }
                                    ActiveInvoice();
                                    invoice_quickSelect();
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });
                    }
                    else {
                        toastr.warning('You have no right to access page contact administrator');
                        $('.close').click();
                    }
                }
            }
            else {
                console.log(data1);
            }
        },
    });
}


function invoice_quickSelect() {
    var familydetails = {
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: 'PS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/doctor_consultation_fees_details_amt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    var tr = '', quickSelect = ''
                    $('#invoice_quickSelect').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            quickSelect = quickSelect + '<li onclick=\'addinvoice(\"' + data[i].consultation_name + '\")\'>' + data[i].consultation_name + '</li>';
                        }
                        $('#invoice_quickSelect').html(quickSelect);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function addinvoice(InvoiceName) {
    var InvoiceNames = InvoiceName;

    var invoice = {}
    invoice.invoice_id = $('#InvoiceId').val(),
        invoice.Patient_id = $('#Hdnpatient_id').val(),
        invoice.doctor_id = $('#pop_doctor_id').val(),
        invoice.invoice_description = InvoiceNames,
        invoice.invoice_date = '',
        invoice.invoice_amount = $('#InvoiceAmount').val(),
        invoice.invoice_status = 1,
        invoice.balance_amount = $('#InvoiceAmount').val(),
        invoice.Dml_Indicator = 'QI',
        invoice.visit_report_id = $('#PVisitReportID').val(),

        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/invoice_payment',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(invoice),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {

                    }
                    collectpayment_afterinsert($('#Hdnpatient_id').val());
                }
                else {
                    console.log(data);
                }
            }
        });
}



$('#btnAddInvoice').click(function () {
    var InvoiceDate = $('#InvoiceDate').val();
    var InvoiceName = $('#InvoiceName').val();
    var InvoiceAmount = $('#InvoiceAmount').val();
    if ($.trim(InvoiceDate) == '') {
        $('#PInvoiceDate').show();
        $('#PInvoiceDate').fadeOut(8000);
        $('#PInvoiceDate').html('Select the invoice date');
        $('#InvoiceDate').focus();
        $('#InvoiceDate').val('');
        return false;
    }
    if ($.trim(InvoiceName) == '') {
        $('#PInvoiceName').show();
        $('#PInvoiceName').fadeOut(8000);
        $('#PInvoiceName').html('Enter the invoice name');
        $('#InvoiceName').focus();
        $('#InvoiceName').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the invoice amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }

    var InvoiceDates = InvoiceDate.split('/');
    InvoiceDate = InvoiceDates[2] + "-" + InvoiceDates[1] + "-" + InvoiceDates[0];
    var invoice = {
        invoice_id: $('#InvoiceId').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        doctor_id: $('#pop_doctor_id').val(),
        invoice_description: $('#InvoiceName').val(),
        invoice_date: InvoiceDate,
        invoice_amount: $('#InvoiceAmount').val(),
        invoice_status: 1,
        balance_amount: $('#InvoiceAmount').val(),
        Dml_Indicator: 'I',
        visit_report_id: $('#PVisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                }
                $('#InvoiceDate').val('');
                $('#InvoiceName').val('');
                $('#InvoiceAmount').val('');
                collectpayment_afterinsert($('#Hdnpatient_id').val());
            }
            else {
                console.log(data);
            }
        }
    });
});


function collectpayment_afterinsert(patient_id) {
    var InvoiceId = {
        Patient_id: patient_id,
        Dml_Indicator: 'IS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        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) {
                        $('#InvoiceId').val(data[0].InvoiceId);
                    }
                }
                ActiveInvoice();
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#cpi_activeInvoice_body').on('click', 'tr', function () {
    $('#cpi_activeInvoice_body > tr').removeClass('active');
    $('#cpi_activeInvoice_body > tr').css('fontSize', '12px');
    $(this).addClass('active');
    var id = $(this).attr('data-invoice');
    var val = id.split(',');

    var GetRight = {
        Dml_Indicator: 'RS',
        doctor_user_role_id: $('#hiddenRole_id').val(),
        doctor_user_module_id: '17'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/DoctorRight',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(GetRight),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var roleRight = '';
                    $.each(data1, function (i, emp) {
                        roleRight = emp.doctor_user_role_rights;
                    });
                    if (roleRight == 1) {
                        ActiveInvoiceDetails(val[0], val[1]);
                        $("#cpiActiveDetails").show();
                    }
                    else {
                        toastr.warning('You have no right to access page contact administrator');
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
});

$('#cpiDetailToggle').click(function () {
    $('#cpi_activeInvoice_body > tr').removeClass('active');
    $('#cpi_activeInvoice_body > tr').css('fontSize', '14px');
    $("#cpiActiveDetails").hide();
    $('#cpi_activeInvoice_sec').removeClass().addClass('col-md-12 padding0');
});

function ActiveInvoice() {
    $('#cpi_activeInvoice_table').addClass('us-db-loader-active-inv');
    var InvoiceId = {
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: 'AI',
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var tr = '';
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#cpi_activeInvoice_body').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {
                            if (data[i].invoice_status == 5) {
                                tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td></td><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td><span class="print btn addicon-btn   btn-sm"><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\",\"' + data[i].invoice_description + '\")\'; ></i></span>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td>SMS payment initiated</td><td>-</td></tr>';
                            }
                            else {
                                tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td><input style="display:none" type="checkbox" id="' + data[i].invoice_id + '" name="checkbox1" value="' + data[i].balance_amount + '" onclick=\'checkval(\"' + data[i].balance_amount + '\",\"' + data[i].invoice_id + '\")\';></td><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td><a class="payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);"  data-backdrop="static" title="CASH" data-keyboard="true" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-money" area-hidden="true"></i></a><a class="payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);" data-backdrop="static" title="CARD" data-keyboard="true" onclick=\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 2 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-credit-card" area-hidden="true"></i><a class="part-payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);" title="Partial Payment" data-backdrop="static" data-keyboard="true" onclick=add_payment1(\"' + data[i].lab_order_id + '\");><i class="fa fa-hourglass-half" area-hidden="true"></i></a><a class="print btn addicon-btn   btn-sm"><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\", \"' + data[i].invoice_description + '\")\'; ></i></a></td><td><a class="delete btn deleteicon-btn   btn-sm" href="javascript:void(0);" onclick=Delete_Active_invoice(\"' + data[i].invoice_id + '\",\"' + data[i].lab_order_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';
                            }
                        }
                        $('#cpi_activeInvoice_body').html(tr);
                        $('#CpiInvoiceTotal').html(parseFloat(data[0].invoice_total) - parseFloat(data[0].invoice_payment));
                        $('#CpiInvoicePayment').html(data[0].invoice_payment);
                        $('#CpiInvoiceTotal_amt').html(data[0].invoice_total);
                    }
                    else {
                    }
                }
                $('#cpi_activeInvoice_table').removeClass('us-db-loader-active-inv');
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#chk_amount').click(function () {
    if ($("[name='checkbox1']").is(":visible")) {
        $("[name='checkbox1']").hide();
        $('.head-payment-wap-popup').removeClass('open');

    } else {
        $("[name='checkbox1']").show();
        $('.head-payment-wap-popup').addClass('open');
        $('#payphonenumber').val($('.Patientpno').html());
    }
});

$('#lookup').click(function () {
    var smspayment = {
        email_id: $('#paymailid').val(),
        phone_number: $('#payphonenumber').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/lookup',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    })
});

$('#btnsmspayment').click(function () {
    if ($('#totpopup_amout >i').html() == '' || $('#totpopup_amout >i').html() == 0) {
        toastr.warning('invoice cannot be empty.Please select atleast one invoice');
        return false;
    }
    if ($('#payphonenumber').val() == '' || $('#payphonenumber').val() == null) {
        $('#Ppayphonenumber').show();
        $('#Ppayphonenumber').fadeOut(8000);
        $('#Ppayphonenumber').html('Enter phone number');
        $('#payphonenumber').focus();
        $('#payphonenumber').val('');
        return false;
    }

    if ($('#paymailid').val() == '' || $('#paymailid').val() == null) {
        $('#P_paymailid').show();
        $('#P_paymailid').fadeOut(8000);
        $('#P_paymailid').html('Enter mail id');
        $('#paymailid').focus();
        $('#paymailid').val('');
        return false;
    }


    var invoice_no_temp = "";
    var Amount_temp = "";
    $('#cpi_activeInvoice_body').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked')) {
            var $row = jQuery(this).closest('tr');
            var $columns = $row.find('td');
            var values = "";
            jQuery.each($columns, function (i, item) {
                invoice_no = $(this).parent("tr").find("td:eq(1)").text();
                Amount = $(this).parent("tr").find("td:eq(4)").text();
            });
            console.log(invoice_no);
            invoice_no_temp = invoice_no_temp + ',' + invoice_no;
            Amount_temp = Amount_temp + ',' + Amount;
        }
    });

    if ($.trim($('#payphonenumber').val()) == "") {
        $('#Ppayphonenumber').show();
        $('#Ppayphonenumber').fadeOut(8000);
        $('#Ppayphonenumber').html('Enter the phone number');
        $('#payphonenumber').focus();
        $('#payphonenumber').val('');
        return false;
    }

    var smspayment = {
        email_id: $('#paymailid').val(),
        phone_number: $('#payphonenumber').val(),
        created_by: $('#hiddenUserId').val(),
        valid_for: '7',
        valid_type: 'days',
        valid_date: '',
        currency: 'INR',
        amount: $('#totpopup_amout >i').html(),
        due_date: '',
        invoice_no: '',
        Dml_Indicator: 'I',
        patient_id: $('.PatientId').html(),
        customer_name: $('#PatientName').html(),
        invoice_no_temp: invoice_no_temp,
        Amount_temp: Amount_temp,
        doctor_id: $('#pop_doctor_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        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) {
                        var sms_invoice_no = data[0].sms_invoice_no;
                        var email_id = data[0].email_id;
                        var phone_number = data[0].phone_number;
                        var amount = data[0].amount;
                        var invoice_no = "";
                        var Amount = "";
                        var invoice_no_temp = "";
                        var Amount_temp = "";

                        var smspayment = {
                            email_id: $('#paymailid').val(),
                            phone_number: $('#payphonenumber').val(),
                            created_by: $('#hiddenUserId').val(),
                            valid_for: '7',
                            valid_type: 'days',
                            valid_date: '',
                            currency: 'INR',
                            amount: $('#totpopup_amout >i').html(),
                            due_date: '',
                            sms_invoice_no: sms_invoice_no,
                            Dml_Indicator: 'sms',
                            patient_id: $('.PatientId').html(),
                            customer_name: $('.PatientName').html()
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/caseStudy/sms_invoice_payment',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(smspayment),
                            success: function (data) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    var data = data.data;
                                    if (jQuery.isEmptyObject((data))) {

                                    }
                                    else {
                                        toastr.success('Payment link sent');
                                        ActiveInvoice();
                                        $('#totpopup_amout>i').html('');
                                        $('#payphonenumber').val('');
                                        $('#paymailid').val('');
                                    }
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});


function checkval(val, id) {
    var tempval = '';
    if ($('#' + id).prop("checked") == true) {
        tempval = $('#totpopup_amout >i').html();
        if (tempval == '') {
            tempval = 0;
        }
        tempval = parseFloat(tempval) + parseFloat(val);
        $('#totpopup_amout >i').html(tempval);
    }
    else if ($('#' + id).prop("checked") == false) {
        tempval = $('#totpopup_amout >i').html();
        if (tempval == '') {
            tempval = 0;
        }
        tempval = parseFloat(tempval) - parseFloat(val);
        $('#totpopup_amout >i').html(tempval);
    }
}


function smslinkfun(value, name) {
    if (value == "" || value == "-") {
        toastr.warning('Please check the patient phone number');
        return false;
    }
    var smspayment = {
        phonenumber: value,
        msg: "Dear " + name + ", . Doctor is held up with an emergency and will call you as soon as possible. Thank you for your patience. By Mocero",
        temp_id: "1607100000000093962"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_link',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {

            if (data == true) {
                toastr.success('SMS sent to patient');
            }
            else {
                toastr.success('SMS sent to patient');
            }
        }
    });
}




function add_payment1(labid) {
    $('#add_cpi_invoice').prop('disabled', false);
    $('#pack_id').val(labid);
    $('#Selpaymenttype').val('1');
    $('#modal_collectpayment_inner').modal('toggle');
}


function Delete_Active_invoice(invoice_id, lab_id) {
    var txt;
    var r = confirm("Are you sure you want to delete the Invoice: " + invoice_id + " ?");
    if (r == true) {
        $('#tblDoctorUser1').modal('toggle');
        $('#hndinvoiceId').val(invoice_id);
    } else {

    }
}


function fullpayment(balance_amount, payment_type, invoice_id, lab_order_id) {
    var GetRight = {
        Dml_Indicator: 'RS',
        doctor_user_role_id: $('#hiddenRole_id').val(),
        doctor_user_module_id: '17'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/DoctorRight',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(GetRight),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var roleRight = '';
                    $.each(data1, function (i, emp) {
                        roleRight = emp.doctor_user_role_rights;
                    });
                    if (roleRight == 1) {
                        var invoice_status = 3;
                        var patient_id, doc_id;
                        if (lab_order_id.length > 3) {
                            patient_id = $('#Hdnpatient_id').val();
                            doc_id = lab_order_id.split('-')[0];
                            if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == $('#HospitalId').val()) {
                                get_package_details(lab_order_id, invoice_id, patient_id);
                            }
                        }

                        var InvoiceId = {
                            doctor_id: $('#pop_doctor_id').val(),
                            patient_id: $('#Hdnpatient_id').val(),
                            payment_amount: balance_amount,
                            payment_type: payment_type,
                            invoice_id: invoice_id,
                            invoice_status: invoice_status,
                            balance_amount: 0,
                            Dml_Indicator: 'PI'
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/caseStudy/invoice_payment',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(InvoiceId),
                            success: function (data) {
                                if (jQuery.isEmptyObject((data))) {
                                }
                                else {
                                    var data = JSON.parse(data);
                                }
                                $('#paymentamount').val('');
                                doc_id = lab_order_id.split('-')[0];
                                if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == ($('#HospitalId').val())) {
                                    get_package_details(lab_order_id, invoice_id, $('#Hdnpatient_id').val());
                                }
                                ActiveInvoice();
                                HistroyInvoice();
                                toastr.success("Full Payment added successfully !!!");
                                $('.paymentclose').click();
                            }
                        });
                    }
                    else {
                        toastr.warning('You have no right to access page contact administrator');
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#mpinsubmit').click(function () {
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'D',
        invoice_id: $('#hndinvoiceId').val(),
        MPIN: $('#mpinnum').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    toastr.warning('MPIN is wrong');
                }

                if (data.length == 0) {
                    toastr.warning("MPIN is wrong");
                }
                else {
                    if (data.length > 0) {
                        if (data[0].StringMsg == 'Success') {
                            toastr.success('Payment Deleted Successfully');
                            ActiveInvoice();
                        }
                        else if (data[0].StringMsg == 'Cannot able to delete') {
                            toastr.warning('Payment Received - cannot delete Invoice');
                        }
                        else {
                            toastr.warning('MPIN is wrong !!!');
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});

function Invoice_lab_print(order_id, visit_report_id, invoice_id, invoice_description) {

    var dml_indicatr = '', invoice_details = invoice_description.split('-');
    var dml_indicatr = '', invoice_details = invoice_description.split('-');
    if (invoice_details[0] == "package") {
        dml_indicatr = "PP";  //package print
        window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
    }
    else {
        //dml_indicatr = "NP"; //normal invoice print
        var invoice = invoice_description.split(' ');
        if (invoice[0] == "LabOrder") {
            if (order_id != '' && order_id != "null") {
                window.open('/PatientDashboard/labinvoice?orderid=' + invoice_id + '&doctorId=' + $('#HiddenDoctorID').val());
            }
        }
        else {
            if (visit_report_id == null || visit_report_id == "" || visit_report_id == "null") {
                dml_indicatr = "PP";
            }
            window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
        }
    }
}


function ActiveInvoiceDetails(id, amount) {
    $('#curinvoiceid').val(id);
    $('#totamt').html(amount);
    $('#paidamt').html('0');
    $('#curamount').val(amount);
    var invoice = {
        invoice_id: $('#curinvoiceid').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'PD',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            $('#tblinvoiceamtdetails_body').empty();
            var tr = '';
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#totamt').html(amount);
                    $('#paidamt').html('0');
                    $('#balanceamt').html('0');
                }
                else {

                    var balanceamt = 0;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var paymenttype = '';
                            if (data[i].payment_type == 1) {
                                paymenttype = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                paymenttype = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                paymenttype = 'Payment Gateway';
                            }
                            else if (data[i].payment_type == 4) {
                                paymenttype = 'Online';
                            }
                            else {
                                paymenttype = '-';
                            }
                            tr = tr + '<tr><td>' + data[i].payment_id + '</td><td>' + paymenttype + '</td><td>' + data[i].payment_amount + '</td></tr>';
                            balanceamt = balanceamt + data[i].payment_amount;

                            //$('#payment_details').html('<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + $('#curinvoiceid').val() + '\")\';>Fully Paid by Card</a>/<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + $('#curinvoiceid').val() + '\")\';>Fully Paid by Card</a>');
                        }
                    }
                    $('#paidamt').html(balanceamt);
                    $('#tblinvoiceamtdetails_body').html(tr);
                    balanceamt = (amount) - (balanceamt);
                    $('#balanceamt').html(balanceamt);

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

$('#add_cpi_invoice').click(function () {
    if ($('#Selpaymenttype').val() == 4) {
        if ($.trim($('#transaction_id').val()) == '') {
            $('#Ptransaction_id').show();
            $('#Ptransaction_id').fadeOut(4000);
            $('#Ptransaction_id').html('enter the transaction_id');
            $('#transaction_id').focus();
            $('#transaction_id').val('');
            return false;
        }
    }
    if ($.trim($('#paymentamount').val()) == '') {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('enter the invoice amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        return false;
    }
    $('#add_cpi_invoice').prop('disabled', true);
    var previousval = 0;
    $('#tblinvoiceamtdetails > tbody  > tr').each(function () {
        $(this).find("td:gt(1)").each(function () {
            var temp = $(this).html();
            previousval = parseFloat(previousval) + parseFloat(temp);
        });
    });
    previousval = parseFloat(previousval) + parseFloat($('#paymentamount').val());
    var invoice_status = '', balance_amount = '', patient_id = '', invoice_id = '', doc_id = '', package_id = '';
    if (previousval > parseFloat($('#curamount').val())) {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('Check amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        $('#add_cpi_invoice').prop('disabled', false);
        return false;
    }
    else if (previousval < parseFloat($('#curamount').val())) {
        invoice_status = 2;
        balance_amount = parseFloat($('#curamount').val()) - parseFloat(previousval);
    }
    else {
        patient_id = $('#Hdnpatient_id').val();
        invoice_id = $('#curinvoiceid').val();
        package_id = $('#pack_id').val();
        if (package_id != null || package_id != "") {
            if (package_id.length > 3) {
                doc_id = $('#pack_id').val().split('-')[0];
                if (doc_id == ($('#HospitalId').val()) || doc_id == ($('#HiddenDoctorID').val())) {
                    get_package_details(package_id, invoice_id, patient_id);
                }
            }
        }
        invoice_status = 3;
        balance_amount = 0;
    }
    var InvoiceId = {
        doctor_id: $('#pop_doctor_id').val(),
        patient_id: $('#Hdnpatient_id').val(),
        payment_amount: $('#paymentamount').val(),
        payment_type: $('#Selpaymenttype').val(),
        invoice_id: $('#curinvoiceid').val(),
        invoice_status: invoice_status,
        balance_amount: balance_amount,
        transaction_id: $("#transaction_id").val(),
        Dml_Indicator: 'PI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                }
                $('#paymentamount').val('');
                $('#transaction_id').val('');
                $('#transaction').hide();
                ActiveInvoice();
                HistroyInvoice();
                ActiveInvoiceDetails($('#curinvoiceid').val(), $('#curamount').val());
                $('#add_cpi_invoice').prop('disabled', false);
                $('#Selpaymenttype').val('1');
            }
            else {
                console.log(data)
            }
        }
    });
});

$('#cpHistoryInvoiceId').click(function () {
    HistroyInvoice();
});

function HistroyInvoice() {
    $('.cpi_historyInvoice_table').addClass('us-db-loader-history-inv');
    var InvoiceId = {
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: 'HS',
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var tr = '';
            $('#cpi_historyInvoice_body').empty();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    if (data.length > 0) {
                        var tr1 = '', tr2 = '', tr3 = '', j = 1;
                        var invoice_id = '';
                        var a = data.length;
                        for (var i = 0; i < data.length; i++) {
                            var payment_type = '';
                            if (data[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else if (data[i].payment_type == 4) {
                                payment_type = 'Online';
                            }
                            else {
                                payment_type = '';
                            }
                            if (a == j) {
                                if (data[i].invoice_id == data[i].invoice_id) {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                    tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\", \"' + data[i].invoice_description + '\")\'; ></i>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td class="ptr"><a tabindex="0" class="" data-html="true" data-toggle="popover" data-trigger="click" data-placement="bottom" title="<span class=\'cpPopClose pull-right\'><i class=\'fa fa-times\' aria-hidden=\'true\'></i></span><table class=\'table\'><thead><tr><th>Pay date</th><th>Amt</th><th>Pay Type</th></tr></thead><tbody>' + tr2 + '</tbody></table>">History</a></td></tr>';
                                    tr2 = '';
                                }
                            }
                            else {
                                if (data[i].invoice_id != data[j].invoice_id) {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                    tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\", \"' + data[i].invoice_description + '\") \';></i>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td class="ptr"><a tabindex="0" class="" data-html="true" data-toggle="popover" data-trigger="click" data-placement="bottom" title="<span class=\'cpPopClose pull-right\'><i class=\'fa fa-times\' aria-hidden=\'true\'></i></span><table class=\'table\'><thead><tr><th>Pay date</th><th>Amt</th><th>Pay Type</th></tr></thead><tbody>' + tr2 + '</tbody></table>">History</a></td></tr>';
                                    tr2 = '';
                                }
                                else {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                }
                            }

                            j++;
                        }
                        tr = tr
                        $('#cpi_historyInvoice_body').html(tr);
                        $("[data-toggle=popover]").popover();
                    }
                }
                $('.cpi_historyInvoice_table').removeClass('us-db-loader-history-inv');
            }
            else {
                console.log(data);
            }
        }
    });
}


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

    if ($("#cpHistoryInvoice-section").hasClass("in")) {
        $('.paymentcollection').animate({ scrollTop: 600 }, 'slow');
    }
    else {
        $('.paymentcollection').animate({ scrollTop: 600 }, 'slow');
    }

});

$('#InvoiceName').change(function () {
    var familydetails = {
        consultation_name: $('#InvoiceName').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'MS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/doctor_consultation_fees_details_amt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {

            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    var tr = ''
                    if (data.length > 0) {
                        $('#InvoiceAmount').val(data[0].consultation_fees);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});


$('#us-chat-send-btn').click(function () {
    if ($.trim($('#supportmsg').val()).length > 0) {
        var val = "1";
        doctor_support(val);
    }
    else {
        $('#errormsg').fadeOut(8000);
        $('#errormsg').html('enter the message');
    }
});

$('#us-chat-st-btn').click(function () {
    $('#us-chat-st-btn').hide();
    var val = "2";
    doctor_support(val);
});

$('#helpSeeQui').click(function () {
    doctor_support_list();
});

function doctor_support(val) {
    if (val == "1") {
        var doctor_support = {
            doctor_id: $('#HiddenDoctorID').val(),
            message: $('#supportmsg').val(),
            sms_group: "5",
            indicator_id: "I"
        }
    }
    else {
        var doctor_support = {
            doctor_id: $('#HiddenDoctorID').val(),
            message: "Request A Call back",
            sms_group: "5",
            indicator_id: "I"
        }
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_support',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctor_support),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (val == "1") {
                        $('#supportmsg').val('');
                        $('.us-chat-callbackform').show();
                        toastr.success("Sent Successfully");
                        $("#ushelpMenu").removeClass('opencustomdropdown');
                    }
                    else {
                        $('.us-chat-callbackbtn').show();
                        toastr.warning("We will get back to you soon");
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function doctor_support_list() {
    var doctor_support = {
        doctor_id: $('#HiddenDoctorID').val(),
        sms_group: "5",
        indicator_id: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_support',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctor_support),
        success: function (data) {
            $('#support_list').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var d = new Date();
                    var month = d.getMonth() + 1;
                    var day = d.getDate();
                    var output = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
                    if (jQuery.isEmptyObject((data))) {
                        $('#support_list').toggleClass('empty-enq-list');
                    }
                    else if (data1['support_list'].length == 0) {
                        $('#support_list').toggleClass('empty-enq-list');
                    }
                    else {
                        $.each(data1['support_list'], function (i, emp) {
                            if (output == emp.sent_on.split('T')[0]) {
                                var html = '<a href="#" class="urs-ques-link" data-toggle="popoverques" data-placement="left" title= "' + emp.date + '" data-content="' + emp.message + '"><li><span class="us-ques-date"> ' + emp.date + '</span><span class="us-ques-abt">' + emp.message + '</span><span class="us-ques-type"><strong>New</strong></span></li></a>';
                                $('#support_list').append(html);

                            }
                            else {
                                var html = '<a href="#" class="urs-ques-link" data-toggle="popoverques" data-placement="left" title= "' + emp.date + '" data-content="' + emp.message + '"><li><span class="us-ques-date"> ' + emp.date + '</span><span class="us-ques-abt">' + emp.message + '</span><span i class="fa fa-clock-o"></i></span></li></a>';
                                $('#support_list').append(html);
                            }
                        });
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

//chatbot stats
$('#btn-input').keypress(function (event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        var html = '<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right">You</span></p><div class="chat-body clearfix"><p>' + $('#btn-input').val() + '</p></div></li>';
        $('#textchatursugar').append(html);
        $('.us-typing').show();
        var val = "1";
        doctor_bot(val);
    }
});

$("#btn-chat").click(function () {
    if ($.trim($('#btn-input').val()).length == "") {
        toastr.warning("Enter Message");
        return false;
    }
    if ($.trim($('#btn-input').val()).length > 0) {
        var html = '<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right">You</span></p><div class="chat-body clearfix"><p>' + $('#btn-input').val() + '</p></div></li>';
        $('#textchatursugar').append(html);
        $('.us-typing').show();
        var val = "1";
        doctor_bot(val);
    }
});

$('.chat-option').click(function (e) {
    var val = e.target.innerHTML;
    var html = '<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right">You</span></p><div class="chat-body clearfix"><p>' + val + '</p></div></li>';
    $('#textchatursugar').append(html);
    $('.us-typing').show();
    doctor_bot(val);
});

$('#chatTriggerbtn').click(function () {
    doctor_bot_history();
});

function doctor_bot(val) {
    if (val == "1") {
        var ChatData = {
            doctor_name: $('#txtDusername').html(),
            text: $('#btn-input').val(),
            chat_id: "default"
        }
    }
    else {
        var ChatData = {
            doctor_name: $('#txtDusername').html(),
            text: val,
            chat_id: "default"
        }
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_help',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ChatData),
        success: function (data) {
            var data1 = JSON.parse(data);
            var data2 = data1.messages;
            $('.us-typing').hide();
            $('#textchatursugar').empty();
            $.each(data2, function (i, emp) {
                if (emp.sender_id == "URSUGAR01") {
                    var ch_type = "Curola";
                    if ($('#HProductCode').val() == "1") ch_type = "Ursugar";
                    if (emp.intent == "add_patient") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Add_Patient.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "calendar_configuration") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Calendar_Configuration.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "casesheet_creation") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Case_Sheet.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "diet_template") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Diet_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "lab_module") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Lab_Module.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "lab_template") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Lab_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "medicine_diet") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Medicine_and_Diet.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "prescription_template") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Prescription_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "quick_entry") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Quick_Entry.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "summary_report") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Summary_Report.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "vip_list") {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/VIP_List.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else {
                        var html = '<span class="muted-color-left">' + ch_type + '</span><li class="left clearfix"><div class="chat-body clearfix"><p>' + emp.message + '</p></div></li>';
                        $('#textchatursugar').append(html);
                    }
                }
                else {
                    var html = '<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right">You</span></p><div class="chat-body clearfix"><p>' + emp.message + '</p></div></li>';
                    $('#textchatursugar').append(html);
                }
            });
            $('#optionvalue').show();
            $("#btn-input").val('');
            uschathelpscroller();
        }
    });
}

function doctor_bot_history() {
    var ChatData = {
        doctor_name: $('#txtDusername').html()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_help_history',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ChatData),
        success: function (data) {
            var data1 = JSON.parse(data);
            var data2 = data1.messages;
            $('#textchatursugar').empty();
            $.each(data2, function (i, emp) {
                if (emp.sender_id == "URSUGAR01") {
                    if (emp.intent == "add_patient") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Add_Patient.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "calendar_configuration") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Calendar_Configuration.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "casesheet_creation") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Case_Sheet.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "diet_template") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Diet_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "lab_module") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Lab_Module.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "lab_template") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Lab_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "medicine_diet") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Medicine_and_Diet.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "prescription_template") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Prescription_Template.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "quick_entry") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Quick_Entry.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "summary_report") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/Summary_Report.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else if (emp.intent == "vip_list") {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><video class="us-video-player" controls controlsList="nodownload"><source src="https://photos.ursugar.com/videos/VIP_List.mp4" type="video/mp4"></video></div></li>';
                        $('#textchatursugar').append(html);
                    }
                    else {
                        var html = '<span class="muted-color-left">Ursugar</span><li class="left clearfix"><div class="chat-body clearfix"><p>' + emp.message + '</p></div></li>';
                        $('#textchatursugar').append(html);
                    }
                }
                else {
                    var html = '<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right">You</span></p><div class="chat-body clearfix"><p>' + emp.message + '</p></div></li>';
                    $('#textchatursugar').append(html);
                }
            });
            $('#optionvalue').show();
            $("#btn-input").val('');
            uschathelpscroller();
        }
    });
}
//chatbotends



//diet start
function DeitPlan(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time, doctor_id, age, gender,visitid) {
    debugger;
    $('#tblDietChart > tbody').empty();
    $('#DietTableRowCount').val(0)
    clear_diet();
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);
    var gen = "";
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);

    Deittemlatelist();

    var slot_start_time = $('#Hdnappointment_date').val();
    slot_start_time = slot_start_time.split('T');
    var visit_id;
    //if ($('#VisitReportID').val() != '') visit_id = $('#VisitReportID').val();
    //else visit_id = $('#EditVisitReportID').val();
    var Template = {
        visit_report_id: visitid,
        Dml_Indicator: 'CDS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/DeitTemplate',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {
                    $('#dietplanDashboard').removeClass('dietplanDashboard-loader');
                }
                else {
                    if (data.length > 0) {
                        if (data.length == '' || data.length == 0) {
                        }
                        else {
                            debugger;
                            $('#tblDietChart > tbody').empty();
                            $('#DietTableRowCount').val(0);
                            $('#txtdietname').val('');
                            for (var i = 0; i < data.length; i++) {
                                $('#btnDiet').html('Update & Next');
                                var sess_key;
                                var rowcount = $.trim($('#DietTableRowCount').val());
                                var tot_row = (Number(rowcount) + 1);
                                var ikey_Deit = '';
                                var sess_data_Deit = data[i].time + "," + data[i].type_of_food + "," + data[i].no_of_servings + "," + data[i].instructions + "," + data[i].display_order;
                                if (rowcount >= 1) {
                                    var getEid = $('#tblDietChart  tr').last();
                                    var actId = getEid.prop('id');
                                    var afterSplit = actId.split('row');
                                    afterInc = parseInt(afterSplit[1]) + 1;
                                    console.log(afterInc);
                                    ikey_Deit = 'row' + afterInc;
                                }
                                else {
                                    ikey_Deit = 'row' + tot_row;
                                }
                                sessionStorage.setItem(ikey_Deit, sess_data_Deit);
                                var value = "<tr id='t_" + ikey_Deit + "'><td>" + data[i].time + "</td><td>" + data[i].type_of_food + "</td><td>" + data[i].no_of_servings + "</td><td>" + data[i].instructions + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Diet' onclick='Dietedit(\"" + ikey_Deit + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Diet' onclick='Dietdelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                                $('#txtKcal').html(data[i].kcal);
                                $('#tblDietChart > tbody:last').append(value);
                                $('#DietTableRowCount').val(tot_row);
                                //$('#btndietsave').html('Update');
                                $('#txtdietname').html(data[i].diet_name);
                                $('#deitupdateid').val(data[i].diet_template_id);
                                $('#benifits').val(data[i].diet_goal_benifits);
                                $('#txtInstruction').val(data[i].diet_goal_notes);
                                var diet_goal_duration = data[0].diet_goal_duration;
                                $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').removeClass('not-active');
                                $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').addClass('active');
                                $('#Etime').val("90");
                            }
                            if (data.length > 0) {
                                $('#deit_print').html('<i class="fa fa-print" onclick=deit_print("' + data[0].VVisit_report_id + '")></i>');
                            }
                            $('#txtTime').val('');
                            $('#txtfood').val('');
                            $('#txtQuantity').val('');
                            $('#txtInstructions').val('');
                        }
                    }
                    $('#dietplanDashboard').removeClass('dietplanDashboard-loader');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function deit_print(VVisit_report_id) {
    window.open('/PatientDashboard/diet?visitreportid=' + VVisit_report_id, "_blank");
}

function Deittemlatelist() {
    var Template = {
        created_by: $('#pop_doctor_id').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/DeitTemplate',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var tr = '';

            var data = JSON.parse(data);
            if (data.msg = "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                    tr = tr + '<a href="/Template/Index?Type=2"><div class="pull-left">Click To Add Diet Template</div><div class="clearfix"></div></a>';
                }
                else {

                    if (data.length <= 0) {
                        tr = tr + '<a href="/Template/Index?Type=2"><div class="pull-left">Click To Add Diet Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" onclick=onDeittemplatelist(' + data[i].diet_template_id + ');><div class="pull-left">' + data[i].diet_name + '</div><div class="clearfix"></div></a>';
                        }
                    }

                }
                $('#deittemplatelist').html(tr);
            }
            else {
                console.log(data);
            }
        }
    });
}


function onDeittemplatelist(val) {
    var Etime = $('#Etime').val();
    if (Etime == '' || Etime == null) {
        toastr.warning('Select the Plan Duration');
        $('#PEtimes').show();
        $('#PEtimes').fadeOut(8000);
        $('#PEtimes').html('Select the Plan Duration');
        $('#Etimes').focus();
        return false;
    }
    else {
        var Template = {
            diet_template_id: val,
            created_by: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'SS'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                var tr = '';
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                        // $('#tblDietChart > tbody').empty();
                        //$('#DietTableRowCount').val('0');
                        $('#txtdietname').val('');
                        for (var i = 0; i < data.length; i++) {
                            var sess_key;
                            var rowcount = $.trim($('#DietTableRowCount').val());
                            var tot_row = (Number(rowcount) + 1);
                            var ikey_Deit = '';
                            var sess_data_Deit = data[i].time + "," + data[i].type_of_food + "," + data[i].no_of_servings + "," + data[i].instructions;
                            if (rowcount >= 1) {
                                var getEid = $('#tblDietChart_body  tr').last();
                                var actId = getEid[0].id;
                                var afterSplit = actId.split('row');
                                afterInc = parseInt(afterSplit[1]) + 1;
                                console.log(afterInc);
                                ikey_Deit = 'row' + afterInc;
                            }
                            else {

                                ikey_Deit = 'row' + tot_row;
                            }
                            sessionStorage.setItem(ikey_Deit, sess_data_Deit);
                            var value = "<tr id='t_" + ikey_Deit + "'><td>" + data[i].time + "</td><td>" + data[i].type_of_food + "</td><td>" + data[i].no_of_servings + "</td><td>" + data[i].instructions + "</td><td><button class='edit btn btn-primary btn-xs btn-add mr-15' onclick='Dietedit(\"" + ikey_Deit + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-xs btn-add' onclick='Dietdelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                            $('#txtKcal').html(data[i].kcal);
                            $('#tblDietChart > tbody:last').append(value);
                            $('#DietTableRowCount').val(tot_row);
                            $('#txtdietname').html(data[i].diet_name);
                            $('#deitupdateid').val(data[i].diet_template_id);
                        }
                        $('#txtTime').val('');
                        $('#txtfood').val('');
                        $('#txtQuantity').val('');
                        $('#txtInstructions').val('');

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

$('#Add_Diet_record').click(function () {
    var Etime = $('#Etime').val();
    if (Etime == '' || Etime == null) {
        toastr.warning('Select the Plan Duration');
        $('#PEtimes').show();
        $('#PEtimes').fadeOut(8000);
        $('#PEtimes').html('Select the Plan Duration');
        $('#Etimes').focus();
        return false;
    }
    else {
        var Time = $('#txtTime').val();
        var food = $('#txtfood').val();
        var Quantity = $('#txtQuantity').val();
        var Instructions = $('#txtInstructions').val();

        if ($.trim((Time)) == "") {
            $('#PtxtTime').show();
            $('#PtxtTime').fadeOut(8000);
            $('#PtxtTime').html('Select Time ');
            $('txtTime').focus();
            return false;
        }
        if ($.trim((food)) == "") {
            $('#Ptxtfood').show();
            $('#Ptxtfood').fadeOut(8000);
            $('#Ptxtfood').html('Enter the food');
            $('#Ptxtfood').focus();
            return false;
        }
        if ($.trim((Quantity)) == "") {
            $('#PtxtQuantity').show();
            $('#PtxtQuantity').fadeOut(8000);
            $('#PtxtQuantity').html('Enter the Quantity');
            $('#txtQuantity').focus();
            return false;
        }
        if ($.trim((Instructions)) == "") {
            $('#PtxtInstructions').show();
            $('#PtxtInstructions').fadeOut(8000);
            $('#PtxtInstructions').html('Enter the Instructions');
            $('#PtxtInstructions').focus();
            return false;
        }
        debugger;
        var sess_key;
        var rowcount = $.trim($('#DietTableRowCount').val());
        var tot_row = (Number(rowcount) + 1);
        var ikey_Deit = '';
        var seriesNumber = tot_row;

        var sess_data_Deit = Time + "," + food + "," + Quantity + "," + Instructions + "," + seriesNumber;

        if (rowcount >= 1) {
            var getEid = $('#tblDietChart_body  tr').last();
            var actId = getEid[0].id;
            var afterSplit = actId.split('row');
            afterInc = parseInt(afterSplit[1]) + 1;
            console.log(afterInc);
            ikey_Deit = 'row' + afterInc;
        }
        else {

            ikey_Deit = 'row' + tot_row;
        }

        sessionStorage.setItem(ikey_Deit, sess_data_Deit);

        var value = "<tr id='t_" + ikey_Deit + "'><td>" + Time + "</td><td>" + food + "</td><td>" + Quantity + "</td><td>" + Instructions + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Diet' onclick='Dietedit(\"" + ikey_Deit + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Diet' onclick='Dietdelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

        $('#tblDietChart > tbody:last').append(value);
        $('#DietTableRowCount').val(tot_row);

        $('#txtTime').val('');
        $('#txtfood').val('');
        $('#txtQuantity').val('');
        $('#txtInstructions').val('');
    }
});


function Dietedit(val) {
    $('#Add_Diet_record').hide();
    $('#Update_Diet_record').show();
    $('#hdn_diet_id').val(val);

    var gkey = val;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#txtTime').val(row_data_split[0]);
    $('#txtfood').val(row_data_split[1]);
    $('#txtQuantity').val(row_data_split[2]);
    $('#txtInstructions').val(row_data_split[3]);

}
function Dietdelete(val) {
    sessionStorage.removeItem(val);
    $('#t_' + val).remove();
    var a = $.trim($('#DietTableRowCount').val());
    var a = (a) - (1);
    $('#DietTableRowCount').val(a);
}

$('#Update_Diet_record').click(function () {
    var table_id = $('#hdn_diet_id').val();

    var Time = $('#txtTime').val();
    var food = $('#txtfood').val();
    var Quantity = $('#txtQuantity').val();
    var Instructions = $('#txtInstructions').val();

    if ($.trim((Time)) == "") {
        $('#PtxtTime').show();
        $('#PtxtTime').fadeOut(8000);
        $('#PtxtTime').html('Select Time ');
        $('txtTime').focus();
        return false;
    }
    if ($.trim((food)) == "") {
        $('#Ptxtfood').show();
        $('#Ptxtfood').fadeOut(8000);
        $('#Ptxtfood').html('Enter the food');
        $('#Ptxtfood').focus();
        return false;
    }
    if ($.trim((Quantity)) == "") {
        $('#PtxtQuantity').show();
        $('#PtxtQuantity').fadeOut(8000);
        $('#PtxtQuantity').html('Enter the Quantity');
        $('#txtQuantity').focus();
        return false;
    }
    if ($.trim((Instructions)) == "") {
        $('#PtxtInstructions').show();
        $('#PtxtInstructions').fadeOut(8000);
        $('#PtxtInstructions').html('Enter the Instructions');
        $('#PtxtInstructions').focus();
        return false;
    }

    $('#Add_Diet_record').show();
    $('#Update_Diet_record').hide();

    var sess_data_Deit = Time + "," + food + "," + Quantity + "," + Instructions;
    var ikey_Deit = table_id;
    sessionStorage.setItem(ikey_Deit, sess_data_Deit);

    $('#tblDietChart > tbody:last').empty();

    var tot_row = $.trim($('#DietTableRowCount').val());
    var i, j;


    for (i = 1; i <= tot_row; i++) {
        var gkey = 'row' + i;
        console.log(sessionStorage.getItem(gkey));
        var row_data = sessionStorage.getItem(gkey);

        if (row_data == null) {
            console.log(gkey + '--------->' + row_data);
        }
        if (row_data != null) {
            row_data = row_data.split(',');
            var value = "<tr id='t_" + gkey + "'><td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + row_data[2] + "</td><td>" + row_data[3] + "</td><td><button class='edit btn btn-primary btn-xs btn-add mr-15' onclick='Dietedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-xs btn-add' onclick='Dietdelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            $('#tblDietChart > tbody:last').append(value);
        }
    }

    $('#DietTableRowCount').val(tot_row);
    $('#txtTime').val('');
    $('#txtfood').val('');
    $('#txtQuantity').val('');
    $('#txtInstructions').val('');
});



function insertdiet() {
    var rowCount = $('#tblDietChart >tbody >tr').length;
    var diet_goal_duration = $('#Etime').val();
    var deittemplateId = '';
    var endDate, StartDate;
    var today = new Date();
    var endDate = new Date();
    var month = endDate.getMonth();
    if (diet_goal_duration == 90) {
        endDate.setDate(today.getDate() + 90);
    }
    else {
        endDate.setDate(today.getDate() + 180);
    }
    var day = endDate.getDate();
    var month = endDate.getMonth();
    var year = endDate.getFullYear();
    endDate = year + '-' + (month + 1) + '-' + day;
    StartDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();

    if ($('#DietTableRowCount').val() > 0) {
        var labval = {
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            diet_goal_priority: '',
            diet_goal_start_date: StartDate,
            diet_goal_end_date: endDate,
            diet_goal_duration: diet_goal_duration,
            diet_goal_status: '1',
            diet_goal_set_by: $('#doctorId').val(),
            diet_goal_benifits: $('#benifits').val(),
            diet_goal_notes: $('#txtInstruction').val(),
            kcal: $('#txtKcal').html(),
            diet_template_id: $('#deitupdateid').val(),
            Dml_Indicator: 'CI',
            created_by: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var diet_goal_id = '';
                    if (data.length > 2) {
                        var data1 = JSON.parse(data);
                        for (var i = 0; i < data1.length; i++) {
                            diet_goal_id = data1[0].diet_goal_id;
                        }

                        var tot_rowM = $.trim($('#DietTableRowCount').val());
                        if (tot_rowM > 0) {
                            var L = 0;
                            for (j = 1; j <= tot_rowM; j++) {
                                var a = $('#tblDietChart_body').children('tr').eq(L);
                                var b = a.prop('id');
                                L++;

                                var C = b.split('_');

                                var gkey = C[1];

                                var row_data = sessionStorage.getItem(gkey);
                                //row_data.sort((a, b) => a[4] - b[4]);

                                var K = 0;
                                if (row_data == "") {
                                    console.log(gkey + '--------->' + row_data);
                                }
                                if (row_data != "" && row_data != null) {
                                    row_data = row_data.split(',');
                                    var sms = {
                                        Dml_Indicator: 'CDI',
                                        diet_goal_id: diet_goal_id,
                                        time: row_data[0],
                                        created_by: $('#doctorId').val(),
                                        instructions: row_data[3],
                                        type_of_food: row_data[1],
                                        no_of_servings: row_data[2],
                                    }
                                    $.ajax({
                                        async: true,
                                        type: 'POST',
                                        url: '/CaseStudy/DeitTemplate',
                                        contentType: 'application/json; charset=UTF-8',
                                        data: JSON.stringify(sms),
                                        success: function (data) {
                                        }
                                    });
                                }
                            }
                            $('#txtTime').val('');
                            $('#txtfood').val('');
                            $('#txtQuantity').val('');
                            $('#txtInstructions').val('');
                            $('#txtdietname').val('');
                            $('#btnDiet').html('Update & Next');
                        }
                    }
                }
            }
        });
    }
}


function loadnewDiet() {
    var Template = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CDS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/DeitTemplate',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var tr = '';
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data = JSON.parse(data);
                $('#tblDietChart > tbody').empty();
                $('#txtdietname').val('');
                for (var i = 0; i < data.length; i++) {
                    $('#btnDiet').html('Update & Next');
                    var sess_key;
                    var rowcount = $.trim($('#DietTableRowCount').val());
                    var tot_row = (Number(rowcount) + 1);
                    var ikey_Deit = '';
                    var sess_data_Deit = data[i].time + "," + data[i].type_of_food + "," + data[i].no_of_servings + "," + data[i].instructions;

                    if (rowcount >= 1) {
                        var getEid = $('#tblDietChart  tr').last();
                        var actId = getEid.prop('id');
                        var afterSplit = actId.split('row');
                        afterInc = parseInt(afterSplit[1]) + 1;
                        console.log(afterInc);
                        ikey_Deit = 'row' + afterInc;
                    }
                    else {

                        ikey_Deit = 'row' + tot_row;
                    }

                    sessionStorage.setItem(ikey_Deit, sess_data_Deit);

                    var value = "<tr id='t_" + ikey_Deit + "'><td>" + data[i].time + "</td><td>" + data[i].type_of_food + "</td><td>" + data[i].no_of_servings + "</td><td>" + data[i].instructions + "</td><td><button class='edit btn btn-primary btn-xs btn-add mr-15' onclick='Dietedit(\"" + ikey_Deit + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-xs btn-add' onclick='Dietdelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                    $('#txtKcal').html(data[i].kcal);

                    $('#tblDietChart > tbody:last').append(value);
                    $('#DietTableRowCount').val(tot_row);
                    $('#txtdietname').html(data[i].diet_name);
                    $('#deitupdateid').val(data[i].diet_template_id);
                    $('#benifits').val(data[i].diet_goal_benifits);
                    $('#txtInstruction').val(data[i].diet_goal_notes);

                    var diet_goal_duration = data[0].diet_goal_duration;

                    $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').removeClass('not-active');
                    $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').addClass('active');
                    $('#Etime').val(diet_goal_duration);
                }
                $('#txtTime').val('');
                $('#txtfood').val('');
                $('#txtQuantity').val('');
                $('#txtInstructions').val('');
            }
        }
    });

}


function deletediet() {
    var Template = {
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'D'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/DeitTemplate',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            insertdiet();
        }
    });
}


$('#AddDiettable').click(function () {
    debugger;
    dietVisitreportId('1');
});

function dietVisitreportId(val) {
    debugger;
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: '15'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        insertdiet(val);
                    }
                    else {
                        $('.close').click();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function insertdiet(val) {
   // $('#shade_slot').show();
    var rowCount = $('#tblDietChart >tbody >tr').length;

    var diet_goal_duration = $('#Etime').val();
    var deittemplateId = '';

    var endDate, StartDate;
    var today = new Date();

    var endDate = new Date();
    var month = endDate.getMonth();
    if (diet_goal_duration == 90) {
        endDate.setDate(today.getDate() + 90);
    }
    else {
        endDate.setDate(today.getDate() + 180);
    }

    var day = endDate.getDate();
    var month = endDate.getMonth();
    var year = endDate.getFullYear();
    endDate = year + '-' + (month + 1) + '-' + day;
    StartDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();

    if ($('#DietTableRowCount').val() > 0) {
        var labval = {
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            diet_goal_priority: '',
            diet_goal_start_date: StartDate,
            diet_goal_end_date: endDate,
            diet_goal_duration: diet_goal_duration,
            diet_goal_status: '1',
            diet_goal_set_by: $('#doctorId').val(),
            diet_goal_benifits: $('#benifits').val(),
            diet_goal_notes: $('#txtInstruction').val(),
            kcal: $('#txtKcal').html(),
            diet_template_id: $('#deitupdateid').val(),
            Dml_Indicator: 'CI',
            created_by: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                var data1 = JSON.parse(data);
                console.log(data1);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                       //  $('#shade_slot').hide();
                    }
                    else {
                        var diet_goal_id = '';
                        //if (data.length > 2) {

                        for (var i = 0; i < data1.length; i++) {
                            diet_goal_id = data1[0].diet_goal_id;
                        }
                        var tot_rowM = $.trim($('#DietTableRowCount').val());
                        if (tot_rowM > 0) {
                            var L = 0; Lcount = 0;
                            var dietArray = new Array();

                            for (j = 1; j <= tot_rowM; j++) {
                                var a = $('#tblDietChart_body').children('tr').eq(L);
                                var b = a.prop('id');
                                L++;
                                var C = b.split('_');
                                var gkey = C[1];

                                var row_data = sessionStorage.getItem(gkey);
                               // row_data.sort((a, b) => a[4] - b[4]);

                                var K = 0;
                                if (row_data == "") {
                                    console.log(gkey + '--------->' + row_data);
                                }
                                if (row_data != "" && row_data != null) {
                                    console.log(gkey + '-------' + row_data);
                                    row_data = row_data.split(',');

                                    var dietInfo = {};

                                    dietInfo.diet_goal_id = diet_goal_id;
                                    dietInfo.time = row_data[0],
                                    dietInfo.instructions = row_data[3],
                                    dietInfo.type_of_food = row_data[1],
                                    dietInfo.no_of_servings = row_data[2],
                                    dietInfo.created_by = $('#doctorId').val(),
                                    dietInfo.user_created_by = $('#HiddenUserCreatedBy').val(),
                                    dietInfo.Dml_Indicator = 'CDI',
                                    dietInfo.DisplayOrder = row_data[4]

                                    dietArray.push(dietInfo);
                                }
                            }


                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/CaseStudy/DeitDetails_Ins',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(dietArray),
                                success: function (data) {
                                    var data = JSON.parse(data);
                                    if (data.msg == "Success") {
                                        setTimeout(function () { $('.close').click(); }, 500);
                                        clear_diet();
                                        if (val == 2) {
                                        window.open('/PatientDashboard/diet?visitreportid=' + $('#VisitReportID').val(), "_blank");
                                        }
                                    }
                                    else {
                                        console.log(data);
                                    }
                                }
                            });
                        //var tot_rowM = $('#tblDietChart >tbody >tr').length;
                        //if (tot_rowM > 0) {
                        //    var L = 0; Lcount = 0;
                        //    for (j = 1; j <= tot_rowM; j++) {
                        //        var a = $('#tblDietChart_body').children('tr').eq(L);
                        //        var b = a.prop('id');
                        //        L++;
                        //        var C = b.split('_');
                        //        var gkey = C[1];
                        //        var row_data = sessionStorage.getItem(gkey);
                        //        var K = 0;
                        //        if (row_data == "") {
                        //            console.log(gkey + '--------->' + row_data);
                        //        }
                        //        if (row_data != "" && row_data != null) {
                        //            console.log(gkey + '-------' + row_data);
                        //            row_data = row_data.split(',');
                        //            var sms = {
                        //                Dml_Indicator: 'CDI',
                        //                diet_goal_id: diet_goal_id,
                        //                time: row_data[0],
                        //                created_by: $('#doctorId').val(),
                        //                instructions: row_data[3],
                        //                type_of_food: row_data[1],
                        //                no_of_servings: row_data[2],
                        //            }
                        //            $.ajax({
                        //                async: true,
                        //                type: 'POST',
                        //                url: '/CaseStudy/DeitTemplate',
                        //                contentType: 'application/json; charset=UTF-8',
                        //                data: JSON.stringify(sms),
                        //                success: function (data) {
                        //                    var data = JSON.parse(data);
                        //                    Lcount++;
                        //                    if (data.msg == "Success") {
                        //                        var data = data.data;
                        //                        if (Lcount == tot_rowM) {
                        //                            setTimeout(function () { $('.close').click(); $('#shade_slot').hide(); }, 500);
                        //                            clear_diet();
                        //                            if (val == 2) {
                        //                                window.open('/PatientDashboard/diet?visitreportid=' + $('#VisitReportID').val(), "_blank");
                        //                            }
                        //                        }
                        //                    }
                        //                    else {
                        //                        console.log(data);
                        //                        $('#shade_slot').hide();
                        //                    }
                        //                }
                        //            });
                        //        }
                        //    }
                            $('#txtTime').val('');
                            $('#txtfood').val('');
                            $('#txtQuantity').val('');
                            $('#txtInstructions').val('');
                            $('#txtdietname').val('');
                        }
                        //}
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}

$('#AddDiettable_print').click(function () {
    dietVisitreportId('2');
});
function clear_diet() {
    $('#benifits').val('');
    $('#txtInstruction').val('');
    $('#txtTime').val('');
    $('#txtfood').val('');
    $('#txtQuantity').val('');
    $('#txtInstructions').val('');
    $('#txtdietname').html('');
    $('#txtKcal').html('');
    $('#tblDietChart > tbody').empty();

    $('a[data-toggle=Etime][data-title=90]').removeClass('active').addClass('not-active');
    $('a[data-toggle=Etime][data-title=180]').removeClass('active').addClass('not-active');
    $('#Etime').val('');

}

//diet end

//buy package code started

function dashboard_buy_package(patient_id) {
    var package_data = {
        indicator_id: "PSR",
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            $('#packagecard').empty();
            $('#patdata').show();
            if (jQuery.isEmptyObject((data)) || data.length == 0) {
            }
            else {
                var image = '', coupon = '';
                var data1 = JSON.parse(data);
                var b = data1.Table;
                var c = data1.Table1;
                $.each(b, function (i, emp) {
                    if (emp.photo != "") {
                        image = $('#patphotop').val() + emp.photo;
                    }
                    else {
                        image = "/Content/img/profile_icon.png";
                    }
                    $('#patient_photo').attr('src', "" + image + "");
                    $('#patient_name').html(emp.first_name);
                    $('#patient_number').html(emp.phone_number_1);
                    $('#patient_id1').val(emp.patient_id);
                });
                $.each(c, function (i, emp) {
                    if (emp.package_image_url != "") {
                        image = $('#patphotop').val() + emp.photo;
                    }
                    else {
                        image = "/Content/img/profile_icon.png";
                    }
                    patient_id = $('#patient_id1').val();
                    coupon = coupon + " <a href='javascript:void(0)' class='ur-sell-pkge' id='individualcard' onclick = package_invoice_generation(this) data-id=" + emp.package_id + " data-name=" + emp.price + "><div class='col-md-6 pkg-detail-card'><div class='pkge_detail_block_card col-md-12'><div class='col-md-12 col-sm-3 col-xs-4 padding0'><div class='package-prof_imgblock text-center'><img src=" + image + " class='img-responsive imgphoto' id='packimage'></div></div><div class='col-md-12 col-sm-8 col-xs-8 padding0'><div class='col-md-12 text-center m22'><p class='pkage-name' id='sellpackage_name'>" + emp.package_name + "</p><p class='pkage-name' id='sellpack_cost'>" + emp.price + "</p><p class='pkage-name' id='sellpack_expire_date'>" + (emp.package_validity_date).split('T')[0] + "</p><p class='pkage-name' id='packhigh'>" + emp.price + "</p></div></div></div></div></a>";
                });
                $('#packagecard').html(coupon);
            }
        }
    });
}

function package_invoice_generation(e) {
    var id = e.getAttribute("data-id")
    var price_amt = e.getAttribute("data-name");
    var package_data = {
        indicator_id: "PIG",
        package_id: id,
        patient_id: $('#patient_id1').val(),
        price: price_amt
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            if (jQuery.isEmptyObject((data)) || data.length == 0) {
            }
            else {
                var data1, b, c, msg, package_id, invoice_id, patient_id, db_msg, pay_msg, patient_id, patient_name, patient_phone_number, patient_visit_id, age, gender;
                data1 = JSON.parse(data);
                b = data1.Table;
                c = data1.Table1;
                $.each(b, function (i, emp) {
                    db_msg = emp.msg;
                    msg = "you choosen package amount was Rs." + emp.invoice_amount + " . Are you buy a package?";
                    package_id = emp.lab_order_id;
                    invoice_id = emp.invoice_id;
                    patient_id = emp.patient_id;
                });
                $.each(c, function (i, emp) {
                    patient_id = emp.patient_id;
                    patient_name = emp.first_name;
                    patient_phone_number = emp.phone_number_1;
                    patient_visit_id = emp.visit_report_id;
                    age = emp.age;
                    gender = emp.gender;
                });
                if (db_msg != "already taken") {
                    r = confirm(msg);
                    if (r == true) {
                        pay_msg = "Invoice generated successfully, are you go to payment?"
                        pay_msg = confirm(pay_msg);
                        if (pay_msg == true) {
                            collectpayment(patient_id, patient_name, patient_phone_number, patient_visit_id, '1', age, gender);
                        }
                        else {
                            toastr.success("Thank You");
                        }
                    }
                    else {
                        toastr.success("Thank you!!");
                    }
                }
                else {
                    toastr.warning("You are already bought this package, Please check it");
                    collectpayment(patient_id, patient_name, patient_phone_number, patient_visit_id, '1', age, gender);
                }
            }
        }
    });
}

function get_package_details(package_id, invoice_id, patient_id) {
    var package_data = {
        indicator_id: "GPD",
        package_id: package_id,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                //else if (data.length > 0){
                else {
                    var no_of_consultation, cosult_details, lab_deatils, pharmadetails, j = 0, data_list = [], list_data = '';

                    cosult_details = data1.Table;
                    lab_deatils = data1.Table1;
                    pharmadetails = data1.Table2;
                    var data = new Array();
                    var data1 = new Array();
                    if (cosult_details[0]["no_of_consultation"] != null || cosult_details[0]["no_of_consultation"] != '') {
                        for (i = 0; i < cosult_details[0]["no_of_consultation"]; i++) {
                            if (cosult_details[0]["no_of_consultation"] > i) {
                                data["package_id"] = cosult_details[0]["package_id"];
                                data["patient_id"] = patient_id;
                                data["coupon_status"] = "1";
                                data["coupon_expire_date"] = cosult_details[0]["date_of_expire"];
                                data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                                data["type_id"] = cosult_details[0]["consult_id"];
                                data["type"] = "1";
                                insert_coupon(data);
                            }
                        }
                    }
                    data = [];
                    if (lab_deatils[0]["no_of_package"] != null || lab_deatils[0]["no_of_package"] != '') {
                        for (i = 0; i < lab_deatils[0]["no_of_package"]; i++) {
                            if (lab_deatils[0]["no_of_package"] > i) {
                                data["package_id"] = lab_deatils[0]["package_id"];
                                data["patient_id"] = patient_id;
                                data["coupon_status"] = "1";
                                data["coupon_expire_date"] = lab_deatils[0]["date_of_expire"];
                                data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                                data["type_id"] = lab_deatils[0]["lab_package_id"];
                                data["type"] = "2";
                                insert_coupon(data);
                            }
                        }
                    }
                    data = [];
                    if (pharmadetails[0]["no_of_free_delivery"] != null || pharmadetails[0]["no_of_free_delivery"] != '') {
                        for (i = 0; i < pharmadetails[0]["no_of_free_delivery"]; i++) {
                            if (pharmadetails[0]["no_of_free_delivery"] > i) {
                                data["package_id"] = pharmadetails[0]["package_id"];
                                data["patient_id"] = patient_id;
                                data["coupon_status"] = "1";
                                data["coupon_expire_date"] = pharmadetails[0]["date_of_expire"];
                                data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                                data["type_id"] = pharmadetails[0]["package_pharmacy_details_id"];
                                data["type"] = "3";
                                insert_coupon(data);
                            }
                        }
                    }
                }
                package_purchase_insert(package_id, invoice_id);
            }
            else {
                console.log(data1);
            }
        }
    });
}

function insert_coupon(data_list) {
    var package_data = {
        indicator_id: "PCDI",
        package_id: data_list.package_id,
        patient_id: data_list.patient_id,
        coupon_status: data_list.coupon_status,
        coupon_expire_date: data_list.coupon_expire_date,
        coupon_consumed_by: data_list.coupon_consumed_by,
        type_id: data_list.type_id,
        type: data_list.type
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
        }
    });
}

function package_purchase_insert(package_id, invoice_id) {
    var package_data = {
        indicator_id: "PPDI",
        package_id: package_id,
        patient_id: invoice_id.split('-')[0],
        invoice_id: invoice_id,
        booking_device: "1",
        payment_type: "1",
        created_by: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        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) {
                        toastr.success("Thank you for buying this package!!!");
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


$(document).on("click", ".cpPopClose", function () {
    $(this).parents(".popover").popover('hide');
});



//package invoice payment funtion code started



//buy package code ended


//casesheet popup start point

$('#Add_lab_details').click(function () {
    if ($('#txttest_name').val() == '') {
        $('#P_txttest_name').show();
        $('#P_txttest_name').fadeOut(8000);
        $('#P_txttest_name').html('Select parameter name');
        $('#txttest_name').focus();
        $('#txttest_name').val('');
        return false;
    }
    if ($('#Observed').val() == '') {
        $('#P_Observed').show();
        $('#P_Observed').fadeOut(8000);
        $('#P_Observed').html('Enter the Observed');
        $('#Observed').focus();
        $('#Observed').val('');
        return false;
    }
    if ($('#txtRef').html() == '') {
        $('#P_txtRef').show();
        $('#P_txtRef').fadeOut(8000);
        $('#P_txtRef').html('Select Ref value');
        $('#txtRef').focus();
        $('#txtRef').val('');
        return false;
    }
    if ($('#txtunits').html() == '') {
        $('#P_txtunits').show();
        $('#P_txtunits').fadeOut(8000);
        $('#P_txtunits').html('Select Units');
        $('#txtunits').focus();
        $('#txtunits').val('');
        return false;
    }

    var labval = {
        visit_report_id: $('#VisitReportID').val(),
        parameter_value: $('#Observed').val(),
        parameter_id: $('#parameter_id').val(),
        Dml_Indicator: 'I',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/master_lab_test',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        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].StringMsg == "success") {
                            $('#P_txttest_name').show();
                            $('#P_txttest_name').fadeOut(8000);
                            $('#P_txttest_name').html('saved successfully !!!');
                        }
                        var tr = '';
                        $('#tbl_lab_details').empty();
                        for (var i = 0; i < data.length; i++) {

                            tr = tr + '<tr><td>' + data[i].parameter_name + '</td><td>' + data[i].parameter_value + '</td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td><td><button class="delete btn btn-default   btn-sm btn-add" data-toggle="popover" title="Delete" onclick="lab_details_del(' + data[i].master_labtest_visit_report_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                        }
                        $('#tbl_lab_details').html(tr);

                        $('#txttest_name').val('');
                        $('#Observed').val('');
                        $('#txtRef').html('');
                        $('#txtunits').html('');
                    }
                }
            }
            else {
                console.log(data);
            }

        }
    });
});


function labdetails() {
    var labval = {
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'VS',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/master_lab_test',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        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].StringMsg == "success") {
                            $('#P_txttest_name').show();
                            $('#P_txttest_name').fadeOut(8000);
                            $('#P_txttest_name').html('saved successfully !!!');
                        }
                        var tr = '';
                        $('#tbl_lab_details').empty();
                        for (var i = 0; i < data.length; i++) {

                            tr = tr + '<tr><td>' + data[i].parameter_name + '</td><td>' + data[i].parameter_value + '</td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td><td><button class="delete btn btn-default   btn-sm btn-add" data-toggle="popover" title="Delete" onclick="lab_details_del(' + data[i].master_labtest_visit_report_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                        }
                        $('#tbl_lab_details').html(tr);
                    }
                }
                labdetails_casesheet();
            }
            else {
                console.log(data);
            }
        }
    });

}

function lab_details_del(val) {
    var labval = {
        master_labtest_visit_report_id: val,
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'D',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/master_lab_test',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            var data = JSON.parse(data);

            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#tbl_lab_details').empty();
                }
                else {

                    if (data.length > 0) {
                        if (data[0].StringMsg == "success") {
                            $('#P_txttest_name').show();
                            $('#P_txttest_name').fadeOut(8000);
                            $('#P_txttest_name').html('saved successfully !!!');
                        }
                        var tr = '';
                        $('#tbl_lab_details').empty();
                        for (var i = 0; i < data.length; i++) {

                            tr = tr + '<tr><td>' + data[i].parameter_name + '</td><td>' + data[i].parameter_value + '</td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td><td><button class="delete btn btn-default   btn-sm btn-add" data-toggle="popover" title="Delete" onclick="lab_details_del(' + data[i].master_labtest_visit_report_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                        }
                        $('#tbl_lab_details').html(tr);
                    }
                    else {
                        $('#tbl_lab_details').empty();
                    }
                }
            }
            else {
                console.log(data);
            }

        }
    });
}



$('#btn_casesheet_popup').click(function () {
    $('#labtestloader').show();
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: '15'
    }


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

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        labtest_casesheet();
                    }

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

});

function labtest_casesheet() {
    LC_patient_level_cardiac();
    //Complaints start point
    if ($('#LC_txtHypoglycemic').val() == '' && ($('#LC_txtGlycemic').val() == 0 || $('#LC_txtGlycemic').val() == '') && $('#LC_txtCVS').val() == '' && $('#LC_txtABS').val() == '' && $('#LC_txtRS').val() == '' && $('#LC_txtCNS').val() == '' && $('#LC_ChkHeartSound').prop('checked') == false && $('#LC_ChkMurmurs').prop('checked') == false && $('#LC_ChkReducedAir').prop('checked') == false && $('#LC_ChkCrackles').prop('checked') == false && $('#LC_ChkBowelSounds').prop('checked') == false && $('#LC_ChkOrganomegaly').prop('checked') == false && $('#LC_ChkTremors').prop('checked') == false && $('#LC_ChkCognitive').prop('checked') == false) {
    }
    else {
        var Glycemic_variability = $('#LC_txtGlycemic').val();
        var heart_sound, murmurs, reduce_air_entry, bowel_sounds, organomeglay, tremors_weakness, cognitive_imparement, crackles;
        if ($('#LC_ChkHeartSound').prop('checked')) {
            heart_sound = 1;
        } else {
            heart_sound = 0;
        }
        if ($('#LC_ChkMurmurs').prop('checked')) {
            murmurs = 1
        } else {
            murmurs = 0
        }
        if ($('#LC_ChkReducedAir').prop('checked')) {
            reduce_air_entry = 1
        } else {
            reduce_air_entry = 0
        }
        if ($('#LC_ChkCrackles').prop('checked')) {
            crackles = 1
        } else {
            crackles = 0
        }
        if ($('#LC_ChkBowelSounds').prop('checked')) {
            bowel_sounds = 1
        } else {
            bowel_sounds = 0
        }
        if ($('#LC_ChkOrganomegaly').prop('checked')) {
            organomeglay = 1
        } else {
            organomeglay = 0
        }
        if ($('#LC_ChkTremors').prop('checked')) {
            tremors_weakness = 1
        } else {
            tremors_weakness = 0
        }
        if ($('#LC_ChkCognitive').prop('checked')) {
            cognitive_imparement = 1
        } else {
            cognitive_imparement = 0
        }
        var Dml_Indicator = 'QI';
        var ObservationData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            hypoglycemia_episodes: $('#LC_txtHypoglycemic').val(),
            glycemic_variability: Glycemic_variability,
            cvs: $('#LC_txtCVS').val(),
            heart_sound: heart_sound,
            murmurs: murmurs,
            rs: $('#LC_txtRS').val(),
            reduce_air_entry: reduce_air_entry,
            crackles: crackles,
            ABS: $('#LC_txtABS').val(),
            bowel_sounds: bowel_sounds,
            organomeglay: organomeglay,
            CNS: $('#LC_txtCNS').val(),
            tremors_weakness: tremors_weakness,
            cognitive_imparement: cognitive_imparement,
            patient_id: $('#Hdnpatient_id').val(),
            created_by: $('#doctorId').val(),
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Observation_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(ObservationData),
            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].StringMsg == "success") {

                            }
                        }

                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //complaints end point

    //Glycemic Parameters start point

    if ($('#LC_txtHbA1c').val() == '' && $('#LC_txtfastingInsulin').val() == '' && $('#LC_txtBloodsugarV_1').val() == '' && $('#LC_txtBloodsugarV_2').val() == '' && $('#LC_txtBloodsugarV_3').val() == '' && $('#LC_txtBloodsugarV_4').val() == '' && $('#LC_txtBloodsugarV_5').val() == '' && $('#LC_txtBloodsugarV_6').val() == '' && $('#LC_txtBloodsugarV_7').val() == '' && $('#LC_txtBloodsugarV_8').val() == '' && $('#LC_txtKetones').val() == '' && $('#LC_txtWBC').val() == '' && $('#LC_txtHB').val() == '' && $('#LC_txtPlatelets').val() == '' && $('#LC_txtnotes_glycemic').val() == '') {

    }
    else {
        var value_1 = '', value_2 = '', value_3 = '', value_4 = '', value_5 = '', value_6 = '', value_7 = '', value_8 = ''
        if ($.trim($('#LC_txtBloodsugarV_1').val()) != '') {
            value_1 = 1
        }
        if ($.trim($('#LC_txtBloodsugarV_2').val()) != '') {
            value_2 = 2
        }
        if ($.trim($('#LC_txtBloodsugarV_3').val()) != '') {
            value_3 = 3
        }
        if ($.trim($('#LC_txtBloodsugarV_4').val()) != '') {
            value_4 = 4
        }
        if ($.trim($('#LC_txtBloodsugarV_5').val()) != '') {
            value_5 = 5
        }
        if ($.trim($('#LC_txtBloodsugarV_6').val()) != '') {
            value_6 = 6
        }
        if ($.trim($('#LC_txtBloodsugarV_7').val()) != '') {
            value_7 = 7
        }
        if ($.trim($('#LC_txtBloodsugarV_8').val()) != '') {
            value_8 = 8
        }
        Dml_Indicator = 'IQ';

        var GlycemicData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            set_by: $('#doctorId').val(),
            created_by: $('#doctorId').val(),
            patient_id: $('#Hdnpatient_id').val(),
            hemoglobin: $('#LC_txtHB').val(),
            patient_hbac_record_value: $('#LC_txtHbA1c').val(),
            fasting_insulin: $('#LC_txtfastingInsulin').val(),
            fasting_inslin_unit: $('#LC_txtfastingInsulin_T').val(),
            note: $('#LC_txtnotes_glycemic').val(),
            WBC: $('#LC_txtWBC').val(),
            platelet: $('#LC_txtPlatelets').val(),
            patient_blood_group: $('#LC_Selbloodgroup').val(),
            se_ketones: $('#LC_txtKetones').val(),


            patient_blood_sugar_value_1: $('#LC_txtBloodsugarV_1').val(),
            patient_blood_sugar_unit_1: $('#LC_txtBloodsugarT_1').val(),
            patient_blood_sugar_type_1: value_1,

            patient_blood_sugar_value_2: $('#LC_txtBloodsugarV_2').val(),
            patient_blood_sugar_unit_2: $('#LC_txtBloodsugarT_2').val(),
            patient_blood_sugar_type_2: value_2,

            patient_blood_sugar_value_3: $('#LC_txtBloodsugarV_3').val(),
            patient_blood_sugar_unit_3: $('#LC_txtBloodsugarT_3').val(),
            patient_blood_sugar_type_3: value_3,

            patient_blood_sugar_value_4: $('#LC_txtBloodsugarV_4').val(),
            patient_blood_sugar_unit_4: $('#LC_txtBloodsugarT_4').val(),
            patient_blood_sugar_type_4: value_4,

            patient_blood_sugar_value_5: $('#LC_txtBloodsugarV_5').val(),
            patient_blood_sugar_unit_5: $('#LC_txtBloodsugarT_5').val(),
            patient_blood_sugar_type_5: value_5,

            patient_blood_sugar_value_6: $('#LC_txtBloodsugarV_6').val(),
            patient_blood_sugar_unit_6: $('#LC_txtBloodsugarT_6').val(),
            patient_blood_sugar_type_6: value_6,

            patient_blood_sugar_value_7: $('#LC_txtBloodsugarV_7').val(),
            patient_blood_sugar_unit_7: $('#LC_txtBloodsugarT_7').val(),
            patient_blood_sugar_type_7: value_7,

            patient_blood_sugar_value_8: $('#LC_txtBloodsugarV_8').val(),
            patient_blood_sugar_unit_8: $('#LC_txtBloodsugarT_8').val(),
            patient_blood_sugar_type_8: value_8,

            bp_flag_type: '',
            patient_id: $('#Hdnpatient_id').val(),
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Glycemic_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(GlycemicData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //Glycemic Parameters end point

    //Renal start point
    if ($('#LC_txtUrea').val() == '' && $('#LC_txtCreatinine').val() == '' && $('#LC_txtCKD').val() == '' && $('#LC_txtSodium').val() == '' && $('#LC_txtCalcium').val() == '' && $('#LC_txtPotassium').val() == '' && $('#LC_txtPhosphorus').val() == '' && $('#LC_txtChlorine').val() == '' && $('#LC_txtMagnesium').val() == '' && $('#LC_txtBiCrabonate').val() == '' && $('#LC_txtnotes_renal').val() == '' && ($('#LC_Chknepropathy').val() == 0 || $('#LC_Chknepropathy').val() == '')) {

    }
    else {
        var ACR = $("input[name='LC_acr1']").val();

        var nephropathy = $('#LC_Chknepropathy').val()


        var Dml_Indicator = 'IQ';
        var egfr = $('#LC_txtEGFR').val();
        var egfr_value = egfr.split('ml');
        egfr = egfr_value[0];
        if (egfr == "- ") egfr = "0";
        var RenalData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            ACR: ACR,
            nephropathy: nephropathy,
            Urea: $('#LC_txtUrea').val(),
            urea_unit: '1',
            egfr_value: egfr,
            creatinine: $('#LC_txtCreatinine').val(),
            Creatinine_unit: $('#LC_SelCreatinine').val(),
            stage_CKD: $('#LC_txtCKDVal').val(),
            Sodium: $('#LC_txtSodium').val(),
            sodium_unit: $('#LC_SelSodium').val(),
            Potassium: $('#LC_txtPotassium').val(),
            potassium_unit: $('#LC_SelPotassium').val(),
            Chlorine: $('#LC_txtChlorine').val(),
            chlorine_unit: $('#LC_SelChlorine').val(),

            BiCarbonate: $('#LC_txtBiCrabonate').val(),
            Bicarbonate_unit: $('#LC_SelBicrabonate').val(),
            Urine_routine: '',

            serium_calcium: $('#LC_txtCalcium').val(),
            Calcium_unit: $('#LC_SelCalcium').val(),

            serium_phosphorous: $('#LC_txtPhosphorus').val(),
            Phosphorus_unit: $('#LC_SelPhosphorus').val(),

            serium_magnesium: $('#LC_txtMagnesium').val(),
            Magnesium_unit: $('#LC_SelMagnesium').val(),
            note: $('#LC_txtnotes_renal').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Renal_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(RenalData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

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

    //Renal end point

    //cholestral start point

    if ($('#LC_txtTCholesterol').val() == '' && $('#LC_txtVLDL').val() == '' && $('#LC_txtLDL').val() == '' && $('#LC_txtTriglycerides').val() == '' && $('#LC_txtHDL').val() == '' && $('#LC_txtHDLRatio').val() == '' && $('#LC_txtnotes_cholesterol').val() == '' && $('#LC_txtNHDL').val() == '') {

    }
    else {

        var dyslipedemia = $('#LC_ChkDyslipidemia').val();

        var Dml_Indicator = "I";

        var cholestrol = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            LDL: $('#LC_txtLDL').val(),
            LDL_unit: $('#LC_SelLDL').val(),
            HDL: $('#LC_txtHDL').val(),
            HDL_unit: $('#LC_SeltxtHDL').val(),
            NHDL: $('#LC_txtNHDL').val(),
            Total_Cholestrol: $('#LC_txtTCholesterol').val(),
            Total_cholestrol_unit: $('#LC_SelTCholesterol').val(),
            Triglycerides: $('#LC_txtTriglycerides').val(),
            Triglycerides_unit: $('#LC_SelTriglycerides').val(),
            VLDL: $('#LC_txtVLDL').val(),
            VLDL_unit: $('#LC_SelVLDL').val(),
            T_cholestrol_Hdl_ratio: $('#LC_txtHDLRatio').val(),
            dyslipedemia: dyslipedemia,
            note: $('#LC_txtnotes_cholesterol').val()
        }

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

                    }
                    else {
                        if (data[0].StringMsg == "success") {

                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //cholestral end point

    //opthal start point
    if (($('#LC_PDRradio').val() == '' || $('#LC_PDRradio').val() == 0) && ($('#LC_NPDRradio').val() == '' || $('#LC_NPDRradio').val() == 0) && ($('#LC_ChkHemorrhage').val() == '' || $('#LC_ChkHemorrhage').val() == '0') && ($('#LC_ChkDetachment').val() == '' || $('#LC_ChkDetachment').val() == 0) && ($('#LC_ChkRetinopathy').val() == '' || $('#LC_ChkRetinopathy').val() == 0) && $('#LC_dpd12').val() == '' && $('#LC_dpd2').val() == '' && $('#LC_txtnotes_opthal').val() == '') {
    }
    else {
        var Dml_Indicator;

        var pdr = $("#LC_PDRradio").val();

        var npdr = $("#LC_NPDRradio").val();

        var ChkHemorrhage = $('#LC_ChkHemorrhage').val(),
            ChkDetachment = $('#LC_ChkDetachment').val(),
            ChkRetinopathy = $('#LC_ChkRetinopathy').val();

        var Dml_Indicator = 'I';
        var lastObservationDate = $('#LC_dpd12').val();

        var nextSuggestedAppointment = $('#LC_dpd2').val();

        var lastdate = lastObservationDate.split('/');
        var lastObservationDate = lastdate[2] + "-" + lastdate[1] + "-" + lastdate[0];

        var Nextdate = nextSuggestedAppointment.split('/');
        var nextSuggestedAppointment = Nextdate[2] + "-" + Nextdate[1] + "-" + Nextdate[0];

        var cholestrol = {
            visit_report_id: $('#VisitReportID').val(),
            last_observation_date: lastObservationDate,
            next_suggested_appointment: nextSuggestedAppointment,
            Dml_Indicator: Dml_Indicator,
            pdr: pdr,
            npdr: npdr,
            patient_id: $('#Hdnpatient_id').val(),
            viterous_hemorage: ChkHemorrhage,
            retinopathy: ChkRetinopathy,
            retinal_detachement: ChkDetachment,
            Doctor_id: $('#HiddenDoctorID').val(),
            note: $('#LC_txtnotes_opthal').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Opthal_Ins_Sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(cholestrol),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //opthal end point

    //cardiac start point
    if ($('#LC_txtecg').val() == '' && $('#LC_txtecho').val() == '' && ($('#LC_R_tmt').val == '' || $('#LC_R_tmt').val == 0) && $('#LC_Chkecg').prop('checked') == false && $('#LC_Selecho').prop('checked') == false && $('#LC_txtnotes_cardiac').val() == '' && $('#LC_txtnotes_ASD').val() == '' && $('#LC_txtnotes_VSD').val() == '' && $('#LC_txtnotes_value').val() == '' && $('#LC_txtnotes_Ejection').val() == '' && $('#LC_txtnotes_Mitral').val() == '' && $('#LC_txtnotes_lotic').val() == '' && $('#LC_txtnotes_Tricuspid').val() == '' && $('#LC_txtnotes_Pulmonary').val() == '') {
    }
    else {
        var ascvd_score = 0;
        var TMT_test = $("#LC_R_tmt").val();

        var ecg_abnormal = '0', echo_abnormal = '0', ON_Hypertension_drugs = '0', ON_statin = '0', ON_Aspirin_Theraphy = '0'
        if ($('#LC_Chkecg').prop('checked')) {
            ecg_abnormal = '1';
        }
        if ($('#LC_Selecho').prop('checked')) {
            echo_abnormal = '1';
        }
        if ($('#LC_txtDrugs').val() == 1) {
            ON_Hypertension_drugs = '1';
        }
        if ($('#LC_txtStatin').val() == 1) {
            ON_statin = '1';
        }
        if ($('#LC_txtTherapy').val() == 1) {
            ON_Aspirin_Theraphy = '1';
        }

        var Dml_Indicator = 'I';

        var Cardiac = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            ECG: $('#LC_txtecg').val(),
            ecg_abnormal: ecg_abnormal,
            ECHO: $('#LC_txtecho').val(),
            echo_abnormal: echo_abnormal,
            TMT_test: TMT_test,
            ascvd_score: ascvd_score,
            ON_Hypertension_drugs: ON_Hypertension_drugs,
            ON_statin: ON_statin,
            ON_Aspirin_Theraphy: ON_Aspirin_Theraphy,
            note: $('#LC_txtnotes_cardiac').val(),
            ASD: $('#LC_txtnotes_ASD').val(),
            VSD: $('#LC_txtnotes_VSD').val(),
            C_value: $('#LC_txtnotes_value').val(),
            fraction: $('#LC_txtnotes_Ejection').val(),
            mitral_value: $('#LC_txtnotes_Mitral').val(),
            lotic_value: $('#LC_txtnotes_lotic').val(),
            tricuspid: $('#LC_txtnotes_Tricuspid').val(),
            pulmonary: $('#LC_txtnotes_Pulmonary').val(),
        }

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

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

    //cardiac end point

    //---- want to start the new 

    //Neuropathy start point
    if (($('#LC_per_neu').val == '' || $('#LC_per_neu').val == 0) && ($('#LC_chkANeuropathy').val() == '' || $('#LC_chkANeuropathy').val() == 0) && $('#LC_txtDoppler').val() == '' && ($('#LC_AB_index').val() == '' || $('#LC_AB_index').val() == 0) && $('#LC_txtnotes_neuropathy').val() == '') {
    }
    else {
        var peripharal_neuhropathy = $("#LC_per_neu").val();
        var AB_index = $("#LC_AB_index").val();
        var ANeuropathy = $('#LC_chkANeuropathy').val();
        var Dml_Indicator = 'I';
        var cholestrol = {
            visit_report_id: $('#VisitReportID').val(),
            peripharal_neuhropathy: peripharal_neuhropathy,
            autonomic_neuropathy: ANeuropathy,
            autonomic_neuropathy_set_by: $('#doctorId').val(),
            AB_index: AB_index,
            doppler_note: $('#LC_txtDoppler').val(),
            note: $('#LC_txtnotes_neuropathy').val(),
            Dml_Indicator: Dml_Indicator,
            patient_id: $('#Hdnpatient_id').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Neuropathy_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(cholestrol),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

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

    }

    //Neuropathy end point

    //Thyroid start point
    if ($('#LC_txtT3').val() == '' && $('#LC_txtT4').val() == '' && $('#LC_txtTSH').val() == '' && $('#LC_txtnotes_thyroid').val() == '' && $('#LC_N_txtT3').val() == '' && $('#LC_N_txtT4').val() == '') {

    }
    else {
        var Dml_Indicator = 'I';
        var cholestrol = {
            visit_report_id: $('#VisitReportID').val(),
            Free_T3: $('#LC_txtT3').val(),
            Free_T3_unit: $('#LC_SelT3').val(),
            Free_T4: $('#LC_txtT4').val(),
            Free_T4_unit: $('#LC_SelT4').val(),
            T3: $('#LC_N_txtT3').val(),
            T3_unit: $('#LC_N_SelT3').val(),
            T4: $('#LC_N_txtT4').val(),
            T4_unit: $('#LC_N_SelT4').val(),
            TSH: $('#LC_txtTSH').val(),
            TSH_unit: $('#LC_SelTSH').val(),
            note: $('#LC_txtnotes_thyroid').val(),
            Dml_Indicator: Dml_Indicator
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Thyroid_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(cholestrol),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //Thyroid end point

    //ultrasound start point 
    if ($('#LC_txtNotes').val() == '' && $('#LC_txtUNotes').val() == '' && $('#LC_ctsnotes').val() == '' && ($('#LC_chkLiver').val == '' || $('#LC_chkLiver').val == 0) && ($('#LC_chkGS').val == '' || $('#LC_chkGS').val == 0)) {

    }
    else {
        var fatty_lives = $('#LC_chkLiver').val(),
            GS_Calculus = $('#LC_chkGS').val();
        var Dml_Indicator;

        Dml_Indicator = 'I';
        var UltraSound = {
            visit_report_id: $('#VisitReportID').val(),
            notes: $('#LC_txtNotes').val(),
            fatty_lives: fatty_lives,
            GS_Calculus: GS_Calculus,
            UNOTES: $('#LC_txtUNotes').val(),
            cts_notes: $('#LC_ctsnotes').val(),
            Dml_Indicator: Dml_Indicator
        }

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

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //ultrasound end point 

    //Liver Function Test start point 
    if ($('#LC_txtSerum_Bilirubin_Total').val() == '' && $('#LC_txtSerum_Bilirubin_Direct').val() == '' && ($('#LC_txtBilirubin_Indirect').val == '' || $('#LC_txtSerum_Protein_Total').val == 0) && ($('#LC_txtSerum_Protein_Albumin').val == '' || $('#LC_txtSerum_Protein_Glibulin').val == 0) && $('#LC_txtSGOT').val() == '' && $('#LC_txtSGPT').val() == '' && $('#LC_txtSerum_Alkaline_Phosphatase').val() == '' && $('#LC_txtGamma_Glutamyl_Transpeptidase').val() == '' && $('#LC_txtSerum_Magnesium').val() == '') {

    }
    else {
        var lever = {
            serum_bilirubin_total: $('#LC_txtSerum_Bilirubin_Total').val(),
            serum_bilirubin_direct: $('#LC_txtSerum_Bilirubin_Direct').val(),
            bilirubin_indirect: $('#LC_txtBilirubin_Indirect').val(),
            serum_protein_total: $('#LC_txtSerum_Protein_Total').val(),
            serum_protein_albumin: $('#LC_txtSerum_Protein_Albumin').val(),
            serumproteinglibulin: $('#LC_txtSerum_Protein_Glibulin').val(),
            SGOT: $('#LC_txtSGOT').val(),
            SGPT: $('#LC_txtSGPT').val(),
            serum_alkaline_phosphatase: $('#LC_txtSerum_Alkaline_Phosphatase').val(),
            gamma_glutamyl_transpeptidase: $('#LC_txtGamma_Glutamyl_Transpeptidase').val(),
            serum_magnesium: $('#LC_txtSerum_Magnesium').val(),
            Dml_Indicator: 'I',
            visit_report_id: $('#VisitReportID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/liver_function_test',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(lever),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //cbc start
    if ($('#txtCBCHemoglobin_1').val() == '' && $('#txtNucleatedBloodcell_1').val() == '' && $('#txtNucleatedBloodcellPercent_1').val() == '' && $('#txtHematocrit_1').val() == '' && $('#txtPlateletCount_1').val() == '' && $('#txtTotalLeucocytesCount_1').val() == '' && $('#txtLymphocytePercent_1').val() == '' && $('#txtMeanCorpuscular_1').val() == '' && $('#txtMeanCorpHemoConc_1').val() == '' && $('#txtMeanCorpuscularVolume_1').val() == '' && $('#txtMonocytes_1').val() == '' && $('#txtNeutrophils_1').val() == '' && $('#txtEosinophilsCount_1').val() == '' && $('#txtBasophilsCount_1').val() == '' && $('#txtLymphocyteCount_1').val() == '' && $('#txtMonocytesAbsoluteCount_1').val() == '' && $('#txtNeutrophilsAbsoluteCount_1').val() == '' && $('#txtBasophils_1').val() == '' && $('#txtEosinophils_1').val() == '' && $('#txtImmatureGranulocytes_1').val() == '' && $('#txtImmatureGranulocytesPercent_1').val() == '' && $('#txtTotalRBC_1').val() == '' && $('#txtRedCellDistributionWidthRD_1').val() == '' && $('#txtRedCellDistributionWidthSD_1').val() == '') {

    }
    else {

        var Dml_Indicator;
        //if ($("#btnCBC").html() == "Update &amp; Next") {
        //    Dml_Indicator = 'U';
        //}
        //else {
        Dml_Indicator = 'I';
        //}
        $("#btnCBC").html('Update & Next')
        var cholestrol = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            hemoglobin: $('#txtCBCHemoglobin_1').val(),
            hemoglobin_unit: $('#txtCBCHemoglobinUnit_1').val(),
            nucleated_red_blood_cells: $('#txtNucleatedBloodcell_1').val(),
            nucleated_red_blood_cells_percent: $('#txtNucleatedBloodcellPercent_1').val(),
            hematocrit: $('#txtHematocrit_1').val(),
            platelet_count: $('#txtPlateletCount_1').val(),
            platelet_count_unit: $('#txtPlateletCountUnit_1').val(),
            total_leucocytes_count: $('#txtTotalLeucocytesCount_1').val(),
            lymphocyte_percent: $('#txtLymphocytePercent_1').val(),
            mean_corpuscular_hemoglobin: $('#txtMeanCorpuscular_1').val(),
            mean_corp_hemo_conc: $('#txtMeanCorpHemoConc_1').val(),
            mean_corpuscular_volume: $('#txtMeanCorpuscularVolume_1').val(),
            monocytes: $('#txtMonocytes_1').val(),
            neutrophils: $('#txtNeutrophils_1').val(),
            eosinophils_absolute_count: $('#txtEosinophilsCount_1').val(),
            basophils_absolute_count: $('#txtBasophilsCount_1').val(),
            lymphocytes_absolute_count: $('#txtLymphocyteCount_1').val(),
            monocytes_absolute_count: $('#txtMonocytesAbsoluteCount_1').val(),
            neutrophils_absolute_count: $('#txtNeutrophilsAbsoluteCount_1').val(),
            basophils: $('#txtBasophils_1').val(),
            eosinophils: $('#txtEosinophils_1').val(),
            immature_granulocytes: $('#txtImmatureGranulocytes_1').val(),
            immature_granulocytes_percent: $('#txtImmatureGranulocytesPercent_1').val(),
            total_rbc: $('#txtTotalRBC_1').val(),
            redcell_distribution_width: $('#txtRedCellDistributionWidthRD_1').val(),
            redcell_distribution_width_sd: $('#txtRedCellDistributionWidthSD_1').val()

        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CBC_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(cholestrol),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

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

    //cbc end

    //urine routine start
    if ($('#txtSpecificGravity_1').val() == '' && $('#txtUrinaryBilirubin_1').val() == '' && $('#txtUrineBlood_1').val() == '' && $('#txtUrobilinogen_1').val() == '' && $('#txtUrinaryGlucose_1').val() == '' && $('#txtUrineKetone_1').val() == '' && $('#txtUrinaryLeucocytes_1').val() == '' && $('#txtNitrite_1').val() == '' && $('#txtPH_1').val() == '' && $('#txtUrinaryProtein_1').val() == '') {

    }
    else {

        var Dml_Indicator;
        //if ($("#btnUrineRoutine").html() == "Update &amp; Next") {
        //    Dml_Indicator = 'U';
        //}
        //else {
        Dml_Indicator = 'I';
        //}
        $("#btnUrineRoutine").html('Update & Next')
        var cholestrol = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            specific_gravity: $('#txtSpecificGravity_1').val(),
            specific_gravity_unit: $('#txtSpecificGravityUnit_1').val(),
            urinary_bilirubin: $('#txtUrinaryBilirubin_1').val(),
            urinary_bilirubin_unit: $('#txtUrinaryBilirubinUnit_1').val(),
            urine_blood: $('#txtUrineBlood_1').val(),
            urobilinogen: $('#txtUrobilinogen_1').val(),
            urobilinogen_unit: $('#txtUrobilinogenUnit_1').val(),
            urinary_glucose: $('#txtUrinaryGlucose_1').val(),
            urine_ketone: $('#txtUrineKetone_1').val(),
            urine_ketone_unit: $('#txtUrineKetoneUnit_1').val(),
            urinary_leucocytes: $('#txtUrinaryLeucocytes_1').val(),
            nitrite: $('#txtNitrite_1').val(),
            nitrite_unit: $('#txtNitriteUnit_1').val(),
            ph: $('#txtPH_1').val(),
            urinary_protein: $('#txtUrinaryProtein_1').val()

        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/UrineRoutine_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(cholestrol),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    //urine routine end
    // ultrasound end point
    setTimeout(function () {
        $('.close').click();
        $('#labtestloader').hide();
    }, 5000);
}


function LC_patient_level_cardiac() {
    var Cardiac = {
        L_LAD: $('#LC_L_txtLMCA').val(),
        L_LAD_type: $('#LC_L_LMCAradio').val(),
        L_LCX: $('#LC_L_txtLAD').val(),
        L_LCX_type: $('#LC_L_LADradio').val(),
        L_RCA: $('#LC_L_txtlcx').val(),
        L_RCA_type: $('#LC_L_lcxradio').val(),
        R_LAD: $('#LC_R_txtlad').val(),
        R_LAD_type: $('#LC_R_ladradio').val(),
        R_LCX: $('#LC_R_txtlcx').val(),
        R_LCX_type: $('#LC_R_lcxradio').val(),
        R_RCA: $('#LC_R_txtrca').val(),
        R_RCA_type: $('#LC_R_rcaradio').val(),
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Patient_level_cardiac',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Cardiac),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

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

}

function full_lab_test(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time, age, gender, doctor_id) {
    LoadCasesheetConfiguration(doctor_id);
    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
    $('#LC_txtfastingInsulin_T,#LC_txtBloodsugarT_1,#LC_txtBloodsugarT_2,#LC_txtBloodsugarT_3,#LC_txtBloodsugarT_4,#LC_txtBloodsugarT_5,#LC_txtBloodsugarT_6,#LC_txtBloodsugarT_7,#LC_txtBloodsugarT_8,#LC_SelTCholesterol,#LC_SelLDL,#LC_SelVLDL,#LC_SelTriglycerides,#LC_SeltxtHDL,#LC_SelT3,#LC_SelT3,#LC_SelTSH,#LC_SelT4,#LC_SelT4').val('1');
    $('#LC_SelUrea,#LC_SelCreatinine').val('2');
    $('#LC_SelChlorine,#LC_SelPotassium,#LC_SelChlorine,#LC_SelBicrabonate,#LC_SelCalcium,#LC_SelPhosphorus,#LC_SelMagnesium').val('3');
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#age').val(age);
    $('#gender').val(gender);
    $('#pop_doctor_id').val(doctor_id);

    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: '15'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        labdetails_casesheet();
                        labdetails();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

//select
function labdetails_casesheet() {
    var patient;
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }

    var PatientData = {
        Patient_id: patient,
        Doctor_id: $('#pop_doctor_id').val(),
        Visit_report_id: $('#VisitReportID').val(),
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseSheetSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
                }
                else {
                    $("#radioBtn > a.active").removeClass("active").addClass("not-active");

                    if (data.Table19.length > 0) {

                        var menutrpop = '';
                        $('.menutrpop').empty();
                        for (var i = 0; i < data.Table19.length; i++) {
                            if (i == 0) {
                                menutrpop = menutrpop + '<li class="list-group-item active"><a href="' + data.Table19[i].description + 'New" class="popTab_' + data.Table19[i].casesheet_module_id + '" data-toggle="tab" aria-expanded="true">' + data.Table19[i].tap_name + ' </a></li>';
                                $('.tap_' + data.Table19[i].casesheet_module_id + '').addClass('active');
                            }
                            else {
                                menutrpop = menutrpop + '<li class="list-group-item"><a href="' + data.Table19[i].description + 'New" class="popTab_' + data.Table19[i].casesheet_module_id + '" data-toggle="tab" aria-expanded="true">' + data.Table19[i].tap_name + ' </a></li>';
                            }
                        }
                        $('.menutrpop').append(menutrpop);
                    }
                    if (data.Table20.length > 0) {
                        $('#gender').val(data.Table20[0].gender);
                        if (data.Table20[0].Dage == '' || data.Table20[0].Dage == null) {
                            $('#age').val(data.Table20[0].age);
                            $('#Dage').val(data.Table20[0].age);
                        }
                        else {
                            $('#age').val(data.Table20[0].Dage);
                            $('#Dage').val(data.Table20[0].Dage);
                        }


                    }
                    //observation
                    if (data.Table.length > 0) {
                        $('#LC_txtHypoglycemic').val(data.Table[0].hypoglycemia_episodes);
                        var glycemic_variability = data.Table[0].glycemic_variability;

                        $('a[data-toggle=LC_txtGlycemic][data-title="' + glycemic_variability + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_txtGlycemic][data-title="' + glycemic_variability + '"]').addClass('active');
                        $('#LC_txtGlycemic').val(glycemic_variability);

                        $('#LC_txtPulseRate').val(data.Table[0].pulse_rate);
                        $('#LC_txtHeartRate').val(data.Table[0].heart_rate);

                        $('#LC_txtCVS').val(data.Table[0].cvs);
                        var heart_sound = data.Table[0].heart_sound;
                        if (heart_sound == 1) {
                            $('#LC_ChkHeartSound').prop('checked', true);
                        }
                        if (data.Table[0].murmurs == 1) {
                            $('#LC_ChkMurmurs').prop('checked', true);
                        }


                        $('#LC_txtABS').val(data.Table[0].ABS);
                        if (data.Table[0].bowel_sounds == 1) {
                            $('#LC_ChkBowelSounds').prop('checked', true);
                        }
                        if (data.Table[0].organomeglay == 1) {
                            $('#LC_ChkOrganomegaly').prop('checked', true);
                        }


                        $('#LC_txtRS').val(data.Table[0].rs);
                        if (data.Table[0].reduce_air_entry == 1) {
                            $('#LC_ChkReducedAir').prop('checked', true);
                        }
                        if (data.Table[0].crackles == 1) {
                            $('#LC_ChkCrackles').prop('checked', true);
                        }

                        $('#LC_txtCNS').val(data.Table[0].CNS);

                        if (data.Table[0].tremors_weakness == 1) {
                            $('#LC_ChkTremors').prop('checked', true);
                        }
                        if (data.Table[0].cognitive_imparement == 1) {
                            $('#LC_ChkCognitive').prop('checked', true);
                        }
                    }
                    //Glycemic_type_1
                    if (data.Table2.length > 0) {

                        var chkAg = data.Table2[0].Zn_Transporters;
                        var chkGAD = data.Table2[0].GAD_Antibiotics_test;
                        var chkICA = data.Table2[0].ICA;
                        var chkIAA = data.Table2[0].IAA;
                        var txtFasting = data.Table2[0].c_peptite_fasting;
                        var txtSimulated = data.Table2[0].c_peptid_simulated;

                        $('#LC_chkAg').val(chkAg);
                        $('a[data-toggle=LC_chkAg][data-title="' + chkAg + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_chkAg][data-title="' + chkAg + '"]').addClass('active');

                        $('#LC_chkGAD').val(chkGAD);
                        $('a[data-toggle=LC_chkGAD][data-title="' + chkGAD + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_chkGAD][data-title="' + chkGAD + '"]').addClass('active');

                        $('#LC_chkICA').val(chkICA);
                        $('a[data-toggle=LC_chkICA][data-title="' + chkICA + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_chkICA][data-title="' + chkICA + '"]').addClass('active');

                        $('#LC_chkIAA').val(chkIAA);
                        $('a[data-toggle=LC_chkIAA][data-title="' + chkIAA + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_chkIAA][data-title="' + chkIAA + '"]').addClass('active');

                        $('#LC_txtFasting').val(txtFasting);
                        $('#LC_txtSimulated').val(txtSimulated);
                    }

                    //Glycemic ParametersBasic
                    if (data.Table3.length > 0) {
                        $('#LC_txtHB').val(data.Table3[0].hemoglobin);
                        $('#LC_txtfastingInsulin').val(data.Table3[0].fasting_insulin);
                        $('#LC_txtfastingInsulin_T').val(data.Table3[0].fasting_inslin_unit);
                        $('#LC_txtnotes_glycemic').val(data.Table3[0].note);
                        $('#LC_txtWBC').val(data.Table3[0].WBC);
                        $('#LC_txtPlatelets').val(data.Table3[0].platelet);
                        $('#LC_txtKetones').val(data.Table3[0].se_ketones);
                    }

                    //Glycemic Parameters HBA1C
                    if (data.Table4.length > 0) {
                        $('#LC_txtHbA1c').val(data.Table4[0].patient_hbac_record_value);
                    }

                    //Glycemic HBA1C
                    if (data.Table5.length > 0) {
                        console.log(data.Table5);
                        for (var i = 0; i < data.Table5.length; i++) {
                            $('#LC_txtBloodsugarV_' + data.Table5[i].patient_blood_sugar_type).val(data.Table5[i].patient_blood_sugar_value);
                            $('#LC_txtBloodsugarT_' + data.Table5[i].patient_blood_sugar_type).val(data.Table5[i].patient_blood_sugar_unit);
                        }
                    }

                    // renal
                    if (data.Table6.length > 0) {
                        $('#LC_txtUrea').val(data.Table6[0].Urea);
                        $('#LC_SelUrea').val(data.Table6[0].urea_unit);
                        $('#LC_txtCreatinine').val(data.Table6[0].creatinine);
                        $('#LC_SelCreatinine').val(data.Table6[0].Creatinine_unit);
                        $('#LC_txtEGFR').val(data.Table6[0].egfr_value);
                        $('#LC_txtSodium').val(data.Table6[0].Sodium);
                        $('#LC_SelSodium').val(data.Table6[0].sodium_unit);
                        $('#LC_txtPotassium').val(data.Table6[0].Potassium);
                        $('#LC_SelPotassium').val(data.Table6[0].potassium_unit);
                        $('#LC_txtChlorine').val(data.Table6[0].Chlorine);
                        $('#LC_SelChlorine').val(data.Table6[0].chlorine_unit);
                        $('#LC_txtBiCrabonate').val(data.Table6[0].BiCarbonate);
                        $('#LC_SelBicrabonate').val(data.Table6[0].Bicarbonate_unit);
                        $('#LC_txtCalcium').val(data.Table6[0].serium_calcium);
                        $('#LC_SelCalcium').val(data.Table6[0].Calcium_unit);
                        $('#LC_txtPhosphorus').val(data.Table6[0].serium_phosphorous);
                        $('#LC_SelPhosphorus').val(data.Table6[0].Phosphorus_unit);
                        $('#LC_txtMagnesium').val(data.Table6[0].serium_magnesium);
                        $('#LC_SelMagnesium').val(data.Table6[0].Magnesium_unit);
                        $('#LC_txtnotes_renal').val(data.Table6[0].note);
                    }
                    //renal casesheet
                    if (data.Table7.length > 0) {
                        var Chknepropathy = data.Table7[0].nephropathy;

                        $('#LC_Chknepropathy').val(Chknepropathy);
                        $('a[data-toggle=LC_Chknepropathy][data-title="' + Chknepropathy + '"]').addClass('active');

                        var txtCKDVal = data.Table7[0].stage_CKD;
                        $('#LC_txtCKDVal').val(txtCKDVal);
                        if (txtCKDVal >= 90) {
                            $('#LC_txtCKD').val('Stage 1');
                        }
                        if (txtCKDVal >= 60 && txtCKDVal <= 89) {
                            $('#LC_txtCKD').val('Stage 2');
                        }
                        if (txtCKDVal >= 45 && txtCKDVal <= 59) {
                            $('#LC_txtCKD').val('Stage 3A');
                        }
                        if (txtCKDVal >= 30 && txtCKDVal <= 44) {
                            $('#LC_txtCKD').val('Stage 3B');
                        }
                        if (txtCKDVal >= 15 && txtCKDVal <= 29) {
                            $('#LC_txtCKD').val('Stage 4');
                        }
                        if (txtCKDVal < 15) {
                            $('#LC_txtCKD').val('Stage 5');
                        }
                        var DCCKD = $('#LC_txtCKD').val();
                        $('#LC_DKindly').html(DCCKD);
                    }

                    //Cholestrol
                    if (data.Table8.length > 0) {
                        $('#LC_txtLDL').val(data.Table8[0].LDL);
                        $('#LC_SelLDL').val(data.Table8[0].LDL_unit);
                        $('#LC_txtTCholesterol').val(data.Table8[0].Total_Cholestrol);
                        $('#LC_SelTCholesterol').val(data.Table8[0].Total_cholestrol_unit);
                        $('#LC_txtVLDL').val(data.Table8[0].VLDL);
                        $('#LC_SelVLDL').val(data.Table8[0].VLDL_unit);
                        $('#LC_txtHDL').val(data.Table8[0].HDL);
                        $('#LC_SeltxtHDL').val(data.Table8[0].HDL_unit);
                        $('#LC_txtTriglycerides').val(data.Table8[0].Triglycerides);
                        $('#LC_SelTriglycerides').val(data.Table8[0].Triglycerides_unit);
                        $('#LC_txtHDLRatio').val(data.Table8[0].T_cholestrol_Hdl_ratio);
                        $('#LC_txtNHDL').val(data.Table8[0].NHDL);
                        $('#LC_SelNHDL').val(data.Table8[0].NHDL_unit);
                        $('#LC_txtnotes_cholesterol').val(data.Table8[0].note);
                    }
                    //Cholestrol casesheet
                    if (data.Table9.length > 0) {
                        var ChkDyslipidemia = data.Table9[0].dyslipedemia;

                        $('#LC_ChkDyslipidemia').val(ChkDyslipidemia);
                        $('a[data-toggle=LC_ChkDyslipidemia][data-title="' + ChkDyslipidemia + '"]').addClass('active');
                    }

                    //Opthal
                    if (data.Table10.length > 0) {
                        $('#LC_dpd12').val(data.Table10[0].last_observation_date);
                        $('#LC_dpd2').val(data.Table10[0].next_suggested_appointment);
                        $('#LC_txtnotes_opthal').val(data.Table10[0].note);
                    }

                    //Opthal casesheet
                    if (data.Table11.length > 0) {
                        var npdr = (data.Table11[0].npdr);
                        var pdr = (data.Table11[0].pdr);
                        var ChkHemorrhage = (data.Table11[0].viterous_hemorage);
                        var ChkDetachment = (data.Table11[0].retinal_detachment);
                        var ChkRetinopathy = (data.Table11[0].retinopathy);
                        $('#LC_NPDRradio').val(npdr);
                        $('a[data-toggle=LC_NPDRradio][data-title="' + npdr + '"]').addClass('active');

                        $('#LC_PDRradio').val(pdr);
                        $('a[data-toggle=LC_PDRradio][data-title="' + pdr + '"]').addClass('active');

                        $('#LC_ChkHemorrhage').val(ChkHemorrhage);
                        $('a[data-toggle=LC_ChkHemorrhage][data-title="' + ChkHemorrhage + '"]').addClass('active');

                        $('#LC_ChkDetachment').val(ChkDetachment);
                        $('a[data-toggle=LC_ChkDetachment][data-title="' + ChkDetachment + '"]').addClass('active');

                        $('#LC_ChkRetinopathy').val(ChkRetinopathy);
                        $('a[data-toggle=LC_ChkRetinopathy][data-title="' + ChkRetinopathy + '"]').addClass('active');
                    }

                    //cardiac
                    if (data.Table12.length > 0) {

                        $('#LC_txtecg').val(data.Table12[0].ECG);
                        $('#LC_txtecho').val(data.Table12[0].ECHO);
                        var R_tmt = (data.Table12[0].TMT_test);
                        var ecg_abnormal = (data.Table12[0].ecg_abnormal);
                        var echo_abnormal = (data.Table12[0].echo_abnormal);
                        $('#LC_txtnotes_cardiac').val(data.Table12[0].note);

                        $('#LC_txtnotes_ASD').val(data.Table12[0].ASD);
                        $('#LC_txtnotes_VSD').val(data.Table12[0].VSD);
                        $('#LC_txtnotes_value').val(data.Table12[0].C_value);
                        $('#LC_txtnotes_Ejection').val(data.Table12[0].fraction);
                        $('#LC_txtnotes_Mitral').val(data.Table12[0].mitral_value);
                        $('#LC_txtnotes_lotic').val(data.Table12[0].lotic_value);
                        $('#LC_txtnotes_Tricuspid').val(data.Table12[0].tricuspid);
                        $('#LC_txtnotes_Pulmonary').val(data.Table12[0].pulmonary);

                        $('#LC_R_tmt').val(R_tmt);
                        $('a[data-toggle=LC_R_tmt][data-title="' + R_tmt + '"]').addClass('active');

                        if (ecg_abnormal == '1') {
                            $("#LC_Chkecg").prop('checked', true);
                        }
                        if (echo_abnormal == '1') {
                            $("#LC_Selecho").prop('checked', true);
                        }
                        var txtDrugs = data.Table12[0].ON_Hypertension_drugs;
                        var txtStatin = data.Table12[0].ON_statin;
                        var txtTherapy = data.Table12[0].ON_Aspirin_Theraphy;
                        if (txtDrugs == true) {
                            txtDrugs = 1;
                        }
                        else {
                            txtDrugs = 0;
                        }
                        if (txtStatin == true) {
                            txtStatin = 1;
                        }
                        else {
                            txtStatin = 0;
                        }
                        if (txtTherapy == true) {
                            txtTherapy = 1;
                        }
                        else {
                            txtTherapy = 0;
                        }
                        $('#LC_txtDrugs').val(txtDrugs);
                        $('a[data-toggle=LC_txtDrugs][data-title="' + txtDrugs + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_txtDrugs][data-title="' + txtDrugs + '"]').addClass('active');

                        $('#LC_txtStatin').val(txtStatin);
                        $('a[data-toggle=LC_txtStatin][data-title="' + txtStatin + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_txtStatin][data-title="' + txtStatin + '"]').addClass('active');

                        $('#LC_txtTherapy').val(txtTherapy);
                        $('a[data-toggle=LC_txtTherapy][data-title="' + txtTherapy + '"]').removeClass('not-active');
                        $('a[data-toggle=LC_txtTherapy][data-title="' + txtTherapy + '"]').addClass('active');
                    }

                    //Neuropathy
                    if (data.Table13.length > 0) {
                        var chkANeuropathy = (data.Table13[0].autonomic_neuropathy);
                        $('#LC_chkANeuropathy').val(chkANeuropathy);
                        $('a[data-toggle=LC_chkANeuropathy][data-title="' + chkANeuropathy + '"]').addClass('active');
                    }
                    //Neuropathy casesheet
                    if (data.Table14.length > 0) {
                        $('#LC_txtDoppler').val(data.Table14[0].doppler_note);
                        $('#LC_txtnotes_neuropathy').val(data.Table14[0].note);
                        var PeripheralNeuropathy = data.Table14[0].peripharal_neuhropathy;
                        var ABIndex = data.Table14[0].AB_index;

                        $('#LC_per_neu').val(PeripheralNeuropathy);
                        $('a[data-toggle=LC_per_neu][data-title="' + PeripheralNeuropathy + '"]').addClass('active');

                        $('#LC_AB_index').val(ABIndex);
                        $('a[data-toggle=LC_AB_index][data-title="' + ABIndex + '"]').addClass('active');
                    }
                    if (data.Table15.length > 0) {
                        $('#LC_L_txtLMCA').val(data.Table15[0].L_LAD);
                        $('#LC_L_LMCAradio').val(data.Table15[0].L_LAD_type);
                        $('a[data-toggle=LC_L_LMCAradio][data-title="' + data.Table15[0].L_LAD_type + '"]').addClass('active');

                        $('#LC_L_txtLAD').val(data.Table15[0].L_LCX);
                        $('#LC_L_LADradio').val(data.Table15[0].L_LCX_type);
                        $('a[data-toggle=LC_L_LADradio][data-title="' + data.Table15[0].L_LCX_type + '"]').addClass('active');

                        $('#LC_L_txtlcx').val(data.Table15[0].L_RCA);
                        $('#LC_L_lcxradio').val(data.Table15[0].L_RCA_type);
                        $('a[data-toggle=LC_L_lcxradio][data-title="' + data.Table15[0].L_RCA_type + '"]').addClass('active');


                        $('#LC_R_txtlad').val(data.Table15[0].R_LAD);
                        $('#LC_R_ladradio').val(data.Table15[0].R_LAD_type);
                        $('a[data-toggle=LC_R_ladradio][data-title="' + data.Table15[0].R_LAD_type + '"]').addClass('active');

                        $('#LC_R_txtlcx').val(data.Table15[0].R_LCX);
                        $('#LC_R_lcxradio').val(data.Table15[0].R_LCX_type);
                        $('a[data-toggle=LC_R_lcxradio][data-title="' + data.Table15[0].R_LCX_type + '"]').addClass('active');

                        $('#LC_R_txtrca').val(data.Table15[0].R_RCA);
                        $('#LC_R_rcaradio').val(data.Table15[0].R_RCA_type);
                        $('a[data-toggle=LC_R_rcaradio][data-title="' + data.Table15[0].R_RCA_type + '"]').addClass('active');
                    }

                    if (data.Table16.length > 0) {
                        $('#LC_txtT3').val(data.Table16[0].Free_T3);
                        $('#LC_txtT4').val(data.Table16[0].Free_T4);
                        $('#LC_N_txtT3').val(data.Table16[0].T3);
                        $('#LC_N_txtT4').val(data.Table16[0].T4);
                        $('#LC_txtTSH').val(data.Table16[0].TSH);
                        $('#LC_txtnotes_thyroid').val(data.Table16[0].note);
                    }

                    if (data.Table17.length > 0) {

                        $('#LC_txtNotes').val(data.Table17[0].notes);
                        var chkLiver = (data.Table17[0].fatty_lives);
                        var chkGS = (data.Table17[0].GS_Calculus);
                        $('#LC_txtUNotes').val(data.Table17[0].USNotes);
                        $('#LC_ctsnotes').val(data.Table17[0].cts_notes);
                        $('#LC_chkLiver').val(chkLiver);
                        $('a[data-toggle=LC_chkLiver][data-title="' + chkLiver + '"]').addClass('active');

                        $('#LC_chkGS').val(chkGS);
                        $('a[data-toggle=LC_chkGS][data-title="' + chkGS + '"]').addClass('active');
                    }

                    if (data.Table18.length > 0) {
                        $('#LC_txtSerum_Bilirubin_Total').val(data.Table18[0].serum_bilirubin_total);
                        $('#LC_txtSerum_Bilirubin_Direct').val(data.Table18[0].serum_bilirubin_direct);
                        $('#LC_txtBilirubin_Indirect').val(data.Table18[0].bilirubin_indirect);
                        $('#LC_txtSerum_Protein_Total').val(data.Table18[0].serum_protein_total);
                        $('#LC_txtSerum_Protein_Albumin').val(data.Table18[0].serum_protein_albumin);
                        $('#LC_txtSerum_Protein_Glibulin').val(data.Table18[0].serumproteinglibulin);
                        $('#LC_txtSGOT').val(data.Table18[0].SGOT);
                        $('#LC_txtSGPT').val(data.Table18[0].SGPT);
                        $('#LC_txtSerum_Alkaline_Phosphatase').val(data.Table18[0].serum_alkaline_phosphatase);
                        $('#LC_txtGamma_Glutamyl_Transpeptidase').val(data.Table18[0].gamma_glutamyl_transpeptidase);
                        $('#LC_txtSerum_Magnesium').val(data.Table18[0].serum_magnesium);
                    }
                    $('#LC_Selbloodgroup').val(data.Table20[0].patient_blood_group);

                    if (data.Table21.length > 0) {

                        $("#btnCBC").html('Update & Next');
                        $('#txtCBCHemoglobin_1').val(data.Table21[0].hemoglobin),
                            $('#txtCBCHemoglobinUnit_1').val(data.Table21[0].hemoglobin_unit),
                            $('#txtNucleatedBloodcell_1').val(data.Table21[0].nucleated_red_blood_cells),
                            $('#txtNucleatedBloodcellPercent_1').val(data.Table21[0].nucleated_red_blood_cells_percent),
                            $('#txtHematocrit_1').val(data.Table21[0].hematocrit),
                            $('#txtPlateletCount_1').val(data.Table21[0].platelet_count),
                            $('#txtPlateletCountUnit_1').val(data.Table21[0].platelet_count_unit),
                            $('#txtTotalLeucocytesCount_1').val(data.Table21[0].total_leucocytes_count),
                            $('#txtLymphocytePercent_1').val(data.Table21[0].lymphocyte_percent),
                            $('#txtMeanCorpuscular_1').val(data.Table21[0].mean_corpuscular_hemoglobin),
                            $('#txtMeanCorpHemoConc_1').val(data.Table21[0].mean_corp_hemo_conc),
                            $('#txtMeanCorpuscularVolume_1').val(data.Table21[0].mean_corpuscular_volume),
                            $('#txtMonocytes_1').val(data.Table21[0].monocytes),
                            $('#txtNeutrophils_1').val(data.Table21[0].neutrophils),
                            $('#txtEosinophilsCount_1').val(data.Table21[0].eosinophils_absolute_count),
                            $('#txtBasophilsCount_1').val(data.Table21[0].basophils_absolute_count),
                            $('#txtLymphocyteCount_1').val(data.Table21[0].lymphocytes_absolute_count),
                            $('#txtMonocytesAbsoluteCount_1').val(data.Table21[0].monocytes_absolute_count),
                            $('#txtNeutrophilsAbsoluteCount_1').val(data.Table21[0].neutrophils_absolute_count),
                            $('#txtBasophils_1').val(data.Table21[0].basophils),
                            $('#txtEosinophils_1').val(data.Table21[0].eosinophils),
                            $('#txtImmatureGranulocytes_1').val(data.Table21[0].immature_granulocytes),
                            $('#txtImmatureGranulocytesPercent_1').val(data.Table21[0].immature_granulocytes_percent),
                            $('#txtTotalRBC_1').val(data.Table21[0].total_rbc),
                            $('#txtRedCellDistributionWidthRD_1').val(data.Table21[0].redcell_distribution_width),
                            $('#txtRedCellDistributionWidthSD_1').val(data.Table21[0].redcell_distribution_width_sd)
                    }
                    if (data.Table22.length > 0) {

                        //$("#btnUrineRoutine").html('Update & Next');
                        $('#txtSpecificGravity_1').val(data.Table22[0].specific_gravity);
                        $('#txtSpecificGravityUnit_1').val(data.Table22[0].specific_gravity_unit);
                        $('#txtUrinaryBilirubin_1').val(data.Table22[0].urinary_bilirubin),
                            $('#txtUrinaryBilirubinUnit_1').val(data.Table22[0].urinary_bilirubin_unit),
                            $('#txtUrineBlood_1').val(data.Table22[0].urine_blood),
                            $('#txtUrobilinogen_1').val(data.Table22[0].urobilinogen),
                            $('#txtUrobilinogenUnit_1').val(data.Table22[0].urobilinogen_unit),
                            $('#txtUrinaryGlucose_1').val(data.Table22[0].urinary_glucose),
                            $('#txtUrineKetone_1').val(data.Table22[0].urine_ketone),
                            $('#txtUrineKetoneUnit_1').val(data.Table22[0].urine_ketone_unit),
                            $('#txtUrinaryLeucocytes_1').val(data.Table22[0].urinary_leucocytes),
                            $('#txtNitrite_1').val(data.Table22[0].nitrite),
                            $('#txtNitriteUnit_1').val(data.Table22[0].nitrite_unit),
                            $('#txtPH_1').val(data.Table22[0].ph),
                            $('#txtUrinaryProtein_1').val(data.Table22[0].urinary_protein)
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
}



$('#txttest_name').on('input', function () {
    if ($.trim($('#txttest_name').val()).length > 0) {
        $('#txttest_name').autocomplete({
            source: function (request, response) {
                $.ajax({
                    async: true,
                    url: "/CaseStudy/Lab_Test?Lab_Test=" + $('#txttest_name').val(),
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.parameter_name, value: item.parameter_name };
                        }));
                    }
                });
            }
        });
    }
    else {

    }
});

$('#txttest_name').change(function () {
    var PaitentsTrend = {
        Dml_Indicator: "DL",
        parameter_name: $('#txttest_name').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Lab_Test_ins',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data = JSON.parse(data);
                var data = data.data;
                if (data.length > 0) {
                    $('#txtRef').html(data[0].reference_value);
                    $('#txtunits').html(data[0].unit);
                    $('#parameter_id').val(data[0].parameter_id);
                }
            }
        }
    });
});

$('a[data-toggle="tooltip"]').tooltip({
    animated: 'fade',
    placement: 'bottom',
    html: true
});

//casesheet popup end point



//unit conversion for lab test values

function LTfastingblood(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_1').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 18).toFixed(2);
        if (txtvalue > 550) {
            $('#PLC_txtBloodsugarV_1').show();
            $('#PLC_txtBloodsugarV_1').fadeOut(8000);
            $('#PLC_txtBloodsugarV_1').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_1').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 30.5) {
            $('#PLC_txtBloodsugarV_1').show();
            $('#PLC_txtBloodsugarV_1').fadeOut(8000);
            $('#PLC_txtBloodsugarV_1').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_1').val(txtvalue);
    }
}

function LPostPrandialblood(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 750) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}


function LPostPrandialblood_2(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_2').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_2').show();
            $('#PLC_txtBloodsugarV_2').fadeOut(8000);
            $('#PLC_txtBloodsugarV_2').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_2').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_2').show();
            $('#PLC_txtBloodsugarV_2').fadeOut(8000);
            $('#PLC_txtBloodsugarV_2').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_2').val(txtvalue);
    }
}


function LPostPrandialblood_3(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_3').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_3').show();
            $('#PLC_txtBloodsugarV_3').fadeOut(8000);
            $('#PLC_txtBloodsugarV_3').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_3').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_3').show();
            $('#PLC_txtBloodsugarV_3').fadeOut(8000);
            $('#PLC_txtBloodsugarV_3').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_3').val(txtvalue);
    }
}


function LPostPrandialblood_4(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_4').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_4').show();
            $('#PLC_txtBloodsugarV_4').fadeOut(8000);
            $('#PLC_txtBloodsugarV_4').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_4').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_4').show();
            $('#PLC_txtBloodsugarV_4').fadeOut(8000);
            $('#PLC_txtBloodsugarV_4').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_4').val(txtvalue);
    }
}



function LPostPrandialblood_5(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_5').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_5').show();
            $('#PLC_txtBloodsugarV_5').fadeOut(8000);
            $('#PLC_txtBloodsugarV_5').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_5').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_5').show();
            $('#PLC_txtBloodsugarV_5').fadeOut(8000);
            $('#PLC_txtBloodsugarV_5').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_5').val(txtvalue);
    }
}

function LPostPrandialblood_6(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_6').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_6').show();
            $('#PLC_txtBloodsugarV_6').fadeOut(8000);
            $('#PLC_txtBloodsugarV_6').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_6').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_6').show();
            $('#PLC_txtBloodsugarV_6').fadeOut(8000);
            $('#PLC_txtBloodsugarV_6').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_6').val(txtvalue);
    }
}


function LPostPrandialblood_7(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_7').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_7').show();
            $('#PLC_txtBloodsugarV_7').fadeOut(8000);
            $('#PLC_txtBloodsugarV_7').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_7').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_7').show();
            $('#PLC_txtBloodsugarV_7').fadeOut(8000);
            $('#PLC_txtBloodsugarV_7').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_7').val(txtvalue);
    }
}

function LPostPrandialblood_8(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtBloodsugarV_8').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 18
        if (txtvalue > 750) {
            $('#PLC_txtBloodsugarV_8').show();
            $('#PLC_txtBloodsugarV_8').fadeOut(8000);
            $('#PLC_txtBloodsugarV_8').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_8').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 18).toFixed(2);
        if (txtvalue > 41.6) {
            $('#PLC_txtBloodsugarV_8').show();
            $('#PLC_txtBloodsugarV_8').fadeOut(8000);
            $('#PLC_txtBloodsugarV_8').html('High value! Are you sure ?');
        }
        $('#LC_txtBloodsugarV_8').val(txtvalue);
    }
}
function LInsulin(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 600) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}


function LTfastingInsulin(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtfastingInsulin').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 6.945).toFixed(2);
        if (txtvalue > 600) {
            $('#PLC_txtfastingInsulin').show();
            $('#PLC_txtfastingInsulin').fadeOut(8000);
            $('#PLC_txtfastingInsulin').html('High value! Are you sure ?');
        }
        $('#LC_txtfastingInsulin').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 6.945).toFixed(2);
        if (txtvalue > 86.3) {
            $('#PLC_txtfastingInsulin').show();
            $('#PLC_txtfastingInsulin').fadeOut(8000);
            $('#PLC_txtfastingInsulin').html('High value! Are you sure ?');
        }
        $('#LC_txtfastingInsulin').val(txtvalue);
    }
}


function CPeptide(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 9) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LDL(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 300) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function TLDL(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#txtLDL').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 0.0259).toFixed(2);
        if (txtvalue > 300) {
            $('#PtxtLDL').show();
            $('#PtxtLDL').fadeOut(8000);
            $('#PtxtLDL').html('High value! Are you sure ?');
        }
        $('#txtLDL').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.0259).toFixed(2);
        if (txtvalue > 7.7) {
            $('#PtxtLDL').show();
            $('#PtxtLDL').fadeOut(8000);
            $('#PtxtLDL').html('High value! Are you sure ?');
        }
        $('#txtLDL').val(txtvalue);
    }
}



function HDL(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 300) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
    if (txtvalue < 10 && txtvalue > 0) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('The seems to be low. Are you sure ?');
    }
}


function THDL(id) {

    var txtType = $('#' + id).val();
    var txtvalue = $('#txtHDL').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 0.0259).toFixed(2);
        if (txtvalue > 300) {
            $('#PtxtHDL').show();
            $('#PtxtHDL').fadeOut(8000);
            $('#PtxtHDL').html('High value! Are you sure ?');
        }
        $('#txtHDL').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.0259).toFixed(2);
        if (txtvalue > 7.7) {
            $('#PtxtHDL').show();
            $('#PtxtHDL').fadeOut(8000);
            $('#PtxtHDL').html('High value! Are you sure ?');
        }
        $('#txtHDL').val(txtvalue);
    }
}

function LDLsum() {
    var LDL = $('#txtLDL').val();
    var HDL = $('#txtHDL').val();
    var totCholesterol = '';
    if (LDL != '' && HDL != '') {
        totCholesterol = parseFloat(LDL) + parseFloat(HDL);
    }
    $('#txtTCholesterol').val(totCholesterol);
}

function HDLRatio() {
    var HDL = $('#txtHDL').val();
    var totCholesterol = $('#txtTCholesterol').val();
    var HDLRatio = '';
    if (HDL != '' && totCholesterol != '') {
        HDLRatio = parseFloat(totCholesterol) / parseFloat(HDL);
        HDLRatio = HDLRatio.toFixed(2);
    }
    $('#txtHDLRatio').val(HDLRatio);
}

function LUrea(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 75) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}


function LTUrea(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtUrea').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 0.357
        if (txtvalue > 75) {
            $('#PtxtUrea').show();
            $('#PtxtUrea').fadeOut(8000);
            $('#PtxtUrea').html('High value! Are you sure ?');
        }
        $('#LC_txtUrea').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.357).toFixed(2);
        if (txtvalue > 210) {
            $('#PtxtUrea').show();
            $('#PtxtUrea').fadeOut(8000);
            $('#PtxtUrea').html('High value! Are you sure ?');
        }
        $('#LC_txtUrea').val(txtvalue);
    }
}


function LCreatinine(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 250) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LTCreatinine(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtCreatinine').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 88.4
        if (txtvalue > 250) {
            $('#PLC_txtCreatinine').show();
            $('#PLC_txtCreatinine').fadeOut(8000);
            $('#PLC_txtCreatinine').html('High value! Are you sure ?');
        }
        $('#LC_txtCreatinine').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 88.4).toFixed(2);
        if (txtvalue > 88.42) {
            $('#PLC_txtCreatinine').show();
            $('#PLC_txtCreatinine').fadeOut(8000);
            $('#PLC_txtCreatinine').html('High value! Are you sure ?');
        }
        $('#LC_txtCreatinine').val(txtvalue);
    }
}

function LSodium(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 400) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}
function LPotassium(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 20) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LChlorine(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 200) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LBiCarbonate(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 350) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LCalcium(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 30) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LTCalcium(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtCalcium').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 0.25
        if (txtvalue > 30) {
            $('#PLC_txtCalcium').show();
            $('#PLC_txtCalcium').fadeOut(8000);
            $('#PLC_txtCalcium').html('High value! Are you sure ?');
        }
        $('#LC_txtCalcium').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.25).toFixed(2);
        if (txtvalue > 120) {
            $('#PLC_txtCalcium').show();
            $('#PLC_txtCalcium').fadeOut(8000);
            $('#PLC_txtCalcium').html('High value! Are you sure ?');
        }
        $('#LC_txtCalcium').val(txtvalue);
    }
}

function LPhosphorus(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 35) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LTPhosphorus(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtPhosphorus').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 0.25
        if (txtvalue > 30) {
            $('#PLC_txtPhosphorus').show();
            $('#PLC_txtPhosphorus').fadeOut(8000);
            $('#PLC_txtPhosphorus').html('High value! Are you sure ?');
        }
        $('#LC_txtPhosphorus').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.25).toFixed(2);
        if (txtvalue > 120) {
            $('#PLC_txtPhosphorus').show();
            $('#PLC_txtPhosphorus').fadeOut(8000);
            $('#PLC_txtPhosphorus').html('High value! Are you sure ?');
        }
        $('#LC_txtPhosphorus').val(txtvalue);
    }
}

function LMagnesium(id) {
    var txtvalue = $('#' + id).val();
    if (txtvalue > 8) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('High value! Are you sure ?');
    }
}

function LTMagnesium(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtMagnesium').val();
    if (txtType == 1) {
        txtvalue = txtvalue * 0.411
        if (txtvalue > 8) {
            $('#PLC_txtMagnesium').show();
            $('#PLC_txtMagnesium').fadeOut(8000);
            $('#PLC_txtMagnesium').html('High value! Are you sure ?');
        }
        $('#LC_txtMagnesium').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 0.411).toFixed(2);
        if (txtvalue > 19.4) {
            $('#PLC_txtMagnesium').show();
            $('#PLC_txtMagnesium').fadeOut(8000);
            $('#PLC_txtMagnesium').html('High value! Are you sure ?');
        }
        $('#LC_txtMagnesium').val(txtvalue);
    }
}



function LTriglycerides(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtTriglycerides').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 6.945).toFixed(2);
        if (txtvalue > 300) {
            $('#PLC_txtTriglycerides').show();
            $('#PLC_txtTriglycerides').fadeOut(8000);
            $('#PLC_txtTriglycerides').html('High value! Are you sure ?');
        }
        $('#LC_txtTriglycerides').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 6.945).toFixed(2);
        if (txtvalue > 86.3) {
            $('#PLC_txtTriglycerides').show();
            $('#PLC_txtTriglycerides').fadeOut(8000);
            $('#PLC_txtTriglycerides').html('High value! Are you sure ?');
        }
        $('#LC_txtTriglycerides').val(txtvalue);
    }
}


function LTVLDL(id) {
    var txtType = $('#' + id).val();
    var txtvalue = $('#LC_txtVLDL').val();
    if (txtType == 1) {
        txtvalue = (txtvalue * 6.945).toFixed(2);
        if (txtvalue > 300) {
            $('#PtxtVLDL').show();
            $('#PtxtVLDL').fadeOut(8000);
            $('#PtxtVLDL').html('High value! Are you sure ?');
        }
        $('#LC_txtVLDL').val(txtvalue);
    }
    else {
        txtvalue = (txtvalue / 6.945).toFixed(2);
        if (txtvalue > 86.3) {
            $('#PtxtVLDL').show();
            $('#PtxtVLDL').fadeOut(8000);
            $('#PtxtVLDL').html('High value! Are you sure ?');
        }
        $('#LC_txtVLDL').val(txtvalue);
    }
}

function Lhundredonly(id) {
    var txtval = $('#' + id).val();
    if (txtval > 100) {
        $('#P_' + id).show();
        $('#P_' + id).fadeOut(8000);
        $('#P_' + id).html('High value! please check');
        $('#' + id).val('');
        $('#' + id).focus();
    }
    else {
    }
}


$('#radioBtn a').on('click', function () {
    var sel = $(this).data('title');
    var tog = $(this).data('toggle');
    $('#' + tog).prop('value', sel).trigger('change');
    $('a[data-toggle="' + tog + '"]').not('[data-title="' + sel + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="' + tog + '"][data-title="' + sel + '"]').removeClass('not-active').addClass('active');
})

$('#radioBtncolor a').on('click', function () {
    var sel = $(this).data('title');
    var tog = $(this).data('toggle');
    $('#' + tog).prop('value', sel).trigger('change');
    $('a[data-toggle="' + tog + '"]').not('[data-title="' + sel + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="' + tog + '"][data-title="' + sel + '"]').removeClass('not-active').addClass('active');
})



//Add visit attachment start

function AddVisitAttachment(patient_id, patient_first_name, slot_start_time, doctor_id, patient_phone_number, age, gender) {

    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    var gen = "";
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);

    LoadVisitAttachmentDetails();

}

$('#uploadVisitAttachmentFile').change(function () {
    attachmentUpload();
});

function attachmentUpload() {
    var uploadpath = $('#uploadVisitAttachmentFile').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#uploadVisitAttachmentFile").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/Dashboard/UploadPatientVisitFiles?patient_id=' + $('#Hdnpatient_id').val(),
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    $('#hnduploadVisitAttachmentFile').val(emp);
                });
            }
        });
    }
}



function LoadVisitAttachmentDetails() {
    var AttachmentData = {
        patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_Visit_Attachment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AttachmentData),
        success: function (data) {
            $('#tblVisitAttachment tbody').empty();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.Table.length > 0) {
                        $('#tblVisitAttachment tbody').empty();
                        var tr = '';
                        for (var i = 0; i < data.Table.length; i++) {
                            var attachmentFile = '<a href="' + $('#HFileUploadViewPath').val() + "/PatientVisitAttachment/" + data.Table[i].attachment_file_path + '" target="_blank">' + ("Attachment" + (i + 1)) + '</a>';
                            tr = tr + "<tr><td>" + (i + 1) + "</td><td>" + attachmentFile + "</td><td class='text-center'><span onclick=DeleteVisitAttachment(" + data.Table[i].patient_visit_attachement_id + ");><i class='fa fa-trash delete btn deleteicon-btn   btn-sm'></i></span></td><tr>"
                        }
                        $('#tblVisitAttachment tbody').append(tr);
                    }


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

$('#btnUploadVisitAttachment').click(function () {
    if ($('#hnduploadVisitAttachmentFile').val() == "" || $('#hnduploadVisitAttachmentFile').val() == null) {
        $('#PUploadVisitAttachment').show();
        $('#PUploadVisitAttachment').fadeOut(8000);
        $('#PUploadVisitAttachment').html('Choose document');
        return false;
    }
    AttachmentVisitReport();
});

function AttachmentVisitReport() {
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: '15'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        $('#VisitReportID').val(VisitReportID);
                        InsertVisitAttachment();
                    }


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

function InsertVisitAttachment() {
    var AttachmentData = {
        patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        Dml_Indicator: 'I',
        visit_report_id: $('#VisitReportID').val(),
        attachment_file_path: $('#hnduploadVisitAttachmentFile').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_Visit_Attachment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AttachmentData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    $('#hnduploadVisitAttachmentFile').val('');
                    $('#uploadVisitAttachmentFile').val('');
                    LoadVisitAttachmentDetails();


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

function DeleteVisitAttachment(patient_visit_attachement_id) {
    var AttachmentData = {
        Dml_Indicator: 'D',
        patient_visit_attachement_id: patient_visit_attachement_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_Visit_Attachment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AttachmentData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg = "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    LoadVisitAttachmentDetails();


                }
            }
            else {
                console.log(data);
            }
        }
    });
}
//Add visit attachment end

function reschedule(patient, slotId, PName, branch_id, type) {

    console.log(patient, slotId, PName);
    if (confirm("Are you sure want to reschedule the appointment?")) {
        window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient + "&PName=" + PName + "&slotId=" + slotId + "&BId=" + branch_id + "&r_type=" + type;
    }
    else {

    }

}



$('#datepickern').change(function () {
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    output = output.split('/');
    output = output[1] + '/' + output[0] + '/' + output[2];
    var appointment_date = $('#datepickern').val();
    appointment_date = appointment_date.split('/');
    appointment_date = appointment_date[1] + '/' + appointment_date[0] + '/' + appointment_date[2];
    var dateFirst = new Date(output);
    var dateSecond = new Date(appointment_date);
    var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    $('#days').val(diffDays);
});



function Prescription_click(patient_id, patient_first_name, patient_phone_number, photoSrc, slot_start_time, doctor_id, doctor_designation, age, gender,patient_branch) {
    debugger;
    LoadCasesheetConfiguration(doctor_id);
    loadMedicineType();
    loadwhentoeat();
    //$('#da-load-quickentry').show();
    //$('.modlarge').addClass('modal-cs-prescri');
    var gen = "";
    $('.modlarge').addClass('da-load-p-prep');
   // $('#tbl-medicine tbody').empty();
    $('#tbl-medicine1').empty();
    $('#tbl-scan_1 tbody').empty();
    $('#labtemplatelist').empty();
    $('#templatelist').empty();
    $('#Copy_prescriptionList').empty();

    $('#txtComplaints_1').val('');
    $('#txtnotes_1').val('');
    $('#txtdiagnosis').val('');
    $('#txtprodcedure').val('');
    $('#txtAdvice').val('');
    $('#txtCounselling').val('');
    $('#datepickern').val('');
    $('#txt_visit_instruction').val('');
    $('#txtXrayFindings').val('');

    $('#txtinvetig').val('');
    $('#txtReviewNotes').val('');
    $('#txtlabfinding').val('');
    $('#divtxtxrayfind').val('');
    $('#txtobserv').val('');
    if (gender == 1) {
        gen = "Male";
    }
    else if (gender == 2) {
        gen = "Female";
    }
    else {
        gen = "others";
    }
    $('.Age').html(" Age:" + age + "|Gender:" + gen);

    $('#divtxtComplaints_1 ul').remove();
    $('#divtxtdiagnosis ul').remove();
    $('#divtxtAdvice ul').remove();
    $('#divtxtCounselling ul').remove();
    $('#divtxtlabfinding ul').remove();
    $('#divtxtxrayfind ul').remove();
    $('#divtxtInvestigation ul').remove();
    $('#divtxtInstruction ul').remove();
    $('#divtxtProcedure ul').remove();
    $('#divtxtNotes ul').remove();
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#Hdnappointment_date').val(slot_start_time);
    $('#pop_doctor_id').val(doctor_id);
    $('#PatBranch_id').val(patient_branch);

    var VisitreportId = {
        Patient_id: patient_id,
        slotTime: slot_start_time,
        doctor_id: doctor_id,
        Dml_Indicator: '7'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id)
                        $('#VisitReportID').val(VisitReportID);

                        var labval = {
                            Dml_Indicator: 'S',
                            patient_id: patient_id,
                            slot_time: slot_start_time,
                            Doctor_id: doctor_id
                        }

                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/caseStudy/Quick_Prescription',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(labval),
                            success: function (data) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    var data = data.data;
                                    if (jQuery.isEmptyObject((data))) {
                                    }
                                    else {

                                        console.log(data);
                                        if (data.Table.length > 0) {
                                            if ($('#txtComplaints_1').hasClass('tag-editor-hidden-src')) {
                                                var complaintsVal = [];
                                                for (var i = 0; i < data.Table.length; i++) {
                                                    complaintsVal.push(data.Table[i].complaints);
                                                }


                                                $('#txtComplaints_1').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: complaintsVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb,

                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val, '1');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }


                                        if (data.Table1.length > 0) {
                                            if ($('#txtdiagnosis').hasClass('tag-editor-hidden-src')) {

                                                var diagnosisVal = [];
                                                var diag_id = [];
                                                for (var i = 0; i < data.Table1.length; i++) {

                                                    diagnosisVal.push(data.Table1[i].diagnosis);
                                                    diag_id.push(data.Table1[i].diagnosis_id);
                                                }

                                                $('#txtdiagnosis').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    maxLength: 250,
                                                    forceLowercase: false,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: diagnosisVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });
                                                var tagDiagIdMap = {};

                                                console.log('diagnosisVal:', diagnosisVal);
                                                console.log('diag_id:', diag_id);

                                                for (var i = 0; i < diagnosisVal.length; i++) {
                                                    // Convert diagnosisVal to lowercase (or uppercase) for case-insensitive mapping
                                                    tagDiagIdMap[diagnosisVal[i].toLowerCase()] = diag_id[i];
                                                    console.log('Mapping:', diagnosisVal[i], '->', diag_id[i]);
                                                }
                                                var previousTags = [];

                                                function onChangecb(field, editor, tags) {
                                                    // Check if any new tags have been added
                                                    var newTags = tags.filter(tag => previousTags.indexOf(tag) === -1);

                                                    // Assuming newTags is an array of newly added tag values
                                                    for (var j = 0; j < newTags.length; j++) {
                                                        var tagValue = newTags[j];

                                                        // Access the corresponding diag_id using the mapping object
                                                        var correspondingDiagId = tagDiagIdMap[tagValue.toLowerCase()];

                                                        // Now you can use correspondingDiagId as needed
                                                        $('#hnddiag_id').val(correspondingDiagId);
                                                        diag_temp(correspondingDiagId);
                                                    }

                                                    // Update previousTags with the current tags
                                                    previousTags = tags.slice();
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    diagnosis_insert(val);
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        if (data.Table2.length > 0) {
                                            var dia = '', pro = '';
                                            if (data.Table2[0].next_appointment_date != null || data.Table2[0].next_appointment_date != "") {
                                                $('#datepickern').val(data.Table2[0].next_appointment_date);
                                            }
                                            for (var i = 0; i < data.Table2.length; i++) {
                                                var diagnosis = '', treatment_procedure = '';
                                                if (data.Table2[i].diagnosis != '' && data.Table2[i].diagnosis != null) {
                                                    diagnosis = data.Table2[i].diagnosis;
                                                    dia = dia + '<a href="JavaScript:Void(0);" onclick=\'diagonsisliston(\"' + diagnosis + '\")\'><div class="pull-left">' + diagnosis + ' (' + data.Table2[i].created_on + ')</div><div class="clearfix"></div></a>';
                                                }
                                                if (data.Table2[i].treatment_procedure != '' && data.Table2[i].treatment_procedure != null) {
                                                    treatment_procedure = data.Table2[i].treatment_procedure;
                                                    pro = pro + '<a href="JavaScript:Void(0);" onclick=\'treatment_procedureon(\"' + treatment_procedure + '\")\'><div class="pull-left">' + treatment_procedure + ' (' + data.Table2[i].created_on + ')</div><div class="clearfix"></div></a>';
                                                }
                                            }
                                            $('#Diagonsislist').html(dia);
                                            $('#Procedurelist').html(pro);
                                        }
                                        //if (data.Table3.length > 0) {
                                        //    var trlist = '';
                                        //    $('#Copy_prescriptionList').empty();
                                        //    for (var i = 0; i < data.Table3.length; i++) {
                                        //        trlist = trlist + '<a href="javascript:void(0);" class="ClsCopy_prescription" onclick=Copy_prescription_id("' + data.Table3[i].visit_report_id + '")><div class="pull-left"> ' + data.Table3[i].visit_date + ' | <span class="badge bg-red pull-right">' + data.Table3[i].medicine_count + '</span></div><div class="clearfix"></div></a>';

                                        //    }
                                        //    console.log(trlist);
                                        //    $('#Copy_prescriptionList').html(trlist);
                                        //}
                                        if (data.Table4.length > 0) {
                                            var tr = '';
                                            $('#templatelist').empty();
                                            for (var i = 0; i < data.Table4.length; i++) {
                                                tr = tr + '<a href="javascript:void(0)" class="Clscopytemplate" onclick=copytemplate(' + data.Table4[i].medicine_template_id + ');><div class="pull-left">' + data.Table4[i].template_name + '</div><div class="clearfix"></div></a>';
                                            }
                                            $('#templatelist').html(tr);
                                        }

                                        //if (data.Table5.length > 0) {
                                        //    var medicine = '';
                                        //    $('#SelMedicineType').empty();
                                        //    for (var i = 0; i < data.Table5.length; i++) {
                                        //        medicine = medicine + '<option value="' + data.Table5[i].medicine_type_id + '">' + data.Table5[i].medicine_type + '</option>';
                                        //    }
                                        //    $('#SelMedicineType').append(medicine);
                                        //}

                                        if (data.Table6.length > 0) {
                                            var trs = '';
                                            $('#hndwenttoeat').empty();
                                            for (var i = 0; i < data.Table6.length; i++) {
                                                trs = trs + '<option value="' + data.Table6[i].when_to_eat_id + '">' + data.Table6[i].when_to_eat_value + '</option>';
                                            }
                                            $('#hndwenttoeat').html(trs);
                                        }

                                        if (data.Table7.length > 0) {
                                            var ltr = '';
                                            for (var i = 0; i < data.Table7.length; i++) {
                                                ltr = ltr + '<a href="javascript:void(0)" onclick=labtemplatelist(' + data.Table7[i].lab_template_id + ');><div class="pull-left">' + data.Table7[i].template_name + '</div><div class="clearfix"></div></a>';
                                            }
                                            $('#labtemplatelist').html(ltr);
                                        }

                                        if (data.Table8.length > 0) {
                                            var labty = '';
                                            $('#labtype_1').empty();
                                            for (var i = 0; i < data.Table8.length; i++) {
                                                labty = labty + '<option value="' + data.Table8[i].lab_type_id + '">' + data.Table8[i].lab_type_name + '</option>';
                                            }
                                            $('#labtype_1').html(labty);
                                        }

                                        //autocomplete all fields
                                        //notes
                                        if (data.Table9.length > 0) {
                                            if ($('#txtnotes_1').hasClass('tag-editor-hidden-src')) {
                                                var notesVal = [];

                                                for (var i = 0; i < data.Table9.length; i++) {
                                                    notesVal.push(data.Table9[i].notes);

                                                }
                                                console.log(notesVal);
                                                $('#txtnotes_1').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: notesVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '2');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //instruction
                                        if (data.Table10.length > 0) {
                                            if ($('#txt_visit_instruction').hasClass('tag-editor-hidden-src')) {
                                                var instructionVal = [];

                                                for (var i = 0; i < data.Table10.length; i++) {
                                                    instructionVal.push(data.Table10[i].instruction);

                                                }
                                                console.log(instructionVal);
                                                $('#txt_visit_instruction').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    maxLength: 250,
                                                    forceLowercase: false,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: instructionVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '3');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }

                                        //investigation
                                        if (data.Table11.length > 0) {
                                            if ($('#txtXrayFindings').hasClass('tag-editor-hidden-src')) {
                                                var investigationVal = [];

                                                for (var i = 0; i < data.Table11.length; i++) {
                                                    investigationVal.push(data.Table11[i].investigation);

                                                }
                                                console.log(investigationVal);
                                                $('#txtXrayFindings').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: investigationVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '4');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }

                                        //advice
                                        if (data.Table12.length > 0) {
                                            if ($('#txtAdvice').hasClass('tag-editor-hidden-src')) {
                                                var adviceVal = [];

                                                for (var i = 0; i < data.Table12.length; i++) {
                                                    adviceVal.push(data.Table12[i].advice);

                                                }
                                                console.log(adviceVal);
                                                $('#txtAdvice').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    maxLength: 250,
                                                    forceLowercase: false,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: adviceVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '5');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }

                                        //procedures
                                        if (data.Table13.length > 0) {
                                            if ($('#txtprodcedure').hasClass('tag-editor-hidden-src')) {
                                                var proceduresVal = [];

                                                for (var i = 0; i < data.Table13.length; i++) {
                                                    proceduresVal.push(data.Table13[i].procedures);

                                                }
                                                console.log(proceduresVal);
                                                $('#txtprodcedure').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: proceduresVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '6');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }

                                        //couselling
                                        if (data.Table14.length > 0) {
                                            if ($('#txtCounselling').hasClass('tag-editor-hidden-src')) {
                                                var cousellingVal = [];

                                                for (var i = 0; i < data.Table14.length; i++) {
                                                    cousellingVal.push(data.Table14[i].couselling);

                                                }
                                                console.log(cousellingVal);
                                                $('#txtCounselling').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    maxLength: 250,
                                                    forceLowercase: false,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: cousellingVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '7');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        if (data.Table15.length > 0) {
                                            $('#phy_data_flag').val(data.Table15[0].data_flag);
                                        }
                                        else {
                                            $('#phy_data_flag').val('0');
                                        }

                                        //lab finding
                                        if (data.Table16.length > 0) {
                                            if ($('#txtlabfinding').hasClass('tag-editor-hidden-src')) {
                                                var labfinVal = [];

                                                for (var i = 0; i < data.Table16.length; i++) {
                                                    labfinVal.push(data.Table16[i].lab_finding);

                                                }
                                                $('#txtlabfinding').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: labfinVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '8');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtlabfinding').hasClass('tag-editor-hidden-src')) {
                                                $('#txtlabfinding').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });
                                                function onChangecb(field, editor, tags) {
                                                }
                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '8');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }


                                        if (data.Table17.length > 0) {
                                            if ($('#txtxrayfind').hasClass('tag-editor-hidden-src')) {
                                                var xrayfindVal = [];

                                                for (var i = 0; i < data.Table17.length; i++) {
                                                    xrayfindVal.push(data.Table17[i].xray_finding);

                                                }
                                                $('#txtxrayfind').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: xrayfindVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '9');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtxrayfind').hasClass('tag-editor-hidden-src')) {
                                                $('#txtxrayfind').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '9');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }


                                        //mri finding
                                        if (data.Table18.length > 0) {
                                            if ($('#txtmrifinding').hasClass('tag-editor-hidden-src')) {
                                                var mrifinVal = [];

                                                for (var i = 0; i < data.Table18.length; i++) {
                                                    mrifinVal.push(data.Table18[i].mri_finding);

                                                }
                                                $('#txtmrifinding').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: mrifinVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '10');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtmrifinding').hasClass('tag-editor-hidden-src')) {
                                                $('#txtmrifinding').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });
                                                function onChangecb(field, editor, tags) {
                                                }
                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '10');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        if (data.Table19.length > 0) {
                                            if ($('#txtobserv').hasClass('tag-editor-hidden-src')) {
                                                var observationVal = [];

                                                for (var i = 0; i < data.Table19.length; i++) {
                                                    observationVal.push(data.Table19[i].observation);

                                                }
                                                console.log(observationVal);
                                                $('#txtobserv').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: observationVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '11');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtobserv').hasClass('tag-editor-hidden-src')) {

                                                $('#txtobserv').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '11');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //investigation
                                        if (data.Table20.length > 0) {
                                            if ($('#txtinvetig').hasClass('tag-editor-hidden-src')) {
                                                var investigationVal = [];

                                                for (var i = 0; i < data.Table20.length; i++) {
                                                    investigationVal.push(data.Table20[i].invest);

                                                }
                                                console.log(investigationVal);
                                                $('#txtinvetig').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: investigationVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '12');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtinvetig').hasClass('tag-editor-hidden-src')) {

                                                $('#txtinvetig').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '12');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //review notes
                                        if (data.Table21.length > 0) {
                                            if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                                                debugger;
                                                var reviewnotesVal = [];

                                                for (var i = 0; i < data.Table21.length; i++) {
                                                    reviewnotesVal.push(data.Table21[i].reviewnotes);

                                                }
                                                console.log(reviewnotesVal);
                                                $('#txtReviewNotes').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: reviewnotesVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '13');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                                                debugger;
                                                $('#txtReviewNotes').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '13');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //past significant adverse events

                                        if (data.Table22.length > 0) {
                                            if ($('#txtpastadverseevents').hasClass('tag-editor-hidden-src')) {
                                                var significant_adverseVal = [];

                                                for (var i = 0; i < data.Table22.length; i++) {
                                                    significant_adverseVal.push(data.Table22[i].past_adverse_event);

                                                }
                                                console.log(significant_adverseVal);
                                                $('#txtpastadverseevents').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: significant_adverseVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '14');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtpastadverseevents').hasClass('tag-editor-hidden-src')) {

                                                $('#txtpastadverseevents').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '14');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //general examination

                                        if (data.Table23.length > 0) {
                                            if ($('#txtgeneralexamination').hasClass('tag-editor-hidden-src')) {
                                                var general_examVal = [];

                                                for (var i = 0; i < data.Table23.length; i++) {
                                                    general_examVal.push(data.Table23[i].general_examination);

                                                }
                                                console.log(general_examVal);
                                                $('#txtgeneralexamination').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: general_examVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '15');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtgeneralexamination').hasClass('tag-editor-hidden-src')) {

                                                $('#txtgeneralexamination').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '15');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }


                                        //local examination

                                        if (data.Table24.length > 0) {
                                            if ($('#txtlocalexamination').hasClass('tag-editor-hidden-src')) {
                                                var local_examVal = [];

                                                for (var i = 0; i < data.Table24.length; i++) {
                                                    local_examVal.push(data.Table24[i].local_examination);

                                                }
                                                console.log(local_examVal);
                                                $('#txtlocalexamination').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: local_examVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '16');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtlocalexamination').hasClass('tag-editor-hidden-src')) {

                                                $('#txtlocalexamination').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '16');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }

                                        //abdomen girth

                                        if (data.Table25.length > 0) {
                                            if ($('#txtabdomengirth').hasClass('tag-editor-hidden-src')) {
                                                var abdomenVal = [];

                                                for (var i = 0; i < data.Table25.length; i++) {
                                                    abdomenVal.push(data.Table25[i].abdomen_girth);

                                                }
                                                console.log(abdomenVal);
                                                $('#txtabdomengirth').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: abdomenVal
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '17');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }

                                        }
                                        else {
                                            if ($('#txtabdomengirth').hasClass('tag-editor-hidden-src')) {

                                                $('#txtabdomengirth').tagEditor({
                                                    delimiter: ',',
                                                    initialTags: [],
                                                    placeholder: '',
                                                    forceLowercase: false,
                                                    maxLength: 250,
                                                    autocomplete: {
                                                        delay: 0,
                                                        position: {
                                                            collision: 'flip'
                                                        },
                                                        source: []
                                                    },
                                                    clickDelete: false,
                                                    beforeTagSave: beforeTagSavecb,
                                                    beforeTagDelete: beforeTagDeletecb,
                                                    onChange: onChangecb
                                                });

                                                function onChangecb(field, editor, tags) {
                                                }

                                                function beforeTagSavecb(field, editor, tags, tag, val) {
                                                    complaints_master_insert(val.toUpperCase(), '17');
                                                }

                                                function beforeTagDeletecb(field, editor, tags, val) {
                                                    return true;
                                                }
                                            }
                                        }
                                        if (data.Table26.length > 0) {
                                            $('#medicinefrequency').empty();
                                            $('#medicinefrequency_edit').empty();
                                            trs = '';
                                            var defaultoption = '<option value="0">--select--</option>';
                                            frequencyarray = data.Table26;
                                            //loadfrequencytype(frequencyarray);
                                            for (var i = 0; i < data.Table26.length; i++) {
                                                trs = trs + '<option value="' + data.Table26[i].frequency_master_id + '">' + data.Table26[i].frequency_name + '</option>';
                                            }
                                            $('#medicinefrequency').append(defaultoption + trs);
                                            // $('.medicinefrequency').append(defaultoption + trs);
                                            $('#medicinefrequency_edit').append(defaultoption + trs);
                                        }
                                    }
                                    loadmedicineprescription(VisitReportID)
                                    select_prescription_list(VisitReportID);

                                    $('.modlarge').removeClass('da-load-p-prep');
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });


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

function LoadCasesheetConfiguration(doctor_id) {
    var casesheetConfig = {
        doctor_id: doctor_id,
        Dml_Indicator: 'DS',
        casesheet_type_id: $('#HCasesheetType').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Casesheet_Configuration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(casesheetConfig),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {


                    console.log(data);

                    if (data != null) {
                        if (data.Table.length > 0) {
                            for (var i = 0; i < data.Table.length; i++) {
                                $('#' + data.Table[i].field_name).show();
                                $('#' + data.Table[i].label_field_name).html(data.Table[i].label_name);

                                $('.' + data.Table[i].field_name).show();
                                $('.' + data.Table[i].label_field_name).html(data.Table[i].label_name);

                            }
                        }

                        if (data.Table1.length > 0) {
                            for (var j = 0; j < data.Table1.length; j++) {
                                $('#' + data.Table1[j].field_name).show();
                                $('#Wdiv' + data.Table1[j].field_name).show();
                                $('.Wdiv' + data.Table1[j].field_name).show();
                                $('.WdivLC_' + data.Table1[j].field_name).show();


                                if (data.Table1[j].is_enable == false || data.Table1[j].is_enable == "0") {
                                    $('#' + data.Table1[j].field_name).attr('disabled', true);
                                    $('#div' + data.Table1[j].field_name).attr('disabled', true);

                                    $('.' + data.Table1[j].field_name).attr('disabled', true);
                                    $('.div' + data.Table1[j].field_name).attr('disabled', true);

                                    $('a[data-toggle=' + data.Table1[j].field_name + ']').attr("disabled", true);
                                    $('a[data-toggle=' + data.Table1[j].field_name + ']').css({ "pointer-events": "none" });
                                    $('a[data-toggle=LC_' + data.Table1[j].field_name + ']').attr("disabled", true);
                                    $('a[data-toggle=LC_' + data.Table1[j].field_name + ']').css({ "pointer-events": "none" });

                                    $('.r_' + data.Table1[j].field_name).attr("disabled", true);
                                    $('.r_' + data.Table1[j].field_name).css({ "pointer-events": "none" });

                                    $('.Unit' + data.Table1[j].field_name).attr('disabled', true);
                                    $('#LC_' + data.Table1[j].field_name).attr('disabled', true);
                                    $('#' + data.Table1[j].field_name + '_1').attr('disabled', true);
                                }
                                else {
                                    $('#' + data.Table1[j].field_name).attr('disabled', false);
                                    $('#div' + data.Table1[j].field_name).attr('disabled', false);
                                    $('.' + data.Table1[j].field_name).attr('disabled', false);
                                    $('.div' + data.Table1[j].field_name).attr('disabled', false);

                                    $('a[data-toggle=' + data.Table1[j].field_name + ']').attr("disabled", false);
                                    $('a[data-toggle=' + data.Table1[j].field_name + ']').css({ "pointer-events": "auto" });
                                    $('a[data-toggle=LC_' + data.Table1[j].field_name + ']').attr("disabled", false);
                                    $('a[data-toggle=LC_' + data.Table1[j].field_name + ']').css({ "pointer-events": "auto" });

                                    $('.r_' + data.Table1[j].field_name).attr("disabled", false);
                                    $('.r_' + data.Table1[j].field_name).css({ "pointer-events": "auto" });

                                    $('.Unit' + data.Table1[j].field_name).attr('disabled', false);
                                    $('#LC_' + data.Table1[j].field_name).attr('disabled', false);
                                    $('#' + data.Table1[j].field_name + '_1').attr('disabled', false);
                                }

                                $('#' + data.Table1[j].label_field_name).html(data.Table1[j].label);
                                $('.' + data.Table1[j].label_field_name).html(data.Table1[j].label);


                                if (data.Table1[j].section_field_name == "divObservation") {
                                    if (data.Table1[j].is_tag_editor == true || data.Table1[j].is_tag_editor == "1") {
                                        $('#' + data.Table1[j].field_name).addClass("tag-editor-hidden-src");
                                        $('.' + data.Table1[j].field_name).addClass("tag-editor-hidden-src");
                                      //  debugger;
                                        if (data.Table1[j].is_enable == false || data.Table1[j].is_enable == "0") {
                                            $('#div' + data.Table1[j].field_name).attr("disabled", true);
                                            $('#div' + data.Table1[j].field_name).css({ "pointer-events": "none" });
                                        }
                                        else {
                                            $('#div' + data.Table1[j].field_name).attr("disabled", false);
                                            $('#div' + data.Table1[j].field_name).css({ "pointer-events": "auto" });
                                        }

                                    }
                                    else {
                                        $('#' + data.Table1[j].field_name).removeClass("tag-editor-hidden-src");
                                        $('.' + data.Table1[j].field_name).removeClass("tag-editor-hidden-src");
                                    }


                                }

                            }
                        }

                        // hide over all tab if all sections are invisible
                        if (data.Table2.length > 0) {
                            for (var k = 0; k < data.Table2.length; k++) {
                                if (parseInt(data.Table2[k].totalsections) == parseInt(data.Table2[k].totalinvisible)) {
                                    $('.popTab_' + data.Table2[k].casesheet_module_id).hide();
                                }
                            }
                        }

                        if (data.Table.length <= 0 && data.Table1.length <= 0) {
                            toastr.warning('Kindly set the Casesheet Configuration');
                        }
                    }
                    else {
                        toastr.warning('Kindly set the Casesheet Configuration');

                    }


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

function select_prescription_list(VisitReportID) {
    debugger
    var VisitreportId = {
        Dml_Indicator: 'SS',
        visit_report_id: VisitReportID,
        is_pharmacy: $('#His_pharmacy').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Quick_Prescription',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {

            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if (data.Table.length > 0) {
                        if (data.Table.length > 0) {
                            $('#tbl-medicine').empty();
                            var a = '', dosage = '', medicineUnit = '', medval = '';
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].medicine_dosage == null || data.Table[i].medicine_dosage == '') {
                                    dosage = '';
                                }
                                else {
                                    dosage = data.Table[i].medicine_dosage + medicineUnit;
                                }
                                var instructions = '';
                                if (data.Table[i].instructions == '' || data.Table[i].instructions == null) {
                                    instructions = '';
                                }
                                else {
                                    instructions = data.Table[i].instructions;
                                }
                                var Mtypeunit = '', Atypeunit = '', Ntypeunit = '';
                                var generic_name = '';
                                if (data.Table[i].generic_name == '' || data.Table[i].generic_name == null) {
                                    generic_name = '';
                                }
                                else {
                                    generic_name = '<span style=font-size:11px;><i>(' + data.Table[i].generic_name + ')</i></span>';
                                }
                                var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                                if (data.Table[i].morning != '' && data.Table[i].morning != null) {

                                    morning = data.Table[i].morning.split('.');

                                    if (morning.length > 1) {
                                        if (morning[1] == 5 || morning[1] == 50 || morning[1] == 05) {
                                            //morning = morning[0] + '<span style="\00BD">&#189;</span>';
                                            if (morning[0] == 0) {
                                                morning = '<sup>1</sup>&frasl;<sub>2</sub>';
                                            }
                                            else {
                                                morning = morning[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                            }
                                        }
                                        else if (morning[1] == 25) {
                                            if (morning[0] == 0) {
                                                morning = '<sup>1</sup>&frasl;<sub>4</sub>';
                                            }
                                            else {
                                                morning = morning[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                            }
                                        }
                                        else if (morning[1] == 75) {
                                            if (morning[0] == 0) {
                                                morning = '<sup>3</sup>&frasl;<sub>4</sub>';
                                            }
                                            else {
                                                morning = morning[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                            }
                                        }
                                        else {
                                            morning = data.Table[i].morning;
                                        }
                                    }
                                    else { morning = data.Table[i].morning; }
                                }

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

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

                                }
                                else {
                                    session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;

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

                                medval = medval + "<tr id='" + data.Table[i].medicine_prescription_id + "'><td>" + data.Table[i].medicine_type + "</td><td style='text-transform: capitalize;'>" + color + data.Table[i].medicine_name.toUpperCase() + generic_name + "</td><td>" + data.Table[i].when_to_eat_value + "</td><td>" + days_to_take + "</td><td>" + instructions + "</td><td>" + session + "</td><td><button class='edit btn btn-primary btn-sm btn-add mr-15' onclick='medicineedit(\"" + data.Table[i].medicine_prescription_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-sm btn-add' onclick='deleteMedi(\"" + data.Table[i].medicine_prescription_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
                            };
                            $('#tbl-medicine').append(medval);

                        }

                    }

                    if (data.Table1.length > 0) {
                        $('#tbl-scan_1 > tbody').empty();
                        for (var i = 0; i < data.Table1.length; i++) {
                            var value = "<tr><td>" + data.Table1[i].lab_prescription + "</td><td>" + data.Table1[i].lab_type_name + "</td><td>" + data.Table1[i].suggested_date + "</td><td><button class='btn btn-primary addicon-btn  btn-sm mr-20' onclick='scanedit_1(\"" + data.Table1[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm btn-danger' onclick='deleteRow_1(\"" + (data.Table1[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
                            $('#tbl-scan_1 > tbody').append(value);
                        }
                    }

                    if (data.Table2.length > 0) {
                        $('#datepickern').val(data.Table2[0].next_appointment_date);

                        var procedure = data.Table2[0].treatment_procedure;
                        if ($('#txtprodcedure').hasClass('tag-editor-hidden-src')) {
                            if (procedure == '' || procedure == null) {
                                $('#divtxtProcedure > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var proceduresplit = procedure.split(',');
                                var tr = [];
                                if (proceduresplit.length > 0) {
                                    for (var i = 0; i < proceduresplit.length; i++) {
                                        tr.push(proceduresplit[i]);
                                    }
                                    $('#txtprodcedure').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtProcedure > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtprodcedure').val(procedure);
                        }

                        var instruction = data.Table2[0].instruction;
                        if ($('#txt_visit_instruction').hasClass('tag-editor-hidden-src')) {
                            if (instruction == '' || instruction == null) {
                                $('#divtxtInstruction > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var instructionsplit = instruction.split(',');
                                var tr = [];
                                if (instructionsplit.length > 0) {
                                    for (var i = 0; i < instructionsplit.length; i++) {
                                        tr.push(instructionsplit[i]);
                                    }
                                    $('#txt_visit_instruction').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtInstruction > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txt_visit_instruction').val(instruction);
                        }

                        var xrayfinds = data.Table2[0].xray_findings;
                        if ($('#txtXrayFindings').hasClass('tag-editor-hidden-src')) {
                            if (xrayfinds == '' || xrayfinds == null) {
                                $('#divtxtXrayFindings > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var xrayfindsplit = xrayfinds.split(',');
                                var tr = [];
                                if (xrayfindsplit.length > 0) {
                                    for (var i = 0; i < xrayfindsplit.length; i++) {
                                        tr.push(xrayfindsplit[i]);
                                    }
                                    $('#txtXrayFindings').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtXrayFindings > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtXrayFindings').val(xrayfinds);
                        }


                        var advice = data.Table2[0].advice;
                        if ($('#txtAdvice').hasClass('tag-editor-hidden-src')) {
                            if (advice == '' || advice == null) {
                                $('#divtxtAdvice > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var advicesplit = advice.split(',');
                                var tr = [];
                                if (advicesplit.length > 0) {
                                    for (var i = 0; i < advicesplit.length; i++) {
                                        tr.push(advicesplit[i]);
                                    }
                                    $('#txtAdvice').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtAdvice > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtAdvice').val(advice);
                        }

                        $('#m_vas').val(data.Table2[0].vas);
                        var counselling = data.Table2[0].counselling;
                        if ($('#txtCounselling').hasClass('tag-editor-hidden-src')) {
                            if (counselling == '' || counselling == null) {
                                $('#divtxtCounselling > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var counsellingsplit = counselling.split(',');
                                var tr = [];
                                if (counsellingsplit.length > 0) {
                                    for (var i = 0; i < counsellingsplit.length; i++) {
                                        tr.push(counsellingsplit[i]);
                                    }
                                    $('#txtCounselling').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtCounselling > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtCounselling').val(counselling);
                        }

                        var lab_findings = data.Table2[0].lab_findings;
                        if ($('#txtlabfinding').hasClass('tag-editor-hidden-src')) {
                            if (lab_findings == '' || lab_findings == null) {
                                $('#divtxtlabfinding > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var lab_findingssplit = lab_findings.split(',');
                                var tr = [];
                                if (lab_findingssplit.length > 0) {
                                    for (var i = 0; i < lab_findingssplit.length; i++) {
                                        tr.push(lab_findingssplit[i]);
                                    }
                                    $('#txtlabfinding').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtlabfinding > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtlabfinding').val(lab_findings);
                        }


                        var xray_findings = data.Table2[0].xray_findings_new;
                        if ($('#txtxrayfind').hasClass('tag-editor-hidden-src')) {
                            if (xray_findings == '' || xray_findings == null) {
                                $('#divtxtxrayfind > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var xray_findingssplit = xray_findings.split(',');
                                var tr = [];
                                if (xray_findingssplit.length > 0) {
                                    for (var i = 0; i < xray_findingssplit.length; i++) {
                                        tr.push(xray_findingssplit[i]);
                                    }
                                    $('#txtxrayfind').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtxrayfind > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtxrayfind').val(xray_findings);
                        }
                        //investigation                       
                        var investigVal = data.Table2[0].investigation;
                        if ($('#txtinvetig').hasClass('tag-editor-hidden-src')) {
                            if (investigVal == '' || investigVal == null) {
                                $('#divtxtinvetig > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var investigValsplit = investigVal.split(',');
                                var tr = [];
                                if (investigValsplit.length > 0) {
                                    for (var i = 0; i < investigValsplit.length; i++) {
                                        tr.push(investigValsplit[i]);
                                    }
                                    $('#txtinvetig').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtinvetig > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtinvetig').val(investigVal);
                        }

                        //$('#txtobserv').val(data.Table2[0].observation);

                        //observation                       
                        var observVal = data.Table2[0].observation;
                        if ($('#txtobserv').hasClass('tag-editor-hidden-src')) {
                            if (observVal == '' || observVal == null) {
                                $('#divtxtobserv > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var observValsplit = observVal.split(',');
                                var tr = [];
                                if (observValsplit.length > 0) {
                                    for (var i = 0; i < observValsplit.length; i++) {
                                        tr.push(observValsplit[i]);
                                    }
                                    $('#txtobserv').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtobserv > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtobserv').val(observVal);
                        }

                        //$('#txtReviewNotes').val(data.Table2[0].review_notes);

                        //review notes
                        var reviewNotes = data.Table2[0].review_notes;
                        if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                            debugger;
                            if (reviewNotes == '' || reviewNotes == null) {
                                $('#divtxtReviewNotes > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var reviewNotessplit = reviewNotes.split(',');
                                var tr = [];
                                if (reviewNotessplit.length > 0) {
                                    for (var i = 0; i < reviewNotessplit.length; i++) {
                                        tr.push(reviewNotessplit[i]);
                                    }
                                    $('#txtReviewNotes').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtReviewNotes > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtReviewNotes').val(reviewNotes);
                        }

                        //MRI findings
                        var xmrifind = data.Table2[0].mri_findings;
                        if ($('#txtmrifinding').hasClass('tag-editor-hidden-src')) {
                            if (xmrifind == '' || xmrifind == null) {
                                $('#divtxtmrifinding > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var xmrifindsplit = xmrifind.split(',');
                                var tr = [];
                                if (xmrifindsplit.length > 0) {
                                    for (var i = 0; i < xmrifindsplit.length; i++) {
                                        tr.push(xmrifindsplit[i]);
                                    }
                                    $('#txtmrifinding').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtmrifinding > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtmrifinding').val(xmrifind);
                        }

                        //diagnosis
                        var diagnosis = data.Table2[0].diagnosis;
                        if ($('#txtdiagnosis').hasClass('tag-editor-hidden-src')) {
                            if (diagnosis == '' || diagnosis == null) {
                                $('#divtxtdiagnosis > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var diagnosiss = diagnosis.split(',');
                                var tr = [];
                                if (diagnosiss.length > 0) {
                                    for (var i = 0; i < diagnosiss.length; i++) {
                                        tr.push(diagnosiss[i]);
                                    }
                                }
                                $('#txtdiagnosis').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtdiagnosis').val(diagnosis);
                        }


                        //past_adverse_events
                        var pastadv = data.Table2[0].past_adverse_events;
                        if ($('#txtpastadverseevents').hasClass('tag-editor-hidden-src')) {
                            if (pastadv == '' || pastadv == null) {
                                $('#divtxtpastadverseevents > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var pastadv = pastadv.split(',');
                                var tr = [];
                                console.log(pastadv);
                                var tags = $('#txtpastadverseevents').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtpastadverseevents').tagEditor('removeTag', tags[i]); }
                                if (pastadv.length > 0) {
                                    for (var i = 0; i < pastadv.length; i++) {
                                        tr.push(pastadv[i]);
                                    }
                                }
                                $('#txtpastadverseevents').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtpastadverseevents').val(pastadv);
                        }

                        //local_examination
                        var localexam = data.Table2[0].local_examination;
                        if ($('#txtlocalexamination').hasClass('tag-editor-hidden-src')) {
                            if (localexam == '' || localexam == null) {

                            }
                            else {
                                var localexam = localexam.split(',');
                                var tr = [];
                                console.log(localexam);
                                var tags = $('#txtlocalexamination').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtlocalexamination').tagEditor('removeTag', tags[i]); }
                                if (localexam.length > 0) {
                                    for (var i = 0; i < localexam.length; i++) {
                                        tr.push(localexam[i]);
                                    }
                                }
                                $('#txtlocalexamination').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtlocalexamination').val(localexam);
                        }
                        //General Examination
                        var GeneraExam = data.Table2[0].general_examination;
                        if ($('#txtgeneralexamination').hasClass('tag-editor-hidden-src')) {
                            if (GeneraExam == '' || GeneraExam == null) {
                                $('#divtxtgeneralexamination > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var GeneraExam = GeneraExam.split(',');
                                var tr = [];
                                console.log(GeneraExam);
                                var tags = $('#txtgeneralexamination').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtgeneralexamination').tagEditor('removeTag', tags[i]); }
                                if (GeneraExam.length > 0) {
                                    for (var i = 0; i < GeneraExam.length; i++) {
                                        tr.push(GeneraExam[i]);
                                    }
                                }
                                $('#txtgeneralexamination').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtgeneralexamination').val(GeneraExam);
                        }
                        debugger;

                        var past_medical_history = data.Table2[0].past_medical_history;

                        if (past_medical_history != null && past_medical_history != "") {

                            var past_medical_historysplit = past_medical_history.split(',');

                            for (i = 0; i < past_medical_historysplit.length; i++) {

                                $("input[name='optionpastmedicalhistory'][value=" + past_medical_historysplit[i] + "]").click();

                            }

                        }

                        var general_examination_chk = data.Table2[0].general_examination_chk;

                        if (general_examination_chk != null && general_examination_chk != "") {

                            var general_examination_chksplit = general_examination_chk.split(',');

                            for (i = 0; i < general_examination_chksplit.length; i++) {

                                $("input[name='optiongeneralexamination'][value=" + general_examination_chksplit[i] + "]").click();

                            }

                        }

                        //abdomen_girth
                        var abdomengirth = data.Table2[0].abdomen_girth;
                        if ($('#txtabdomengirth').hasClass('tag-editor-hidden-src')) {
                            if (abdomengirth == '' || abdomengirth == null) {

                            }
                            else {
                                var abdomengirth = abdomengirth.split(',');
                                var tr = [];
                                console.log(abdomengirth);
                                var tags = $('#txtabdomengirth').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtabdomengirth').tagEditor('removeTag', tags[i]); }
                                if (abdomengirth.length > 0) {
                                    for (var i = 0; i < abdomengirth.length; i++) {
                                        tr.push(abdomengirth[i]);
                                    }
                                }
                                $('#txtabdomengirth').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtabdomengirth').val(abdomengirth);
                        }
                    }

                    if (data.Table3.length > 0) {
                        var notes = data.Table3[0].note;
                        if ($('#txtnotes_1').hasClass('tag-editor-hidden-src')) {
                            if (notes == '' || notes == null) {
                                $('#divtxtNotes > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var notessplit = notes.split(',');
                                var tr = [];
                                if (notessplit.length > 0) {
                                    for (var i = 0; i < notessplit.length; i++) {
                                        tr.push(notessplit[i]);
                                    }
                                    $('#txtnotes_1').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtNotes > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtnotes_1').val(notes);
                        }

                        var complaints = data.Table3[0].current_complaints;
                        if ($('#txtComplaints_1').hasClass('tag-editor-hidden-src')) {
                            if (complaints == '' || complaints == null) {
                                $('#divtxtComplaints_1 > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var complaintss = complaints.split(',');
                                var tr = [];
                                if (complaintss.length > 0) {
                                    for (var i = 0; i < complaintss.length; i++) {
                                        tr.push(complaintss[i]);
                                    }
                                }
                                $('#txtComplaints_1').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtComplaints_1').val(complaints);
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#Prescriptionclose').click(function () {
    debugger
    $('ul.tag-editor').addClass('hidden ui-sortable');

    $('.btn.btn-default.btn-sm').removeClass('active');
})

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

}

function dosage() {
    var medicine_name = $('#medicine_name').val();
    if ($('#doctorId').val() != 'USD00035') {

        if (medicine_name.length > 0) {
            var medicine = {
                medicine_name: medicine_name,
                doctor_id: $('#doctorId').val(),
            }

            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/select_Medicine',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(medicine),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        var data1 = data1.data;
                        if (jQuery.isEmptyObject((data1))) {

                        }
                        else {
                            if (data1.length > 2) {


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


        }
    }
}

//$('#medicine_name').autocomplete({

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

$('#report_1').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/CaseStudy/labAutoCompletelist?TestName=' + $('#report_1').val() + "&testid=" + $('#labtypetest').val() + "&labid=" + $('#lab_id').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.testname, value: item.testname };
                }))

            }
        })
    }
});


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

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


function diagonsisliston(values) {

    var tr = [];
    tr = values
    $('#txtdiagnosis').tagEditor('addTag', tr);
}

function treatment_procedureon(values) {
    var tr = [];
    tr = values
    $('#txtprodcedure').tagEditor('addTag', tr);
    $('#txtprodcedure').val(values);
}


function complaints_master_insert(val, Type) {
    var complaints_master_list = {
        doctor_id: $('#pop_doctor_id').val(),
        complaints: val,
        Dml_Indicator: 'I',
        type: Type
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/complaints_master',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(complaints_master_list),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

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

function diagnosis_insert(val) {
    var complaints_master_list = {
        diagnosis: val,
        doctor_id: $('#pop_doctor_id').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/diagnosis_master',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(complaints_master_list),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

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

function monthval(val) {

    $('#days').val(val);

    var someDate = new Date();
    var numberOfDaysToAdd = val;
    someDate.setDate(someDate.getDate() + numberOfDaysToAdd);

    var dd = someDate.getDate();
    var mm = someDate.getMonth() + 1;
    var y = someDate.getFullYear();




    var someFormattedDate = dd + '/' + mm + '/' + y;
    $('#datepickern').val(someFormattedDate);
    $('#datepickerscan').val(someFormattedDate);
    var appointment_date = $('#Hdnappointment_date').val();
}


$('#medclear').on("click", function () {
    $('#SelMedicineType').val('7');
    $('#medicine_name,#prescriptionNotes,#days,#txtGenericName').val('');
    $('#hndwenttoeat').val('1');
    $('#mor,#aft,#nit').val('0');
    $("#high,#medium,#low").prop("checked", false);
});


$('#ADD_Medicine').on("click", function () {

    $('#ADD_Medicine').attr('disabled', true);
    var priority = $("input[name='optradio']:checked").val();

    var mor = $('#mor').val();
    var aft = $('#aft').val();
    var nit = $('#nit').val();
    if (mor > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#mor').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (aft > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#aft').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (nit > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#nit').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    var Durations = $('#hndduration').val();
    var WhenEat = $('#hndwenttoeat').val();
    var day = $('#days').val();
    if (day == '' || day == null) {
    }
    else {
        var days = 0;
        if (Durations == 1) {
            days = day;
        }
        else if (Durations == 2) {
            days = ((day) * (7));
        }
        else if (Durations == 3) {
            days = ((day) * (30));
        }
        else {

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

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



    var mdescription = {
        Dml_Indicator: 'I',
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        medicine_type_id: $('#SelMedicineType').val(),
        medicine_name: $('#medicine_name').val(),
        how_to_take: $('#hndwenttoeat').val(),
        morning: mor,
        afternoon: aft,
        evening: $('#eve').val(),
        night: nit,
        days_to_take: days,
        pmedicine_dosage: $('#dosage').val(),
        medicine_dosage: $('#dosage').val(),
        medicine_type: $('#SelUnit').val(),
        doctor_id: $('#pop_doctor_id').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        instructions: $('#prescriptionNotes').val(),
        medicine_unit: $('#SelUnit').val(),
        generic_name: $('#txtGenericName').val(),
        max_quantity: max_quantity,
        priority: priority,
    }

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

                }
                else {
                    $('#tbl-medicine').empty();
                    var a = '', dosage = '', medicineUnit = '', medval = '';
                    $.each(data1, function (i, emp) {
                        if (emp.medicine_dosage == null || emp.medicine_dosage == '') {
                            dosage = '';
                        }
                        else {
                            dosage = emp.medicine_dosage + medicineUnit;
                        }
                        var instructions = '';
                        if (emp.instructions == '' || emp.instructions == null) {
                            instructions = '';
                        }
                        else {
                            instructions = emp.instructions;
                        }
                        var Mtypeunit = '', Atypeunit = '', Ntypeunit = '';
                        var generic_name = '';
                        if (emp.generic_name == '' || emp.generic_name == null) {
                            generic_name = '';
                        }
                        else {
                            generic_name = '<span style=font-size:11sssssspx;><i>(' + emp.generic_name + ')</i></span>';
                        }
                        var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                        if (emp.morning != '' && emp.morning != null) {

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

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

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

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

                        }
                        else {
                            session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;

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

                        medval = medval + "<tr id='" + emp.medicine_prescription_id + "'><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name.toUpperCase() + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + days_to_take + "</td><td>" + instructions + "</td><td>" + session + "</td><td><button class='edit btn btn-primary btn-sm btn-add mr-15' onclick='medicineedit(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-sm btn-add' onclick='deleteMedi(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
                    });
                    $('#tbl-medicine').append(medval);

                    $('#SelMedicineType').val('0');
                    $('#food').val('1');
                    $('#medicine_name').val('');
                    //$('#days').val('');
                    $('#dosage').val('');
                    $('input:checkbox').prop('checked', false);
                    $('#mor').val(0);
                    $('#aft').val(0);
                    $('#eve').val(0);
                    $('#nit').val(0);
                    $('#prescriptionNotes').val('');
                    $('#txtGenericName').val('');
                    $('#lblGenericName').html('');

                    //when_to eat reset
                    $('#before_food').prop('checked', true);
                    $('#with_food').prop('checked', false);
                    $('#after_food').prop('checked', false);
                    $('.when_to_eat_disp').text('Before Food');
                    $('p.before_food').addClass('text_before_btn');
                    $('p.with_food').removeClass('text_before_btn');
                    $('p.after_food').removeClass('text_before_btn');
                    $('#hndwenttoeat').val(1);
                    //duration reset
                    $('#duration_days').prop('checked', true);
                    $('#duration_week').prop('checked', false);
                    $('#duration_month').prop('checked', false);
                    $('p.duration_days').addClass('text_before_btn');
                    $('p.duration_week').removeClass('text_before_btn');
                    $('p.duration_month').removeClass('text_before_btn');
                    $('.duration_disp').html('Days');
                    $('#hndduration').val(1);
                    $('#prescriptionNotesToggle').hide();
                    $("input[name='optradio']").prop('checked', false);

                }

                $('#ADD_Medicine').attr('disabled', false);
            }
            else {
                console.log(data1);
            }
        }

    });
});


function medicineedit(medicine_id) {
    $('#ADD_Medicine').hide();
    $('#Update_Medicine').show();
    var medicineId = medicine_id;
    $('#hddn_medicine_prescription_id').val(medicineId);
    var mdescription = {
        Dml_Indicator: 'SS',
        medicine_prescription_id: medicineId,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdescription),
        success: function (data) {
            var medval = '';
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    $.each(data1, function (i, emp) {
                        var medicine_name_ = emp.medicine_name;
                        var medicine_type_ = emp.medicine_type_id;
                        var food_ = emp.how_to_take;
                        var dosage_ = emp.medicine_dosage;
                        var seldosage_ = emp.medicine_unit;
                        var days_ = emp.days_to_take;
                        var morning_ = emp.morning;
                        var afternoon_ = emp.afternoon;
                        var eve_ = emp.evening;
                        var night_ = emp.night;
                        var prescriptionNotes_ = emp.instructions;
                        var generic_name = emp.generic_name;

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

                        $('#SelMedicineType').val(medicine_type_);

                        $('#hndwenttoeat').val(food_);
                        $('#medicine_name').val(medicine_name_);

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

                        $('#dosage').val(dosage_);
                        $('#SelUnit').val(seldosage_);
                        $('#mor').val(morning_);
                        $('#aft').val(afternoon_);
                        $('#eve').val(eve_);
                        $('#nit').val(night_);
                        $('#prescriptionNotes').val(prescriptionNotes_);
                        $('#setDurationUnit').text('Days');
                        $('#txtGenericName').show();
                        $('#lblGenericName').hide();
                        $('#txtGenericName').val(generic_name);
                        $('#prescriptionNotesToggle').show();
                        if (food_ == 9 || food_ == 10) {
                            $('#eveningSession').show();
                            $('.alltime').removeClass('col-lg-3');
                            $('.alltime').addClass('col-lg-4');
                            $('.alltimeinner').removeClass('col-md-4');
                            $('.alltimeinner').addClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-2');
                            $('.whentoeatcls').addClass('col-lg-1');
                        }
                        else {
                            $('#eveningSession').hide();
                            $('.alltime').addClass('col-lg-3');
                            $('.alltime').removeClass('col-lg-4');
                            $('.alltimeinner').addClass('col-md-4');
                            $('.alltimeinner').removeClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-1');
                            $('.whentoeatcls').addClass('col-lg-2');
                            $('#eve').val(0);
                        }
                    });

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

$('#Update_Medicine').click(function () {
    var priority = $("input[name='optradio']:checked").val();
    var mor = $('#mor').val();
    var aft = $('#aft').val();
    var nit = $('#nit').val();
    if (mor > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#mor').focus();
        return false;
    }
    if (aft > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#aft').focus();
        return false;
    }
    if (nit > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#nit').focus();
        return false;
    }
    var Durations = $('#hndduration').val();
    var WhenEat = $('#hndwenttoeat').val();
    var day = $('#days').val();
    if (day == '' || day == null) {
    }
    else {
        var days = 0;
        if (Durations == 1) {
            days = day;
        }
        else if (Durations == 2) {
            days = ((day) * (7));
        }
        else if (Durations == 3) {
            days = ((day) * (30));
        }
    }
    var days1 = days;
    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
        $('#PSelMedicineType').show();
        $('#PSelMedicineType').fadeOut(8000);
        $('#PSelMedicineType').html('Select Types');
        $('#SelMedicineType').focus();
        $('#SelMedicineType :selected').val('0');
        return false;
    }
    if ($.trim($('#medicine_name').val()) == "") {
        $('#Pmedicine_name').show();
        $('#Pmedicine_name').fadeOut(8000);
        $('#Pmedicine_name').html('Enter Medicine Name');
        $('#medicine_name').focus();
        $('#medicine_name').val('');
        return false;
    }
    if ($.trim($('#days').val()) == "") {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter days');
        $('#days').focus();
        $('#days').val('');
        return false;
    }

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

    var medicineType = $('#dosage').val();
    $('#ADD_Medicine').show();
    $('#Update_Medicine').hide();
    var mdescription = {
        Dml_Indicator: 'U',
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        medicine_type_id: $('#SelMedicineType').val(),
        medicine_name: $('#medicine_name').val(),
        how_to_take: $('#hndwenttoeat').val(),
        morning: mor,
        afternoon: aft,
        evening: $('#eve').val(),
        night: nit,
        days_to_take: days,
        pmedicine_dosage: $('#dosage').val(),
        medicine_dosage: $('#dosage').val(),
        medicine_type: $('#SelUnit').val(),
        doctor_id: $('#pop_doctor_id').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        instructions: $('#prescriptionNotes').val(),
        medicine_unit: $('#SelUnit').val(),
        generic_name: $('#txtGenericName').val(),
        medicine_prescription_id: $('#hddn_medicine_prescription_id').val(),
        max_quantity: max_quantity,
        priority: priority
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdescription),
        success: function (data) {
            var medval = '';
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                var data1 = data1.data;

                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    $('#tbl-medicine').empty();
                    var a = '', dosage = '', medicineUnit = '';
                    $.each(data1, function (i, emp) {


                        if (emp.medicine_unit == 1) {
                            medicineUnit = 'gm';
                        }
                        else if (emp.medicine_unit == 2) {
                            medicineUnit = 'mg';
                        }
                        else if (emp.medicine_unit == 3) {
                            medicineUnit = 'units';
                        }
                        else if (emp.medicine_unit == 4) {
                            medicineUnit = 'mcg';
                        }
                        else if (emp.medicine_unit == 5) {
                            medicineUnit = 'ng';
                        }
                        else if (emp.medicine_unit == 6) {
                            medicineUnit = 'ml';
                        }
                        else if (emp.medicine_unit == 7) {
                            medicineUnit = '%';
                        }
                        else if (emp.medicine_unit == 8) {
                            medicineUnit = '';
                        }
                        if (emp.medicine_dosage == null || emp.medicine_dosage == '') {
                            dosage = '';
                        }
                        else {
                            dosage = emp.medicine_dosage + medicineUnit;
                        }
                        var instructions = '';
                        if (emp.instructions == '' || emp.instructions == null) {
                            instructions = '';
                        }
                        else {
                            instructions = emp.instructions;
                        }
                        var Mtypeunit = '', Atypeunit = '', Ntypeunit = '';
                        var generic_name = '';
                        if (emp.generic_name == '' || emp.generic_name == null) {
                            generic_name = '';
                        }
                        else {
                            generic_name = '<span style=font-size:11px;><i>(' + emp.generic_name + ')</i></span>';
                        }
                        var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                        if (emp.morning != '' && emp.morning != null) {

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

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

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

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

                        if (emp.evening == '' || emp.evening == null || emp.evening == 0) {
                            session = morning + ' - ' + afternoon + ' - ' + night;

                        }
                        else {
                            session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;

                        }
                        var days_to_take = '';
                        if (emp.days_to_take == '' || emp.days_to_take == null) {
                            days_to_take = '';
                        }
                        else {
                            days_to_take = emp.days_to_take;
                        }
                        var color = '';
                        if (emp.priority == 1) {
                            color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
                        }
                        else if (emp.priority == 2) {
                            color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
                        }
                        else if (emp.priority == 3) {
                            color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
                        }
                        else {
                            color = '<i class=" fa fa-square" style="color:#ffffff"></i>&nbsp;';
                        }
                        medval = medval + "<tr id='" + emp.medicine_prescription_id + "'><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name.toUpperCase() + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + days_to_take + "</td><td>" + instructions + "</td><td>" + session + "</td><td><button class='edit btn btn-primary btn-sm btn-add mr-15' onclick='medicineedit(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-sm btn-add' onclick='deleteMedi(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
                    });
                    $('#tbl-medicine').append(medval);

                    $('#SelMedicineType').val('0');
                    $('#food').val('1');
                    $('#medicine_name').val('');
                    $('#dosage').val('');
                    $('input:checkbox').prop('checked', false);
                    $('#mor').val(0);
                    $('#aft').val(0);
                    $('#nit').val(0);
                    $('#eve').val(0);
                    $('#prescriptionNotes').val('');
                    $('#txtGenericName').val('');
                    $('#lblGenericName').html('');

                    //when_to eat reset
                    $('#before_food').prop('checked', true);
                    $('#with_food').prop('checked', false);
                    $('#after_food').prop('checked', false);
                    $('.when_to_eat_disp').text('Before Food');
                    $('p.before_food').addClass('text_before_btn');
                    $('p.with_food').removeClass('text_before_btn');
                    $('p.after_food').removeClass('text_before_btn');
                    $('#hndwenttoeat').val(1);
                    //duration reset
                    $('#duration_days').prop('checked', true);
                    $('#duration_week').prop('checked', false);
                    $('#duration_month').prop('checked', false);
                    $('p.duration_days').addClass('text_before_btn');
                    $('p.duration_week').removeClass('text_before_btn');
                    $('p.duration_month').removeClass('text_before_btn');
                    $('.duration_disp').html('Days');
                    $('#hndduration').val(1);
                    $('#prescriptionNotesToggle').hide();
                    $("input[name='optradio']").prop('checked', false);
                }
            }
            else {
                console.log(data1);
            }
        }

    });

});

function deleteMedi(id) {
    var medicineId = id;
    var mdescription = {
        Dml_Indicator: 'D',
        medicine_prescription_id: medicineId,
        visit_report_id: $('#VisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdescription),
        success: function (data) {
            var medval = '';
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    $('#tbl-medicine').empty();
                    var a = '', dosage = '', medicineUnit = '';
                    $.each(data1, function (i, emp) {



                        if (emp.medicine_dosage == null || emp.medicine_dosage == '') {
                            dosage = '';
                        }
                        else {
                            dosage = emp.medicine_dosage + medicineUnit;
                        }
                        var instructions = '';
                        if (emp.instructions == '' || emp.instructions == null) {
                            instructions = '';
                        }
                        else {
                            instructions = emp.instructions;
                        }
                        var Mtypeunit = '', Atypeunit = '', Ntypeunit = '';
                        var generic_name = '';
                        if (emp.generic_name == '' || emp.generic_name == null) {
                            generic_name = '';
                        }
                        else {
                            generic_name = '<span style=font-size:11px;><i>(' + emp.generic_name + ')</i></span>';
                        }
                        var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                        if (emp.morning != '' && emp.morning != null) {

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

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

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

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

                        if (emp.evening == '' || emp.evening == null || emp.evening == 0) {
                            session = morning + ' - ' + afternoon + ' - ' + night;

                        }
                        else {
                            session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;

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

                        medval = medval + "<tr id='" + emp.medicine_prescription_id + "'><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name.toUpperCase() + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + days_to_take + "</td><td>" + instructions + "</td><td>" + session + "</td><td><button class='edit btn btn-primary btn-sm btn-add mr-15' onclick='medicineedit(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger btn-sm btn-add' onclick='deleteMedi(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
                    });
                    $('#tbl-medicine').append(medval);

                    $('#SelMedicineType').val('0');
                    $('#food').val('1');
                    $('#medicine_name').val('');
                    //$('#days').val('');
                    $('#dosage').val('');
                    $('input:checkbox').prop('checked', false);
                    $('#mor').val(0);
                    $('#aft').val(0);
                    $('#nit').val(0);
                    $('#prescriptionNotes').val('');

                    //when_to eat reset
                    $('#before_food').prop('checked', true);
                    $('#with_food').prop('checked', false);
                    $('#after_food').prop('checked', false);
                    $('.when_to_eat_disp').text('Before Food');
                    $('p.before_food').addClass('text_before_btn');
                    $('p.with_food').removeClass('text_before_btn');
                    $('p.after_food').removeClass('text_before_btn');
                    $('#hndwenttoeat').val(1);
                    //duration reset
                    $('#duration_days').prop('checked', true);
                    $('#duration_week').prop('checked', false);
                    $('#duration_month').prop('checked', false);
                    $('p.duration_days').addClass('text_before_btn');
                    $('p.duration_week').removeClass('text_before_btn');
                    $('p.duration_month').removeClass('text_before_btn');
                    $('.duration_disp').html('Days');
                    $('#hndduration').val(1);
                    $("input[name='optradio']").prop('checked', false);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}





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

    var SelFacility = $("#report_1").val();
    var SelFacilityId = $("#labtype_1").val(); //removed :checked
    var Registration = $("#datepickerscan").val();


    if ($.trim((SelFacilityId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((SelFacility)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    if ($.trim((Registration)) == "") {
        $('#Pdatepickerscan').show();
        $('#Pdatepickerscan').fadeOut(8000);
        $('#Pdatepickerscan').html('Select Suggested Date');
        $('#datepickerscan').focus();
        $('#Pdatepickerscan').val('');
        return false;
    }

    var suggeteddate = $('#datepickerscan').val();
    var suggeteddate1 = suggeteddate.split('/');
    suggeteddate = suggeteddate1[2] + '-' + suggeteddate1[1] + '-' + suggeteddate1[0];
    if (SelFacility.length > 0 && SelFacilityId.length > 0) {
        var sms = {
            Dml_Indicator: 'I',
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            lab_prescription: SelFacility,
            lab_type: SelFacilityId,
            suggested_date: suggeteddate,
            slot_start_time: $('#Hdnappointment_date').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(sms),
            success: function (data) {
                var data = JSON.parse(data);
                var tr = '';
                if (data.msg = "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {


                        $('#tbl-scan_1 > tbody').empty();

                        for (var i = 0; i < data.length; i++) {
                            var value = "<tr><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td>" + data[i].suggested_date + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='scanedit_1(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger   btn-sm btn-add' onclick='deleteRow_1(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                            $('#tbl-scan_1 > tbody').append(value);
                        }
                    }
                    $('#report_1').val('');
                    $('#datepickerscan').val('');
                }
                else {
                    console.log(data);
                }
            }
        });
    }

});

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


    var table_id = $('#hdn_scan_id_1').val();


    var SelFacility = $("#report_1").val();
    var SelFacilityId = $("#labtype_1").val(); // removed :checked
    var Registration = $("#datepickerscan").val();

    if ($.trim((SelFacilityId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((SelFacility)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    if ($.trim((Registration)) == "") {
        $('#Pdatepickerscan').show();
        $('#Pdatepickerscan').fadeOut(8000);
        $('#Pdatepickerscan').html('Select Suggested Date');
        $('#datepickerscan').focus();
        $('#Pdatepickerscan').val('');
        return false;
    }

    $('#Add_Lab_record_1').show();
    $('#Update_Lab_record_1').hide();


    if (SelFacility.length > 0 && SelFacilityId.length > 0) {
        var SelFacility = $("#report_1").val();
        var SelFacilityId = $("input[name='scan']").val(); //removed :checked
        var Registration = $("#datepickerscan").val();


        if ($.trim((SelFacilityId)) == "") {
            $('#PSelFacilityId').show();
            $('#PSelFacilityId').fadeOut(8000);
            $('#PSelFacilityId').html('Select Type ');
            return false;
        }
        if ($.trim((SelFacility)) == "") {
            $('#Preport').show();
            $('#Preport').fadeOut(8000);
            $('#Preport').html('Enter Report');
            $('#report').focus();
            $('#report').val('');
            return false;
        }
        if ($.trim((Registration)) == "") {
            $('#Pdatepickerscan').show();
            $('#Pdatepickerscan').fadeOut(8000);
            $('#Pdatepickerscan').html('Select Suggested Date');
            $('#datepickerscan').focus();
            $('#Pdatepickerscan').val('');
            return false;
        }
        var suggeteddate = $('#datepickerscan').val();
        var suggeteddate1 = suggeteddate.split('/');
        suggeteddate = suggeteddate1[2] + '-' + suggeteddate1[1] + '-' + suggeteddate1[0];
        if (SelFacility.length > 0 && SelFacilityId.length > 0) {
            var sms = {
                Dml_Indicator: 'U',
                patient_id: $('#Hdnpatient_id').val(),
                visit_report_id: $('#VisitReportID').val(),
                lab_prescription: SelFacility,
                lab_type: $("#labtype_1").val(),
                suggested_date: suggeteddate,
                slot_start_time: $('#Hdnappointment_date').val(),
                prescription_scan_id: $('#hdn_scan_id_1').val(),
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(sms),
                success: function (data) {
                    console.log(data);

                    var tr = '';
                    var data = JSON.parse(data);
                    if (data.msg == "Success") {
                        var data = data.data;
                        if (jQuery.isEmptyObject((data))) {

                        }
                        else {

                            $('#tbl-scan_1 > tbody:last').empty();
                            for (var i = 0; i < data.length; i++) {
                                var value = "<tr><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td>" + data[i].suggested_date + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='scanedit_1(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger   btn-sm btn-add' onclick='deleteRow_1(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                                $('#tbl-scan_1 > tbody:last').append(value);
                            }
                        }
                        $('#report_1').val('');
                        $('#datepickerscan').val('');
                        $('#checkboxs').prop('value', 0); // by D
                        $('a[data-toggle="checkboxs"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active'); // by D
                        $('a[data-toggle="checkboxs"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active'); // by D
                        $('a[data-toggle="checkboxs"]').not('[data-title="' + 3 + '"]').removeClass('active').addClass('not-active'); // by D
                    }
                    else {
                        console.log(data);
                    }
                }
            });
        }
    }
});

function labtemplatelist(lab_template_id) {
    if ($('#datepickerscan').val() == '' || $('#datepickerscan').val() == null) {
        $('#Pdatepickern').show();
        $('#Pdatepickern').fadeOut(8000);
        $('#Pdatepickern').html('Select date');
        $('#datepickerscan').focus();
        $('#datepickerscan').val('');
        return false;
    }
    var suggeteddate = $('#datepickerscan').val();
    var suggeteddate1 = suggeteddate.split('/');
    suggeteddate = suggeteddate1[2] + '-' + suggeteddate1[1] + '-' + suggeteddate1[0];

    var Template = {
        lab_template_id: lab_template_id,
        doctor_id: $('#pop_doctor_id').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        suggested_date: suggeteddate,
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Lab_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var tr = '';
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    $('#tbl-scan_1 > tbody:last').empty();
                    for (var i = 0; i < data.length; i++) {
                        var value = "<tr><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td>" + data[i].suggested_date + "</td><td><button class='edit btn btn-primary btn-sm btn-add' onclick='scanedit_1(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-danger   btn-sm btn-add' onclick='deleteRow_1(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                        $('#tbl-scan_1 > tbody:last').append(value);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function Copy_prescription_id(visit_report_id) {
   // $('.ClsCopy_prescription').hide();

    //setTimeout(function () {
    //    $('.ClsCopy_prescription').show();
    //}, 2000);
    var VisitreportId = {
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: visit_report_id,
        Dml_Indicator: 'Cp'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#Ptbl-medicine').show();
                    $('#Ptbl-medicine').fadeOut(8000);
                    $('#Ptbl-medicine').html('No medicine prescribed during previous data found');
                    $('#Ptbl-medicine').focus();
                    $('#Ptbl-medicine').val('');
                    return false;
                }
                else {
                if (data1.length > 0) {
                    MedicineDataBinding(data1);
                    $('#pres_popupcls').click();
                }
                else {

                    toastr.success("Medicine deleted");
                }
               }
            }
            else {
                console.log(data1);
            }
        }
    });

}

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

    var VisitreportId = {
        medicine_template_id: medicineTemplateId,
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'TI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#Ptbl-medicine').show();
                    $('#Ptbl-medicine').fadeOut(8000);
                    $('#Ptbl-medicine').html('No medicine prescribed during previous data found');
                    $('#Ptbl-medicine').focus();
                    $('#Ptbl-medicine').val('');
                    return false;
                }
                else {
                    if (data1.length > 0) {
                        MedicineDataBinding(data1);
                    }
                }
                $('.Clscopytemplate').show();
                $('#loaderimg').hide();
            }
            else {
                console.log(data);
            }
        }
    });
}

function MedicineDataBinding(data1) {
    debugger
    $('#tbl-medicine tbody').empty();
    $('#tbl-medicine').empty();
    var a = '', dosage = '', medicineUnit = '', medval = '';
    //var data1 = JSON.parse(data1);
    $.each(data1, function (i, emp) {
        if (emp.medicine_dosage == null || emp.medicine_dosage == '') {
            dosage = '';
        }
        else {
            dosage = emp.medicine_dosage + medicineUnit;
        }
        var instructions = '';
        if (emp.instructions == '' || emp.instructions == null) {
            instructions = '';
        }
        else {
            instructions = emp.instructions;
        }
        var Mtypeunit = '', Atypeunit = '', Ntypeunit = '';
        var generic_name = '';
        if (emp.generic_name == '' || emp.generic_name == null) {
            generic_name = '';
        }
        else {
            generic_name = '<span style=font-size:11sssssspx;><i>(' + emp.generic_name + ')</i></span>';
        }
        var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
        if (emp.morning != '' && emp.morning != null) {

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

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

            if (night.length > 1) {
                if (night[1] == 5 || night[1] == 50 || night[1] == 05) {
                    if (night[0] == 0) {
                        night = '<sup>1</sup>&frasl;<sub>2</sub>';
                    }
                    else {
                        night = night[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                    }
                }
                else if (night[1] == 25) {
                    if (night[0] == 0) {
                        night = '<sup>1</sup>&frasl;<sub>4</sub>';
                    }
                    else {
                        night = night[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                    }
                }
                else if (night[1] == 75) {
                    if (night[0] == 0) {
                        night = '<sup>3</sup>&frasl;<sub>4</sub>';
                    }
                    else {
                        night = night[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                    }
                }
                else {
                    night = emp.night;
                }
            }
            else { night = emp.night; }
        }
        if (emp.evening == '' || emp.evening == null || emp.evening == 0) {
            session = morning + ' - ' + afternoon + ' - ' + night;
        }
        else {
            session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;
        }
        var days_to_take = '';
        if (emp.days_to_take == '' || emp.days_to_take == null) {
            days_to_take = '';
        }
        else if (emp.days_to_take == '9999') {
            days_to_take = 'Daily';
        }
        else {
            days_to_take = emp.days_to_take;
        }
        var color = '';
        if (emp.priority == 1) {
            color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
        }
        else if (emp.priority == 2) {
            color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
        }
        else if (emp.priority == 3) {
            color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
        }
        else {
            color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
        }
        medval = medval + "<tr id='" + emp.medicine_prescription_id + "'><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + days_to_take + "</td><td>" + instructions + "</td><td>" + session + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Update Medicine' onclick='medicineedit(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Medicine' onclick='deleteMedi(\"" + emp.medicine_prescription_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"
    });
    $('#tbl-medicine').append(medval);
    loadmedicineprescription()
}



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

    var com = $('#txtComplaints_1').val();
    var cdate = '';
    if ($('#datepickern').val() != '' && $('#datepickern').val() != null) {
        var sdate = $('#datepickern').val().split('/');
        cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
    }

    // added by nandhini
    const checkboxespastmedicalhistory = document.querySelectorAll('input[name="optionpastmedicalhistory"]:checked');
    let pastmedicalhistory = [];
    checkboxespastmedicalhistory.forEach((checkbox) => {
        pastmedicalhistory.push(checkbox.value);
    });
    var pastmedicalhistory1 = pastmedicalhistory.toString();

    const checkboxesgeneralexamination = document.querySelectorAll('input[name="optiongeneralexamination"]:checked');
    let generalexamination = [];
    checkboxesgeneralexamination.forEach((checkbox) => {
        generalexamination.push(checkbox.value);
    });
    var generalexamination1 = generalexamination.toString();


    var create_visit_report = {
        Dml_Indicator: 'DDU',
        patient_id: $('#Hdnpatient_id').val(),
        diagnosis: $('#txtdiagnosis').val(),
        treatment_procedure: $('#txtprodcedure').val(),
        visit_report_id: $('#VisitReportID').val(),
        complaints: com,
        Notes: $('#txtnotes_1').val(),
        instruction: $('#txt_visit_instruction').val(),
        next_appointment_date: cdate,
        xray_findings: $('#txtXrayFindings').val(),
        advice: $('#txtAdvice').val(),
        counselling: $('#txtCounselling').val(),
        vas: $('#m_vas').val(),
        lab_findings: $('#txtlabfinding').val(),
        xray_findings_new: $('#txtxrayfind').val(),
        investigation: $('#txtinvetig').val(),
        observation_val: $('#txtobserv').val(),
        review_notes: $('#txtReviewNotes').val(),
        past_adverse_events: $('#txtpastadverseevents').val(),
        local_examination: $('#txtlocalexamination').val(),
        abdomen_girth: $('#txtabdomengirth').val(),
        mri_findings: $('#txtmrifinding').val(),
        general_examination_chk: generalexamination1,
        general_examination: $('#txtgeneralexamination').val(),
        past_medical_history: pastmedicalhistory1
    }

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

                }
                else {
                    prescriptionClear();
                    saveprescription(1)
                }
            }
            else {
                console.log(data);
            }
        }
    });
});


$('#btnprescription_print').click(function () {
    debugger
    var com = $('#txtComplaints_1').val();
    var cdate = '';
    if ($('#datepickern').val() != '' && $('#datepickern').val() != null) {
        var sdate = $('#datepickern').val().split('/');
        cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
    }

    // added by nandhini
    const checkboxespastmedicalhistory = document.querySelectorAll('input[name="optionpastmedicalhistory"]:checked');
    let pastmedicalhistory = [];
    checkboxespastmedicalhistory.forEach((checkbox) => {
        pastmedicalhistory.push(checkbox.value);
    });
    var pastmedicalhistory1 = pastmedicalhistory.toString();

    const checkboxesgeneralexamination = document.querySelectorAll('input[name="optiongeneralexamination"]:checked');
    let generalexamination = [];
    checkboxesgeneralexamination.forEach((checkbox) => {
        generalexamination.push(checkbox.value);
    });
    var generalexamination1 = generalexamination.toString();

    var create_visit_report = {
        Dml_Indicator: 'DDU',
        diagnosis: $('#txtdiagnosis').val(),
        treatment_procedure: $('#txtprodcedure').val(),
        visit_report_id: $('#VisitReportID').val(),
        complaints: com,
        Notes: $('#txtnotes_1').val(),
        instruction: $('#txt_visit_instruction').val(),
        next_appointment_date: cdate,
        xray_findings: $('#txtXrayFindings').val(),
        advice: $('#txtAdvice').val(),
        counselling: $('#txtCounselling').val(),
        vas: $('#m_vas').val(),
        lab_findings: $('#txtlabfinding').val(),
        xray_findings_new: $('#txtxrayfind').val(),
        investigation: $('#txtinvetig').val(),
        observation_val: $('#txtobserv').val(),
        review_notes: $('#txtReviewNotes').val(),
        past_adverse_events: $('#txtpastadverseevents').val(),
        local_examination: $('#txtlocalexamination').val(),
        abdomen_girth: $('#txtabdomengirth').val(),
        mri_findings: $('#txtmrifinding').val(),
        general_examination_chk: generalexamination1,
        general_examination: $('#txtgeneralexamination').val(),
        past_medical_history: pastmedicalhistory1
    }

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

                }
                else {
                    var VisitReportID = $('#VisitReportID').val()
                    var visitid = data[0].visitid
                    var branchid = data[0].branch_id
                    var hospitalid = data[0].hospitalid
                    var prescription_page_style = data[0].prescription_page_style
                    var patientid = data[0].patientid
                    printpdf(VisitReportID, visitid, patientid, hospitalid, branchid, prescription_page_style)
                   // window.open('/PatientDashboard/PPDF?visitreportid=' + $('#VisitReportID').val() + '&lantype=' + 1 + '&btnval=1', "_blank");
                    prescriptionClear();
                    saveprescription(1)
                }
            }
            else {
                console.log(data);
            }
        }
    });
});

function printpdf(VisitReportID, visitid, patientid, hospitalid, branchid, prescription_page_style) {
    debugger;
    if (prescription_page_style != "8") {
        window.open('/PatientDashboard/PPDF?visitreportid=' + VisitReportID + '&lantype=' + $('#sellang').val() + '&btnval=1', "_blank");
    }
    else {

        var load_data = {
            formid: '137',
            branchid: branchid,
            hospitalid: hospitalid,
            patientid: patientid,
            visit_reportid: visitid,
            doctorname: "",
            hospital_name: "",
            phone_number: "",
            email_id: ""
        }


        $.ajax({
            async: true,
            type: 'POST',
            url: '/reports/SetPrescriptionReportParameters',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(load_data),
            success: function (data) {
                window.open('/Webform/PrescriptionPrint.aspx', '_blank');
            }
        });
    }
}

function prescriptionClear() {
    $('#tbl-medicine tbody').empty();
    $('#tbl-scan_1 tbody').empty();
    $('#labtemplatelist').empty();
    $('#templatelist').empty();
    $('#Copy_prescriptionList').empty();

    $('#txtComplaints_1').val('');
    $('#txtnotes_1').val('');
    $('#txtdiagnosis').val('');
    $('#txtprodcedure').val('');
    $('#txtAdvice').val('');
    $('#txtCounselling').val('');
    $('#datepickern').val('');
    $('#txt_visit_instruction').val('');
    $('#txtXrayFindings').val('');
    $('#txtinvetig').val('');
    $('#txtReviewNotes').val('');
    $('#txtlabfinding').val('');
    $('#txtxrayfind').val('');
    $('#txtobserv').val('');
    $('#txtpastadverseevents').val('');
    $('#txtlocalexamination').val('');
    $('#txtabdomengirth').val('');
    $('#txtmrifinding').val('');

    $('#divtxtComplaints_1 ul').remove();
    $('#divtxtdiagnosis ul').remove();
    $('#divtxtAdvice ul').remove();
    $('#divtxtCounselling ul').remove();
    $('#divtxtlabfinding ul').remove();
    $('#divtxtxrayfind ul').remove();
    $('#divtxtInvestigation ul').remove();
    $('#divtxtInstruction ul').remove();
    $('#divtxtProcedure ul').remove();
    $('#divtxtNotes ul').remove();
    $('#divtxtReviewNotes ul').remove();
    $('#divtxtobserv ul').remove();
    $('#divtxtinvetig ul').remove();
    $('#divtxtmrifinding ul').remove();
    $('.close').click();

}

// Prescription end
//paymenttype if value=4 transaction id will enable
$("#Selpaymenttype").change(function () {
    var value = $("#Selpaymenttype").val();
    if (value == 4) {
        $("#transaction").show();
    }
    else {
        $("#transaction").hide();
    }
})
//
$("#btn_email").click(function () {
    if ($.trim($('#e_mail').val()).length == "") {
        $('#Pe_mail').show();
        $('#Pe_mail').fadeOut(8000);
        $('#Pe_mail').html('Required');
        $('#Pe_mail').focus();
        $('#Pe_mail').val('');
        return false;
    }
    else {
        var invoice_data = {
            email: $("#e_mail").val(),
            visit_report_id: $("#Pvisit_report").val(),
            patient_name: $("#Ppatient_name").val(),
            doctor_id: $("#Pdoctor_id").val(),
            doctor_name: $('#txtDusername').html()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/Invoice_function',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(invoice_data),
            success: function (data) {
                toastr.success("Mail Sent");
                $('#email_Popup').modal('hide');
            }
        });
    }
});

$('#myschedule_tab_list').click(function () {
    debugger;
    if ($('#hiddenRole_id').val() == 1) {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
    else {
        $('#SelBranch_div').show()
        $('#SelDoctor_div').show()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
})

$('#reviewvisit_tab_list').click(function () {
    debugger;
    if ($('#hiddenRole_id').val() == 1) {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
    else {
        $('#SelBranch_div').show()
        $('#SelDoctor_div').show()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }

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

    if ($('#hiddenRole_id').val() == 1) {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
    else {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').show()
        $('#referal_Doctor_div').show()
        $('#referal_to_div').show()
        $('#referal_clear_div').show()
        healthcare();
    }
})


$('#referredpatients_tab_list').click(function () {
    debugger;

    if ($('#hiddenRole_id').val() == 1) {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').hide()
        $('#referal_Doctor_div').hide()
        $('#referal_to_div').hide()
        $('#referal_clear_div').hide()
    }
    else {
        $('#SelBranch_div').hide()
        $('#SelDoctor_div').hide()

        $('#referal_Branch_div').show()
        $('#referal_Doctor_div').show()
        $('#referal_to_div').show()
        $('#referal_clear_div').show()
        LoadBranch();
    }
})

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

function healthcareall() {

    debugger;
    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    } else {
        btndisable = 'style="display:none";';
    }

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    var branch_id = $('#SelBranch').val();
    if ($('#SelDoctor').val() != 0 && $('#SelDoctor').val() != null) {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
        branch_id = (branch_id == null || branch_id == "") ? $('#HospitalBranchID').val() : branch_id;
    }

    var healthcareData = {
        Dml_Indicator: "HPS",
        AppointmentDate: date,
        Schedule_Type: 4
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(healthcareData),
        success: function (data) {
            console.log(data);
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                if (!jQuery.isEmptyObject(data1.data)) {
                    console.log(data1);

                    var tr = '',
                        i = 0;
                    var a = data1.data;
                    console.log(a);
                    if (a.length > 0) {

                        console.log(a[i].DoctorName);
                        console.log(a[i].branch_name);
                        for (i = 0; i < a.length; i++) {
                            tr += '<tr class="view">' +
                                "<td class='tb_name opensub'>" + a[i].user_name + "</td>" +
                                "<td class='opensub'>" + "Audilogisit" + "</td>" +
                                "<td class='opensub'>" + a[i].user_name_count + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                /*"<td class='opensub'>" + "-" + "</td>" +*/
                                /*'<td class="opensub">' +*/
                                '<td class="opensub" onclick=\'details(\"' + a[i].user_name + '\",\"' + a[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr><tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>'

                        }

                        $('#FO_app_list_tableall tbody').empty();
                        $('#FO_app_list_tableall tbody').append(tr);

                        $(".fold-table tr.view .opensub").on("click", function () {
                            $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
                        });
                    } else {
                        LoadAppointmentRequest($('#HiddenDoctorID').val());
                    }
                }
                LoadBranch();
            }
        }
    });
}
function unifiedFunction() {
    debugger;
    var DoctorId = $('#HiddenDoctorID').val();
    var branchid = ($('#HospitalBranchID').val() == '' ? 0 : $('#HospitalBranchID').val());
    $('#FO_app_list_tableall tbody').empty();

    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    } else {
        btndisable = 'style="display:none";';
    }

    var DoctorData = {
        Dml_Indicator: "A",
        doctor_id: DoctorId,
        product_code: $('#HProductCode').val(),
        hospital_id: $('#HospitalId').val(),
        branch_id: branchid,
        // AppointmentDate: date,
    };

    var healthcareData = {
        Dml_Indicator: "HPS",
        AppointmentDate: date,
        Schedule_Type: 4
    };

    var appointmentData = [];
    var healthcareDataResponse = [];

    $.when(
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/Dashboard_appointment_count',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if (data1.msg == "Success" && !jQuery.isEmptyObject(data1.data)) {
                    appointmentData = data1.data.data1;
                }
            }
        }),
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Dashboard/select_Appointment_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(healthcareData),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if (data1.msg == "Success" && !jQuery.isEmptyObject(data1.data)) {
                    healthcareDataResponse = data1.data;
                }
            }
        })
    ).then(function () {
        // Combine and render data
        var combinedData = [];
        combinedData = combinedData.concat(appointmentData, healthcareDataResponse);

        if (combinedData.length > 0) {
            var tr = '';
            for (var i = 0; i < combinedData.length; i++) {
                if (combinedData[i].DoctorName !== undefined) { // appointment_summary data
                    tr += '<tr class="view">' +
                        "<td class='tb_name opensub'>" + combinedData[i].DoctorName + "</td>" +
                        "<td class='opensub'>" + "Doctor" + "</td>" +
                        "<td class='opensub'>" + (combinedData[i].Booked + combinedData[i].visited) + "</td>" +
                        "<td class='opensub'>" + combinedData[i].visited + "</td>" +
                        "<td class='opensub'>" + combinedData[i].Booked + "</td>" +
                        "<td class='opensub'>" + combinedData[i].video_call + "</td>" +
                        "<td class='opensub'>" + combinedData[i].Prescribed + "</td>" +
                        '<td class="opensub">' +
                        '<div class="icon-toggle opensub" onclick=\'view_specificappointment_details(\"' + combinedData[i].doctor_id + '\",\"' + combinedData[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';>' +
                        '<i class="fa fa-angle-down" aria-hidden="true"></i>' +
                        '</div>' +
                        '<div class="icon-toggle opensub bind-table-icon" onclick=\'view_revisit_list(\"newapprow_' + (i + 1) + '\",this);\'> ' +
                        '<i class="fa fa-table" aria-hidden="true"></i>' +
                        '</div>' +
                        '<div class="icon-toggle opensub bind-table-icon" onclick=\'view_review_list(\"newapprow_' + (i + 1) + '\",this);\'>' +
                        '<i class="fa fa-user" aria-hidden="true"></i>' +
                        '</div>' +
                        '</td></tr>' +
                        '<tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>';
                } else { // healthcareall data
                    tr += '<tr class="view">' +
                        "<td class='tb_name opensub'>" + combinedData[i].user_name + "</td>" +
                        "<td class='opensub'>" + "Audilogisit" + "</td>" +
                        "<td class='opensub'>" + combinedData[i].user_name_count + "</td>" +
                        "<td class='opensub'>" + "-" + "</td>" +
                        "<td class='opensub'>" + "-" + "</td>" +
                        "<td class='opensub'>" + "-" + "</td>" +
                        "<td class='opensub'>" + "-" + "</td>" +
                        '<td class="opensub" onclick=\'details(\"' + combinedData[i].user_name + '\",\"' + combinedData[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr><tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>';
                }
            }
            $('#FO_app_list_tableall tbody').empty();
            $('#FO_app_list_tableall tbody').append(tr);

            $(".fold-table tr.view .opensub").on("click", function () {
                $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
            });
        } else {
            LoadAppointmentRequest($('#HiddenDoctorID').val());
        }
        LoadBranch();
    });
}

function healthcare() {
   
    debugger;
    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    } else {
        btndisable = 'style="display:none";';
    }

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    var branch_id = $('#SelBranch').val();
    if ($('#SelDoctor').val() != 0 && $('#SelDoctor').val() != null) {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
        branch_id = (branch_id == null || branch_id == "") ? $('#HospitalBranchID').val() : branch_id;
    }

    var healthcareData = {
        Dml_Indicator: "HPS",
        AppointmentDate: date,
        Schedule_Type: 4
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(healthcareData),
        success: function (data) {
            console.log(data);
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                if (!jQuery.isEmptyObject(data1.data)) {
                    console.log(data1);
                    
                    var tr = '',
                        i=0;
                    var a = data1.data;
                    console.log(a);
                    if (a.length > 0) {
                        
                        console.log(a[i].DoctorName);
                        console.log(a[i].branch_name);
                        for (i = 0; i < a.length; i++) {
                            tr += '<tr class="views">' +
                                "<td class='tb_name opensub'>" + a[i].user_name + "</td>" +
                                "<td class='opensub'>" + "Audilogisit" + "</td>" +
                                "<td class='opensub'>" + a[i].user_name_count + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                "<td class='opensub'>" + "-" + "</td>" +
                                /*"<td class='opensub'>" + "-" + "</td>" +*/
                                /*'<td class="opensub">' +*/
                                '<td class="opensub" onclick=\'details(\"' + a[i].user_name+ '\",\"' + a[i].doctor_user_id + '\",\"newapprow_' + (i + 1) + '\",this)\';><div class="icon-toggle opensub"><i class="fa fa-angle-down" aria-hidden="true"></i></div></td></tr><tr class="fold" id="newapprow_' + (i + 1) + '"><td class="fold" colspan="8"></td></tr>'

                        }

                        $('#FO_app_list_tablenew tbody').empty();
                        $('#FO_app_list_tablenew tbody').append(tr);

                        $(".fold-table tr.views .opensub").on("click", function () {
                            $(this).parent('tr').toggleClass("open").next(".fold").toggleClass("open");
                        });
                    } else {
                        LoadAppointmentRequest($('#HiddenDoctorID').val());
                    }
                }
                LoadBranch();
            }
        }
    });
}
function details(user_name, user_id, rowid, e) {
    debugger;
    $('#' + rowid + ' td').empty();
    $('#' + rowid + ' td').append(detailsNew(user_name, user_id, rowid));

}
function detailsNew(user_name, user_id, row_id) {
    debugger;
    var div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');

    div.removeClass('loading');
    var tr, row_data = '';
    tr = $('<table class="table table-condensed body-borderless table_borderless">');
    tr.append('<thead><tr><th class="hidden"></th><th>Token No</th><th>Branch Name</th><th>Visit Report ID</th><th>Patient ID</th><th>Name</th><th>Phone Number</th><th>Actions</th></tr></thead><tbody id="tblHealthcareprofessional_body">');

    var date = '';
    var currentseldate = "";
    if ($('.app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    } else if ($('.app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    } else if ($('.app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    } else {
        date = $('.app_date_current').html();
    }
    currentseldate = date;
    var currentseldates = currentseldate.split('/');
    currentseldate = currentseldates[1] + '/' + currentseldates[0] + '/' + currentseldates[2];

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = d.getFullYear() + '-' +
        (month < 10 ? '0' : '') + month + '-' +
        (day < 10 ? '0' : '') + day;

    var btndisable = '';
    if (date == output) {
        btndisable = '';
    } else {
        btndisable = 'style="display:none";';
    }

    var DoctorId = $('#myHiddenVar').val();
    var role_id = $('#hiddenRole_id').val();
    var branch_id = $('#SelBranch').val();
    if ($('#SelDoctor').val() != 0 && $('#SelDoctor').val() != null) {
        DoctorId = $('#SelDoctor').val();
        role_id = 1;
        branch_id = (branch_id == null || branch_id == "") ? $('#HospitalBranchID').val() : branch_id;
    }

    var healthcareData = {
        Dml_Indicator: "HP",
        AppointmentDate: date,
        Schedule_Type: 4,
        user_role: user_name
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/select_Appointment_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(healthcareData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var tbody = $('#tblHealthcareprofessional_body');
                tbody.empty();
                if (jQuery.isEmptyObject(data1.data)) {
                    var emptyRow = '<tr><td colspan="9"><div class="img-center"><img src="/Content/img/no_record.png" class="img-responsive no_record_img"><br><div class="no_data_content">No data found.</div></div></td></tr>';
                    tbody.append(emptyRow);
                } else {
                    $.each(data1.data, function (i, emp) {
                        var row = '<tr>' +
                            '<td>' + (i + 1) + '</td>' +
                            '<td>' + emp.branch_name + '</td>' +
                            '<td>' + emp.visit_report_id + '</td>' +
                            '<td>' + emp.patient_id + '</td>' +
                            '<td>' + emp.first_name + '</td>' +
                            '<td>' + emp.phone_number + '</td>' +
                            '<td>' +
                            '<button type="button" class="engage-btn btn btn-primary">' +
                            '<i class="fa fa-user"></i> Engage</button>' +
                            '</td>' +
                            '</tr>';
                        tbody.append(row);

                    });
                }
            }
        }
    });

    div.append(tr);
    $('#' + row_id + ' td').empty().append(div);
}




function referal_LoadDoctor() {
    debugger;
    //var roleId = $('#hiddenRole_id').val();
    //var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#referal_SelBranch').val()
    }

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


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

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

$('#referal_SelDoctor').change(function () {
    debugger;
    LoadReferredPatientsList('RDF')
})

$('#referal_to_SelDoctor').change(function () {
    debugger;
    LoadReferredPatientsList('RDF')
})

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

$('#referal_btn_clear').click(function () {
    debugger;
    $('#referal_SelBranch').val(0)
    $('#referal_SelDoctor').empty()
    $('#referal_to_SelDoctor').empty()
    LoadReferredPatientsList()
})

function Hideshow() {
    debugger;
    var show = {
        dml_indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(show),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            $('#hhomecarestatus').empty();
            $('#hhomecarevisit').empty();
            $('#hipstatus').empty();
            $('#hipvisit').empty();
            $('#hlhcstatus').empty();
            $('#hlhcvisit').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;
                var ipstatus = data.data.Table[1].status;
                var ipvisit = data.data.Table[1].master_vist_type_id;
                var homecarestatus = data.data.Table[2].status;
                var homecarevisit = data.data.Table[2].master_vist_type_id;
                var lhcstatus = data.data.Table[28].status;
                var lhcvisit = data.data.Table[28].master_vist_type_id;
                var pharmstatus = data.data.Table[36].status;
                var pharmvisit = data.data.Table[36].master_vist_type_id;

                $('#hhomecarestatus').val(homecarestatus);
                $('#hhomecarevisit').val(homecarevisit);
                $('#hipstatus').val(ipstatus);
                $('#hipvisit').val(ipvisit);
                $('#hlhcstatus').val(lhcstatus);
                $('#hlhcvisit').val(lhcvisit);
                $('#hpharmstatus').val(pharmstatus);
                $('#hpharmvisit').val(pharmvisit);
                if ($('#hhomecarestatus').val() == 0 && $('#hhomecarevisit').val() == 3) {
                    debugger;
                    $('#homecare_div').hide();
                }
                if ($('#hipstatus').val() == 0 && $('#hipvisit').val() == 2) {
                    debugger;
                    $('#ip_bill_card').hide();
                }
                if ($('#hlhcstatus').val() == 0 && $('#hlhcvisit').val() == 29) {
                    debugger;
                    $('#LHC_Card').hide();
                }

            }
        }
    });
}

function mobileapp() {
    debugger;
    var show = {
        dml_indicator: 'MA'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(show),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            $('#happ').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;
                var app = data.data.Table[0].is_app;
                $('#happ').val(app);
                if ($('#happ').val() == 1) {
                    debugger;
                    $('#mobile_user').show();
                }
                else {
                    $('#mobile_user').hide();
                }
            }
        }
    });
}

//Forms Start

//load Select Form
//function loadserviceForm() {
//    debugger;
//    var data = {
//        Dml_Indicator: 'FSD'
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(data),
//        success: function (data) {
//            debugger;

//            var data2 = JSON.parse(data);
//            console.log(data2);
//            if (jQuery.isEmptyObject((data2.data))) {

//            }
//            else {

//                if (data2.msg == "Success") {
//                    $('#selectform').empty();
//                    var option = "";
//                    var data1 = data2.data;
//                    var default_option = "<option value='0'>--Select--</option>";
//                    $.each(data1, function (i, emp) {
//                        option = option + "<option value=" + emp.Formid + " >" + emp.Form_Name + "</option>"
//                    })
//                    // $('#servicetype_filter').append(default_option + option);
//                    $('#selectform').append(default_option + option);
//                }
//            }
//        }
//    })
//}

function loadForm(patient_id,dml) {
    debugger;
    var data = {
        Dml_Indicator: dml,
        Patient_Id: patient_id,
        RoleId: $('#hiddenRole_id').val(),
        UserId: $('#hiddenUser_id').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    $('#selectform1').empty();
                    $('#selectform').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.Formid + " >" + emp.Form_Name + "</option>"
                    })
                    $('#selectform1').append(default_option + option);
                    $('#selectform').append(default_option + option);
                    $('#hndpatientid').val(patient_id)
                }
            }
        }
    })
}


$('#selectform').change(function () {
    debugger;
    //var selectedOptionText = $(this).find('option:selected').text();
    //$('#formShow_header').html(selectedOptionText);
    var Form_Data = {
        Dml_Indicator: "EIIF",
        surgery_request_id: $('#selectform').val(),
        patient_ID: $('#hndpatientid').val()
    }

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

            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1[0].id != 0) {
                        $('#formShow').attr('src', $('#Hdformurl').val() + 'edit-form/' + data1[0].id + '');
                    }
                    else {
                        $('#formShow').attr('src', $('#Hdformurl').val() + 'form/' + $('#selectform').val() + '?visit_reportid=' + btoa($('#HdnVisitid').val()) + '&patientid=' + btoa($('#HdnPatientid').val()) + '');
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
});


function Forms(vist_report_id,vist_reportid, patient_id, patientid, doctor_id, doctor_appoinment_slot_id, branch_id) {
    debugger;
    loadForm(patient_id,'FSD')
    $('#hnpdoctor_appoinment_solt_id').val(doctor_appoinment_slot_id)
    $('#doctorId').val(doctor_id)
    $('#hnpvist_reportid').val(vist_reportid)
    $('#hnppatientid').val(patientid)
    $('#hnDBranch_id').val(branch_id)

    $('#hnppatient_id').val(patient_id)
    $('#hnpvist_report_id').val(vist_report_id)
    $('#iframeFormpopup').modal("toggle");
    $('.fileuploadid').hide()
    $('#formShow').removeAttr('src');
    $('#formShow_header').html('')
    $('#formSubmit').attr('disabled', false);
}

//$('#selectform').change(function () {
//    debugger;
//    var selectid = $('#selectform').val()
//    selectedOptionText = $(this).find('option:selected').text();

//    $('#formShow_header').html(selectedOptionText);
   
//    $('#formShow').attr('src', $("#Hdformurl").val() + 'form/' + selectid + '?patientid=' + btoa($('#hnppatientid').val()) + '&visit_reportid=' + btoa($('#hnpvist_reportid').val()) + '')


//})


//vitals-quickentry --Nurse Initial Assessment Form--
function LoadUser(user) {
    debugger;
    var department = {
        Dml_Indicator: "VU"
    }
    $.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) {
            debugger
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Department;
                    $('#SelLanguageCordinator').empty();

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Department = Department + '<option value="' + emp.doctor_user_id + '" data-id=' + emp.doctor_user_role_id + '>' + emp.Doctor + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelLanguageCordinator').append(Department);
                        $("#SelLanguageCordinator").change();

                    }
                    else {
                        $('#SelLanguageCordinator').append(default_opt + Department);

                    }

                    if (user != '' && user != null) {
                        $('#SelLanguageCordinator').val(user);
                    }

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


$('[data-toggle="Chkspecialreligious"]').click(function () {
    debugger;
    if ($(this).attr('data-title') === '1') {
        $('#div_special_details').show();
    } else {
        $('#div_special_details').hide();
    }
});
$('[data-toggle="ChkPainscreening"]').click(function () {
    debugger;
    if ($(this).attr('data-title') === '1') {
        $('#div_painscore').show();
    } else {
        $('#div_painscore').hide();
    }
});
$('[data-toggle="ChkAnylanguagebarrier"]').click(function () {
    debugger;
    if ($(this).attr('data-title') === '1') {
        $('#div_languagecordinator').show();
        LoadUser()
    } else {
        $('#div_languagecordinator').hide();
    }
});

$('[data-toggle="ChkAllergiesifany"]').click(function () {
    debugger;
    if ($(this).attr('data-title') === '1') {
        $('#div_Allergies').show();
    } else {
        $('#div_Allergies').hide();
    }
});
function loadMedicineType(medi_type) {
    debugger;
    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#doctorId').val(),
        is_pharmacy: $('#His_pharmacy').val(),
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/MedicineType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(params),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var medicine;
                    $('#SelMedicineType').empty();
                    medicinetypearray = data1;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        medicine = medicine + '<option value="' + emp.medicine_type_id + '">' + emp.medicine_type + '</option>';
                    });
                    $('#SelMedicineType').append(default_opt + medicine);
                    if (medi_type != '') {
                        $('#SelMedicineType').val(medi_type);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
  //  loadwhentoeat();
}


//Added By Akshaya - new prescription

//health plix prescription


// Use event delegation to attach Autocomplete to dynamically generated elements
$(document).on('focus', '.durationinput', function () {
    $(this).autocomplete({
        source: function (request, response) {
            var inputValue = request.term; // Get the user's input
            debugger;
            // Generate duration options based on the input
            var options = [];
            if (!isNaN(inputValue) && inputValue > 0) {
                options.push(inputValue + " Days");
                options.push(inputValue + " Weeks");
                options.push(inputValue + " Months");
                options.push(inputValue + " Years");
            }

            // Provide the generated options to the autocomplete
            response(options);
        },
        minLength: 0, // Show suggestions even with no characters entered
        select: function (event, ui) {
            // Automatically populate the duration field with the selected value
            $(this).val(ui.item.value);
             $('#txttdno_duration').val('1')
            return false; // Prevent the value from being inserted twice
        },
    });
});



//$(document).on("focus", ".dosage-autocomplete", function () {
//    $(this).autocomplete({
//        source: ["1-0-1", "1-1-1", "1-0-1", /* Add your medicine names here */],
//        minLength: 0,
//        select: function (event, ui) {
//            // Automatically add a new row when a medicine is selected

//        }
//    });
//});


// Medicine Type auto complete
$(document).on("focus", ".SelMedicineTypeA", function () {
    debugger;
    console.log(medicinetypearray)
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");

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

            MedicineTypeId = medicinetypearray.find(item => item.medicine_type === ui.item.value).medicine_type_id;
            MedicineTypeName = medicinetypearray.find(item => item.medicine_type === ui.item.value).medicine_type;
            newRow1.find('#txttdmedicine_type_id').val(MedicineTypeId)
            newRow1.find('#txttdmedicine_type_name').val(MedicineTypeName)

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


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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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


});


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

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

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


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

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

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

                }
            })
        },
    });

});

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

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

                }
            })
        },
    });
});

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

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

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

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

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

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

});

// Add a global event listener for Enter key press
$(document).on("keydown", ".medicine-autocomplete", handleEnterKey);

//Function to handle appending a new row on Enter key press
function handleEnterKey(event) {
    debugger;
    if (event.keyCode === 13) { // Check if Enter key is pressed
        var inputElement = $(event.target);
        var currentRow = inputElement.closest("tr");
        var nextInput = currentRow.find("input[type='text']").eq(inputElement.index() + 2);
        currentRow.find('.deleteicon-btn').show();
        // If there's a next input in the same row, focus on it

        if (inputElement.val() != "") {
            nextInput.focus();

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

                var newRow = currentRow.clone();
                newRow.find("input").val(""); // Clear input values in the new row
                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
            }
        }

    }
}

// Add a global event listener for Enter key press
$(document).on("keydown", ".prescriptionNotes ", handleEnterKey1);

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

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

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

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

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

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

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

    }
}


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

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


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

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

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

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

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

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

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

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

});

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

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

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

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

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

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

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

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

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

    var tableData = [];
    var tot_rowM = $('#tblmedicine >tbody >tr').length;
    if (tot_rowM > 0) {
        $('#loaderimg').show();
        $("#tblmedicine tbody tr").each(function () {
            var row = $(this);
            if (row.find("#txtmedicineName").val() !== '') {

                var mor = 0;
                var aft = 0;
                var nit = 0;
                var eve = 0;
                var max_quantity = 0;
                var daysInUnit = 0;
                var dosageValue = row.find("#txttddosage").val();
                dosageValue = dosageValue.replace(/\s*-\s*/g, "-");
                row.find("#txttddosage").val(dosageValue);
                if (typeof dosageValue === "string" && ((/^\s*\d+(?:\s*-\s*\d+)+\s*$/.test(dosageValue)) || (/^\s*\d.+(?:\s*-\s*\d.+)+\s*$/.test(dosageValue)))) {  ///^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {

                    // Split the value into parts
                    var parts = dosageValue.split('-');
                    if (parts.length == 3) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[2])) || 0;
                    }
                    else if (parts.length == 4) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[3])) || 0;
                        eve = parseFloat($.trim(parts[2])) || 0;
                    }
                }
                var txttdno_duration = row.find("#txttdno_duration").val();
                if (txttdno_duration !== '0') {
                    var text = row.find("#txttddurationinput").val();

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

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


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



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

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

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

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

    //if (val == 1) {
    //    diagnosis();
    //}

}



function loadmedicineprescription() {
    debugger;
    var visit_id;
    if ($('#VisitReportID').val() != '') visit_id = $('#VisitReportID').val();
    else visit_id = $('#EditVisitReportID').val();

    var VisitreportId = {
        visit_report_id: visit_id,
        Dml_Indicator: 'S',
        is_pharmacy: $('#His_pharmacy').val()
    }

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

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

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


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



    var medval = '';
    var j = $('#tblmedicine tbody tr').length;


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

        // var j = parseInt(i) + 1
        j++
        var checked1 = '', checked2 = '', checked3 = '';
        if (emp.priority == 3) {
            checked1 = 'checked'
        }
        else if (emp.priority == 2) {
            checked2 = 'checked'
        }
        else if (emp.priority == 1) {
            checked3 = 'checked'
        }
        // Construct the table row based on your data
        var row = '<tr id="' + emp.medicine_prescription_id + '">' +
            '<td class="draggable-handle tblserialnumber" style="cursor:move !important" id="txttdserialnumber">' + j + '</td>' +

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

            '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" value="' + emp.how_to_take + '" id="Hidwhen_to_eat_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" value="' + emp.medicine_frequency + '" id="Hidmedicine_frequencyId" /></td>' +


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

        medval += row;

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

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

        '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" id="Hidwhen_to_eat_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" id="Hidmedicine_frequencyId" /></td>' +

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

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

function updateSerialNumbers() {
    $("#tbl-medicine1 tr").each(function (index, row) {
        $(row).find("td:first").text(index + 1); // Update serial number
    });
}
function deleteMedicine(e, id) {
    debugger;
    var rowCount = $("#tblmedicine tbody tr").length;

    if (rowCount === 1) {

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

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


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

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

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

function loadwhentoeat() {

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

                }
                else {

                    $('#hndwenttoeat').empty();
                    trs = '';
                    var defaultoption = '<option value="">--select--</option>';

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

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

    });
}

function copyprescriptionlist() {
    debugger
    var visiti = $('#VisitReportID').val();
    visiti = visiti.split('-');
    if (visiti[1] == "V001") {
        $('#copymed').hide();
    }
    else {
        $('#copymed').show();
        var VisitreportId = {
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            Dml_Indicator: 'CPL',
            doctor_id: ($('#hiddenRole_id').val() == 1) ? $('#myHiddenVar').val() : $('#doctorId').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(VisitreportId),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                        tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="copyprestablel" />');
                        tr.append("<thead><tr><th>S No</th><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead><tbody>");
                    }
                    else {
                        var trlist = '', trlist_final = '', j = 0, k = 0, medtable, medtableend, medheadTable;
                        $('#copyprestablelist').empty();
                        for (var i = 0; i < data.length; i++) {
                            if (i < ((data.length) - 1)) {
                                if (data[i].visit_report_id == data[i + 1].visit_report_id) {
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                }
                                else {
                                    k = k + 1;
                                    medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                    medtableend = '</table></div></div>';
                                    medheadTable = '<thead><tr><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                    trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                    medtable, medtableend, medheadTable, trlist = '';
                                }
                            }
                            else if (i <= ((data.length) - 1)) {
                                k = k + 1;
                                trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                medtableend = '</table></div></div>';
                                medheadTable = '<thead><tr><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                medtable, medtableend, medheadTable, trlist = '';
                            }
                            else {
                                if (i == data.length) {
                                    k = k + 1;
                                    medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                    medtableend = '</table></div></div>';
                                    medheadTable = '<thead><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                }
                                else {
                                    trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                    trlist, medtable, medtableend, medheadTable = '';
                                }
                            }
                        }
                        $('#copyprestablelist').html(trlist_final);
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    templatelist();
}

function templatelist() {
    debugger
    var Template = {
        doctor_id: ($('#hiddenRole_id').val() == 1) ? $('#myHiddenVar').val() : $('#doctorId').val(),
        Dml_Indicator: 'S',
        is_ip: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                $('#templatelist').empty();
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {
                    // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                    tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                }
                else {
                    if (data.length <= 0) {
                        // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                        tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" class="Clscopytemplate" onclick=copytemplate(' + data[i].medicine_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div></a><br>';
                        }
                    }
                }
                $('#templatelist').html(tr);

                //commented by nandhini for performance issue on 20/09/2022 and lab prescription section removed already.
                //labtemlatelist();
                //labtype();

                //Deittemlatelist();

            }
            else {
                console.log(data);
            }
        }
    });
}
function diag_temp(id) {
    var temp = {
        indicator_id: 'DTSL',
        diagnosis_id: id,
        doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/diagnosis_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(temp),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {

            }
            else {
                var data2 = data1.data;
                if (data2.Table.length > 0) {
                    for (var i = 0; i < data2.Table.length; i++) {
                        var name = data2.Table[i].name;
                        //complaints
                        if (name === 'Complaints') {
                            if ($('#txtComplaints_1').hasClass('tag-editor-hidden-src')) {
                                var complaintsVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Complaints') {
                                        var complaintsValPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        complaintsVal = complaintsVal.concat(complaintsValPoints);
                                    }
                                }
                                complaintsVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(complaintsVal);
                                $('#txtComplaints_1').tagEditor('addTag', complaintsVal);
                            }
                        }

                        //instruction
                        if (name === 'Instruction') {
                            if ($('#txt_visit_instruction').hasClass('tag-editor-hidden-src')) {
                                var instructionVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Instruction') {
                                        var instructionValPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        instructionVal = instructionVal.concat(instructionValPoints);
                                    }
                                }
                                instructionVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(instructionVal);
                                $('#txt_visit_instruction').tagEditor('addTag', instructionVal);
                            }
                        }
                        //procedures
                        if (name === 'Procedure') {
                            if ($('#txtprodcedure').hasClass('tag-editor-hidden-src')) {
                                var ProcedureVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Procedure') {
                                        var ProcedurePoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        ProcedureVal = ProcedureVal.concat(ProcedurePoints);
                                    }
                                }
                                ProcedureVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(ProcedureVal);
                                $('#txtprodcedure').tagEditor('addTag', ProcedureVal);
                            }
                        }

                        //notes
                        if (name === 'Notes') {
                            if ($('#txtnotes_1').hasClass('tag-editor-hidden-src')) {
                                var notesVal = [];
                                // Iterate through the data and find the 'Notes' section
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Notes') {
                                        // Split the notes into individual points
                                        var notesPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            // Remove leading and trailing white spaces
                                            return point.trim();
                                        });
                                        // Add each point as a separate tag
                                        notesVal = notesVal.concat(notesPoints);
                                    }
                                }
                                // Sort notes based on size for alignment
                                notesVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });

                                console.log(notesVal);
                                // Add the notes points as separate tags to the tag editor
                                $('#txtnotes_1').tagEditor('addTag', notesVal);
                            }
                        }
                        //observation
                        if (name === 'Observation') {
                            if ($('#txtobserv').hasClass('tag-editor-hidden-src')) {
                                var ObservationVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Observation') {
                                        var ObservationValPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        ObservationVal = ObservationVal.concat(ObservationValPoints);
                                    }
                                }
                                ObservationVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(ObservationVal);
                                $('#txtobserv').tagEditor('addTag', ObservationVal);
                            }
                        }

                        //investigation
                        if (name === 'Investigation') {
                            if ($('#txtinvetig').hasClass('tag-editor-hidden-src')) {
                                var invetigVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Investigation') {
                                        var invetigValPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        invetigVal = invetigVal.concat(invetigValPoints);
                                    }
                                }
                                invetigVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(invetigVal);
                                $('#txtinvetig').tagEditor('addTag', invetigVal);
                            }
                        }

                        //advice
                        if (name === 'Advice') {
                            if ($('#txtAdvice').hasClass('tag-editor-hidden-src')) {
                                var AdviceVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Advice') {
                                        var AdviceValPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        AdviceVal = AdviceVal.concat(AdviceValPoints);
                                    }
                                }
                                AdviceVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(AdviceVal);
                                $('#txtAdvice').tagEditor('addTag', AdviceVal);
                            }
                        }

                        //couselling
                        if (name === 'Counselling') {
                            if ($('#txtCounselling').hasClass('tag-editor-hidden-src')) {
                                var CounsellingVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Counselling') {
                                        var CounsellingPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        CounsellingVal = CounsellingVal.concat(CounsellingPoints);
                                    }
                                }
                                CounsellingVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(CounsellingVal);
                                $('#txtCounselling').tagEditor('addTag', CounsellingVal);
                            }
                        }

                        //lab finding
                        if (name === 'Lab Finding') {
                            if ($('#txtlabfinding').hasClass('tag-editor-hidden-src')) {
                                var labfinVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Lab Finding') {
                                        var labfinPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        labfinVal = labfinVal.concat(labfinPoints);
                                    }
                                }
                                labfinVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(labfinVal);
                                $('#txtlabfinding').tagEditor('addTag', labfinVal);
                            }
                        }

                        //xray finding
                        if (name === 'Xray Findings') {
                            if ($('#txtxrayfind').hasClass('tag-editor-hidden-src')) {
                                var xrayfindVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Xray Findings') {
                                        var xrayfindPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        xrayfindVal = xrayfindVal.concat(xrayfindPoints);
                                    }
                                }
                                xrayfindVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(xrayfindVal);
                                $('#txtxrayfind').tagEditor('addTag', xrayfindVal);
                            }
                        }

                        //Review Note
                        if (name === 'Review Notes') {
                            if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                                var ReviewNotesVal = [];
                                for (var j = 0; j < data2.Table.length; j++) {
                                    if (data2.Table[j].name === 'Review Notes') {
                                        var ReviewNotesPoints = data2.Table[j].description.split(/\d+\./).filter(Boolean).map(function (point) {
                                            return point.trim();
                                        });
                                        ReviewNotesVal = ReviewNotesVal.concat(ReviewNotesPoints);
                                    }
                                }
                                ReviewNotesVal.sort(function (a, b) {
                                    return a.length - b.length;
                                });
                                console.log(ReviewNotesVal);
                                $('#txtReviewNotes').tagEditor('addTag', ReviewNotesVal);
                            }
                        }


                    }
                }
            }
        }
    });
}