var vitals_nodata_img = '<div class="well">No Recorded Value</div>';

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

//var ref = new Firebase("https://ursugar-6ce9a.firebaseio.com/");
//var ref = new Firebase("https://ursugartest.firebaseio.com/");
//var ref = new Firebase($('#HFirebaseID').val());
//casesheet

$(document).ready(function () {
    debugger;
    loadvisit_type()
    loadMedicineType();
    LoadPatientGeneralInformation();
    LoadFutureServicesList();
    loadwhentoeat();
    loadmedicineprescription();
    DeitPlan();
    Assesed_by();
    debugger;
    $('.da-load-casestudy').show();
    $('#txtTime').timepicker({
        showInputs: false
    });
    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);
});

isBookAppointment = false;
var patient
if ($('#Hdnpatient_id').val() == '') {
    patient = $('#EditVisitReportID').val();
    var patient_id = patient.split('-');
    patient = patient_id[0];
}
else {
    patient = $('#Hdnpatient_id').val()
}

var more = 0;
$('#view_more_1').click(function () {
    more++;
    if (more == 1) {
        load_patient_summary_visit_report();
    }
    sessionStorage.clear();
});

function changedefault(e) {
    var photoSrc = "/Content/img/profile_icon.png";
    $(e).attr("src", photoSrc);
}
$('#Hdnpatient_id').val(patient);

function Assesed_by() {
    var VisitreportId
    if ($('#VisitReportID').val() != "") {
        VisitreportId = {
            visit_report_id: $('#VisitReportID').val(),
            Dml_Indicator: 'ABB',
            branch_id: $('#HBranchID').val()
        }
    }
    else {
        VisitreportId = {

            Dml_Indicator: 'AB',
            branch_id: $('#HBranchID').val()
        }
    }

    $.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;
                var val = data.Table[0].assesed_by;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var default_opt = '<option value="0">--Select--</option>';
                    var user = '';
                    $.each(data.Table, function (i, emp) {
                        user = user + '<option value="' + emp.doctor_user_id + '">' + emp.first_name + '</option>';
                    });
                    $('#assesed_by').append(default_opt + user);
                    if (val != "" && val != null) {
                        $('#assesed_by').val(val);
                    }
                    else {
                        $('#assesed_by').val($('#hiddenUser_id').val());
                    }
                }
            }
        }
    })
}

function VisitreportId() {
    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#doctorId').val(),
        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);
                        $('#appointment_id').val(data.Table[0].appointment_id);
                        $('#Doc_Name').val(data.Table[0].DoctorName);
                        //$('.Hdoctorname').html(data.Table[0].DoctorName);
                        if (data.Table[0].referredby != null && data.Table[0].referredby != "") {
                            $('.HReferredBy').html(data.Table[0].referredby);
                        }
                        else {
                            $('.divReferredBy').hide();
                        }
                        $('#Hpatient_BillingClass').val(data.Table[0].billing_class);
                        $('#Hpatient_Wardid').val(data.Table[0].wardid);
                        //added by nandhini on 26/09/2022
                        $('#EditVisitReportID').val(VisitReportID);
                        Engage();
                        $('#Hpatient_BillingClass').val(data.Table[0].billing_class);
                        if ($('#appointment_type').val() == 2) {
                            $('#btnvideocall').show();
                            $('#btnvideocall_1').show();
                            $('#btnclicktocall_1').show();
                            NewVideoFunction();
                        }
                        else {
                            $('#btnvideocall').hide();
                            $('#btnvideocall_1').hide();
                            $('#btnclicktocall_1').hide();
                        }


                    }
                }
            }

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

        }
    });
    getlabfile();

}
function Engage() {
    var Engage = {
        patient_id: $('#Hdnpatient_id').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        visit_report_id: $('#VisitReportID').val(),
        check_by: $('#doctorId').val(),
        check_staus: '2',
        Dml_Indicator: 'VCI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engage),
        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) {
                        $('#patient_checkin_id').val(data[0].patient_checkin_id);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function height_popupdata() {
    $('#txtcentimeter').val($('.clsheight').html())
    if ($('#HCasesheetType').val() == "4") {
        var ageval = $('#AAge').val();
        if (parseInt(ageval) > 25 && ($('#txtcentimeter').val() != null && $('#txtcentimeter').val() != '' && $('#txtcentimeter').val() != '-')) {
            $('#txtcentimeter').prop('readonly', true);
            $('#txtfeet').prop('readonly', true);
            $('#txtinches').prop('readonly', true);
        }
        else {
            $('#txtcentimeter').prop('readonly', false);
            $('#txtfeet').prop('readonly', false);
            $('#txtinches').prop('readonly', false);
        }
    }
    $('#txtweight').val($('.clsweight').html());
    $('#lblbmi').html($('.clsbmi').html());
}


function EditEngage() {
    var Engage = {
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#EditVisitReportID').val(),
        check_by: $('#doctorId').val(),
        check_staus: '4',
        Dml_Indicator: 'ECI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engage),
        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) {
                        $('#patient_checkin_id').val(data[0].patient_checkin_id);
                        $('#Hpatient_BillingClass').val(data[0].billing_class);
                        $('#Hpatient_Wardid').val(data[0].wardid);

                        if (data[0].referredby != null && data[0].referredby != "") {
                            $('.HReferredBy').html(data[0].referredby);
                        }
                        else {
                            $('.divReferredBy').hide();
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function patient_select_new() {
    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,
        Dml_Indicator: '1',
        Doctor_id: $('#doctorId').val(),

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

            }
            else {
                console.log(data);
                if (data.Table.length > 0) {
                    $('#noofvisit').html(data.Table[0].visit_count);
                    $('.noofvisit').html(data.Table[0].visit_count);
                    //Assesed_by(data.Table[0].assesed_by);
                    if (data.Table[0].created_on == '' || data.Table[0].created_on == null) {
                        $('#firstvisit').html('');
                        $('.firstvisit').html('');
                    }
                    else {
                        $('#firstvisit').html(data.Table[0].created_on);
                        $('.firstvisit').html(data.Table[0].created_on);
                    }

                    $('#moreinfovisit_date').html(data.Table[0].visit_count + ' visits since ' + $('#firstvisit').html());

                    $('#Selbloodgroup').val(data.Table[0].patient_blood_group);
                    if (data.Table[0].type_of_diabetes == '' || data.Table[0].type_of_diabetes == null) {
                        $('#diab').html('Type of Diabetes');
                        $('.diab').html('Type of Diabetes');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg4');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg');
                    }
                    else if (data.Table[0].type_of_diabetes == '0') {
                        $('#diab').html('Diabetes');
                        $('.diab').html('Diabetes');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('#diab').html('Type of Diabetes');
                        $('.diab').html('Type of Diabetes');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg4');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg');
                    }
                    else if (data.Table[0].type_of_diabetes == '1') {
                        $('#diab').html('Type1');
                        $('.diab').html('Type1');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg4');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg2');
                    }
                    else if (data.Table[0].type_of_diabetes == '2') {
                        $('#diab').html('Type2');
                        $('.diab').html('Type2');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);

                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg4');
                        $('body').addClass('orange_bg5');
                    }
                    else if (data.Table[0].type_of_diabetes == '3') {
                        $('#diab').html('MODY');
                        $('.diab').html('MODY');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg4');
                    }
                    else if (data.Table[0].type_of_diabetes == '4') {
                        $('#diab').html('LADA');
                        $('.diab').html('LADA');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg4');
                    }
                    else if (data.Table[0].type_of_diabetes == '5') {
                        $('#diab').html('GDM');
                        $('.diab').html('GDM');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg4');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg3');
                    }
                    else if (data.Table[0].type_of_diabetes == '6') {
                        $('#diab').html('Other');
                        $('.diab').html('Other');
                        $('#diabVal').val(data.Table[0].type_of_diabetes);
                        $('body').removeClass('orange_bg');
                        $('body').removeClass('orange_bg1');
                        $('body').removeClass('orange_bg2');
                        $('body').removeClass('orange_bg3');
                        $('body').removeClass('orange_bg5');
                        $('body').addClass('orange_bg4');
                    }

                    $('#smoking').val(data.Table[0].patient_smoking_habit);
                    var image = (data.Table[0].photo);
                    var PatientPhoto = $('#ChdnPatientPhoto').val();
                    if ($.trim(image) == "" || image == null) {
                        photoSrc = "/Content/img/profile_icon.png";
                    }
                    else {
                        photoSrc = PatientPhoto + image;
                    }
                    $('.imgphoto').attr('src', photoSrc);

                    var first_name = (data.Table[0].first_name)
                    var last_name = (data.Table[0].last_name)
                    if (last_name == '' || last_name == null) {
                        last_name = '';
                    }
                    first_name = first_name + ' ' + last_name;
                    $("#PatientName").attr('title', data.Table[0].patient_id);
                    $('.PatientName').html(first_name);
                    $('.Patientpno').html('<i class="fa fa-phone" aria-hidden="true"></i> ' + data.Table[0].phone_number_1);
                    debugger;
                    $('#Patientpno').val(data.Table[0].phone_number_1);

                    $('#PatientId').html(data.Table[0].patient_id);
                    $('.PatientId').html('<i class="fa fa-credit-card"></i> ' + data.Table[0].patient_id);
                    $('.Hdoctorname').html(data.Table[0].doctor_name);
                    var r_age;
                    if (data.Table[0].DOB == '' || data.Table[0].DOB == null) {
                        if (data.Table[0].age_registered_date == "" || data.Table[0].age_registered_date == null) {
                            if (data.Table[0].gender == '' || data.Table[0].gender == null) {
                                $('.age').html('-');
                            }
                            else if (data.Table[0].age == "" || data.Table[0].age == null) {
                                $('.age').html('-');
                            }
                            else {
                                $('.age').html('-');
                            }
                        }
                        else {
                            var dob = (data.Table[0].age_registered_date);
                            dob = new Date(dob);
                            var today = new Date();
                            r_age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                        }
                        $('#gender').val(data.Table[0].gender);
                        var gender;
                        if (data.Table[0].gender == '1') {
                            gender = ' - 1'
                            $('#Male').prop('checked', true);
                        }
                        if (data.Table[0].gender == '2') {
                            gender = ' - 2'
                            $('#Female').prop('checked', true);
                        }
                        if (data.Table[0].gender == '3') {
                            gender = ' - 3'
                            $('#Male').prop('checked', true);
                        }
                        var genders = data.Table[0].gender;
                        $('#Csex').val(genders);
                        $('a[data-toggle=Csex][data-title="' + genders + '"]').removeClass('not-active');
                        $('a[data-toggle=Csex][data-title="' + genders + '"]').addClass('active');

                        if (genders == 1) {
                            genders = 'Male';
                        }
                        else if (genders == 2) {
                            genders = 'Female';
                        }
                        else if (genders == 3) {
                            genders = 'Others';
                        }
                        else {
                            genders = 'Gender';
                        }
                        var age = '', ageC = '';
                        if (data.Table[0].age_registered_date == '' || data.Table[0].age_registered_date == null) {
                            if (data.Table[0].age == '' || data.Table[0].age == null) {
                                age = 'Age / ';
                            }
                            else {
                                ageC = data.Table[0].age;
                                age = data.Table[0].age + ' years ';
                            }
                        }
                        else {
                            ageC = r_age;
                            age = r_age + ' years ';
                        }
                        $('#hndage').val(ageC);
                        $('#AAge').val(ageC);
                        $('.Age').html(age + genders);
                    }
                    else {
                        var gender;
                        $('#Csex').val(data.Table[0].gender);
                        $('a[data-toggle=Csex][data-title="' + data.Table[0].gender + '"]').removeClass('not-active');
                        $('a[data-toggle=Csex][data-title="' + data.Table[0].gender + '"]').addClass('active');
                        if (data.Table[0].gender == '1') {
                            gender = ' - 1'
                            $('#Male').prop('checked', true);
                        }
                        if (data.Table[0].gender == '2') {
                            gender = ' - 2'
                            $('#Female').prop('checked', true);
                        }
                        if (data.Table[0].gender == '3') {
                            gender = ' - 3'
                            $('#Male').prop('checked', true);
                        }
                        var dob = (data.Table[0].DOB);
                        dob = new Date(dob);
                        var today = new Date();
                        var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));

                        $('#gender').val(gender);
                        $('#hndage').val(age);
                        $('#AAge').val(age);
                        var genders = data.Table[0].gender;
                        if (genders == 1) {
                            genders = 'Male';
                        }
                        else if (genders == 2) {
                            genders = 'Female';
                        }
                        else if (genders == 3) {
                            genders = 'Others';
                        }
                        else {
                            genders = 'Gender';
                        }

                        $('#gender').val(data.Table[0].gender);
                        var sex = data.Table[0].gender;
                        if (sex == 1) {
                            $("#Male").prop('checked', true);
                        }
                        if (sex == 2) {
                            $("#Female").prop('checked', true);
                        }
                        $('.Age').html(age + ' ' + 'years ' + genders);
                    }
                    if (data.Table[0].diabetes_of_year == '' || data.Table[0].diabetes_of_year == null) {
                        if (data.Table[0].diabetes_of_month == '' || data.Table[0].diabetes_of_month == null) {
                            $('#diabetes').html('History in years');
                            $('.diabetes').html('History in years');
                        }
                        else {
                            $('#diabetes').html('0.' + data.Table[0].diabetes_of_month + 'History in years');
                            $('.diabetes').html('0.' + data.Table[0].diabetes_of_month + 'History in years');
                        }
                    }
                    else {
                        if (data.Table[0].diabetes_of_month == '' || data.Table[0].diabetes_of_month == null) {
                            $('#diabetes').html(data.Table[0].diabetes_of_year + ' Years');
                            $('.diabetes').html(data.Table[0].diabetes_of_year + ' Years');
                        }
                        else {
                            $('#diabetes').html(data.Table[0].diabetes_of_year + '.' + data.Table[0].diabetes_of_month + ' Years');
                            $('.diabetes').html(data.Table[0].diabetes_of_year + '.' + data.Table[0].diabetes_of_month + ' Years');
                            $('#txtCHDiabetes').val(data.Table[0].diabetes_of_year);
                            $('#yearDia').html(data.Table[0].diabetes_of_year);
                        }
                    }
                    if (data.Table[0].patient_height == '' || data.Table[0].patient_height == null) {
                        $('.clsheight').html('-');
                    }
                    else {
                        //var hieghtdb = parseInt(data.Table[0].patient_height * 12) + parseInt(data.Table[0].patient_height_metric);
                        ////var hieghtout = Math.round(hieghtdb * 2.54);
                        //var hieghtout = (hieghtdb * 2.54);

                        var hieghtout = (data.Table[0].patient_height * 30.48) + (data.Table[0].patient_height_metric * 2.54);
                        hieghtout = hieghtout.toFixed(1);

                        $('.clsheight').html(hieghtout);
                        $('#hieght').html(hieghtout);
                        $('.clsheight').val(hieghtout);
                    }
                    if (data.Table[0].patient_weight == '' || data.Table[0].patient_weight == null) {
                        $('.clsweight').html('-');
                    }
                    else {
                        $('.clsweight').html(data.Table[0].patient_weight);
                        $('.clsweight').val(data.Table[0].patient_weight);
                        $('#hidwight').val(data.Table[0].patient_weight);
                    }
                    var heightFt = (data.Table[0].patient_height),
                        heightIn = (data.Table[0].patient_height_metric),
                        height = parseFloat(heightFt * 12) + parseFloat(heightIn);
                    var weight = (data.Table[0].patient_weight);
                    weight = (weight * 2.20462)
                    BMI = calculateBMI(height, weight);

                    $('.clsbmi').html(isNaN(BMI) ? '-' : BMI);
                    $('.clsbmi').val(isNaN(BMI) ? '-' : BMI);

                    var BmiFlags = $('.clsbmi').html();
                    if (BmiFlags <= 18.5) {
                        $('#BMI').html('Underweight');
                        $('#BMI_head').addClass('dash-notify-above');
                    }
                    else if (BmiFlags > 18.5 && BmiFlags <= 24.9) {
                        $('#BMI').html('Normal');
                        $('#BMI_head').addClass('dash-notify-normal');
                    }
                    else if (BmiFlags > 25.0 && BmiFlags <= 29.9) {
                        $('#BMI').html('Overweight');
                        $('#BMI_head').addClass('dash-notify-above');
                    }
                    else if (BmiFlags >= 30.0) {
                        $('#BMI').html('Obese');
                        $('#BMI_head').addClass('dash-notify-above');
                    }
                    $('#ChkAlcohol').val(data.Table[0].patient_alcohol_consumption);
                    $('a[data-toggle=ChkAlcohol][data-title="' + data.Table[0].patient_alcohol_consumption + '"]').removeClass('not-active');
                    $('a[data-toggle=ChkAlcohol][data-title="' + data.Table[0].patient_alcohol_consumption + '"]').addClass('active');
                    var ls = data.Table[0].patient_alcohol_consumption;
                    var lsTxt;
                    if (ls == 1) {
                        lsTxt = "Non Drinker";
                    } else if (ls == 2) {
                        lsTxt = "Rare";
                    } else if (ls == 3) {
                        lsTxt = "Social";
                    } else if (ls == 4) {
                        lsTxt = "Regular";
                    } else if (ls == 5) {
                        lsTxt = "Heavy";
                    }
                    else {
                        lsTxt = "Select";
                    }
                    $('#AlcText>span').text(lsTxt);

                    $('#ChkFood').val(data.Table[0].patient_food_perference);
                    $('a[data-toggle=ChkFood][data-title="' + data.Table[0].patient_food_perference + '"]').removeClass('not-active');
                    $('a[data-toggle=ChkFood][data-title="' + data.Table[0].patient_food_perference + '"]').addClass('active');
                    var ls = data.Table[0].patient_food_perference;
                    var lsTxt;
                    if (ls == 1) {
                        lsTxt = "Vegetarian";
                    } else if (ls == 2) {
                        lsTxt = "Non-Vegetarian";
                    } else if (ls == 3) {
                        lsTxt = "Eggetarian";
                    } else if (ls == 4) {
                        lsTxt = "Vegan";
                    }
                    else {
                        lsTxt = "Select";
                    }
                    $('#ChkFoodText>span').text(lsTxt);

                    $('#ChkSmoking').val(data.Table[0].patient_smoking_habit);
                    $('a[data-toggle=ChkSmoking][data-title="' + data.Table[0].patient_smoking_habit + '"]').removeClass('not-active');
                    $('a[data-toggle=ChkSmoking][data-title="' + data.Table[0].patient_smoking_habit + '"]').addClass('active');

                    var ls = data.Table[0].patient_smoking_habit;
                    var lsTxt;
                    if (ls == "8517006") {
                        lsTxt = "Iv'e quit";
                    } else if (ls == "266919005") {
                        lsTxt = "Don't Smoke";
                    } else if (ls == "4.28061E+14") {
                        lsTxt = "1-2/day";
                    } else if (ls == "4.28041E+14") {
                        lsTxt = "3-5/day";
                    } else if (ls == "4.28071E+14") {
                        lsTxt = "5-10/day";
                    } else if (ls == "449868002") {
                        lsTxt = "10/day";
                    }
                    else {
                        lsTxt = "Select";
                    }
                    $('#smkText>span').text(lsTxt);
                    $('#ChkActivity').val(data.Table[0].patient_activity_level);
                    $('a[data-toggle=ChkActivity][data-title="' + data.Table[0].patient_activity_level + '"]').removeClass('not-active');
                    $('a[data-toggle=ChkActivity][data-title="' + data.Table[0].patient_activity_level + '"]').addClass('active');
                    var ls = data.Table[0].patient_activity_level;
                    var lsTxt;
                    if (ls == 1) {
                        lsTxt = "Sedentary(low)";
                    } else if (ls == 2) {
                        lsTxt = "Moderate(normal)";
                    } else if (ls == 3) {
                        lsTxt = "Active(high)";
                    } else if (ls == 4) {
                        lsTxt = "Athletic(Very high)";
                    }
                    else {
                        lsTxt = "Select";
                    }
                    $('#ChkActText>span').text(lsTxt);

                    $('#sellangs').val(data.Table[0].print_flag);
                }
                if (data.Table1.length > 0) {
                    $('#appointment_id').val(data.Table1[0].appointment_id);
                    if (data.Table1[0].bp_flag_type == '' || data.Table1[0].bp_flag_type == null) {
                        $('#BP').html('-');
                        $('#BP_head_1').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].bp_flag_type == '0') {
                        $('#BP').html('Normal');
                        $('#BP_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].bp_flag_type == '1') {
                        $('#BP').html('Low BP');
                        $('#BP_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].bp_flag_type == '2') {
                        $('#BP').html('Low BP');
                        $('#BP_head').addClass('dash-notify-below');
                    }
                    else if (data.Table1[0].bp_flag_type == '3') {
                        $('#BP').html('Normal');
                        $('#BP_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].bp_flag_type == '4') {
                        $('#BP').html('Prehypertension');
                        $('#BP_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].bp_flag_type == '5') {
                        $('#BP').html('Hypertension Stage 1');
                        $('#BP_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].bp_flag_type == '6') {
                        $('#BP').html('Hypertension Stage 2');
                        $('#BP_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].bp_flag_type == '7') {
                        $('#BP').html('Hypertension Crisis');
                        $('#BP_head').addClass('dash-notify-above');
                    }
                    var DDietBP = $('#BP').html();
                    $('#DBP').html(DDietBP);

                    if (data.Table1[0].dyslipedemia1 == '' || data.Table1[0].dyslipedemia1 == null) {
                        $('#Dyslipidimea').html('-');
                        $('.Dyslipidimea_head > i').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].dyslipedemia1 == '0') {
                        $('#Dyslipidimea').html('No');
                        $('#Dyslipidimea_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].dyslipedemia1 == '1') {
                        $('#Dyslipidimea').html('Yes');
                        $('#Dyslipidimea_head').addClass('dash-notify-below');
                    }
                    if (data.Table1[0].pdr == '' || data.Table1[0].pdr == null) {
                        $('#PDR').html('-');
                        $('#PDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].pdr == '0') {
                        $('#PDR').html('-');
                        $('#PDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].pdr == '1') {
                        $('#PDR').html('None');
                        $('#PDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].pdr == '2') {
                        $('#PDR').html('Mild');
                        $('#PDR_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].pdr == '3') {
                        $('#PDR').html('Moderate');
                        $('#PDR_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].pdr == '4') {
                        $('#PDR').html('Severe');
                        $('#PDR_head').addClass('dash-notify-below');
                    }
                    if (data.Table1[0].npdr == '' || data.Table1[0].npdr == null) {
                        $('#NPDR').html('-');
                        $('#NPDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].npdr == '0') {
                        $('#NPDR').html('-');
                        $('#NPDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].npdr == '1') {
                        $('#NPDR').html('None');
                        $('#NPDR_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].npdr == '2') {
                        $('#NPDR').html('Mild');
                        $('#NPDR_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].npdr == '3') {
                        $('#NPDR').html('Moderate');
                        $('#NPDR_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].npdr == '4') {
                        $('#NPDR').html('Severe');
                        $('#NPDR_head').addClass('dash-notify-below');
                    }
                    if (data.Table1[0].neuropathy_flag == '' || data.Table1[0].npdr == null || data.Table1[0].npdr == 0) {
                        $('#PNeuropathy').html('-');
                        $('#PNeuropathy_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].neuropathy_flag == '1') {
                        $('#PNeuropathy').html('Normal');
                        $('#PNeuropathy_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].neuropathy_flag == '2') {
                        $('#PNeuropathy').html('Mild');
                        $('#PNeuropathy_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].neuropathy_flag == '3') {
                        $('#PNeuropathy').html('Moderate');
                        $('#PNeuropathy_head').addClass('dash-notify-above');
                    }
                    else if (data.Table1[0].neuropathy_flag == '4') {
                        $('#PNeuropathy').html('Severe');
                        $('#PNeuropathy_head').addClass('dash-notify-below');
                    }
                    if (data.Table1[0].autonomic_neuropathy == '' || data.Table1[0].autonomic_neuropathy == null) {
                        $('#ANeuropathy').html('-');
                        $('#ANeuropathy_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].autonomic_neuropathy == '0') {
                        $('#ANeuropathy').html('Absent');
                        $('#ANeuropathy_head').addClass('dash-notify-normal');
                    }
                    else if (data.Table1[0].autonomic_neuropathy == '1') {
                        $('#ANeuropathy').html('Present');
                        $('#ANeuropathy_head').addClass('dash-notify-below');
                    }
                }
                if (data.Table2.length > 0) {
                    if ($.trim(data.Table2[0].treatment_history_notes) == '' || data.Table2[0].treatment_history_notes == null) {
                        $('#THistory').html('Add Note');
                    }
                    else {
                        $('#THistory').html(data.Table2[0].treatment_history_notes);
                    }
                    if ($.trim(data.Table2[0].surgery_history_notes) == '' || data.Table2[0].surgery_history_notes == null) {
                        $('#SHistory').html('Add Note');
                    }
                    else {
                        $('#SHistory').html(data.Table2[0].surgery_history_notes);
                    }
                }
                else {
                    $('#THistory').html('Add Note');
                    $('#SHistory').html('Add Note');
                }
                if (data.Table3.length > 0) {
                    var Angina = data.Table3[0].history_angina;
                    var CHD = data.Table3[0].coronary_heart_disease;
                    var CVA = data.Table3[0].CVA;
                    var PAD = data.Table3[0].history_pad;

                    if (Angina == 1) {
                        $('#Angina').prop('checked', true);
                        $("#Angina").click();
                    }
                    if (CHD == 1) {
                        $('#CoronaryHeart').prop('checked', true);
                        $("#CoronaryHeart").click();
                    }
                    if (CVA == 1) {
                        $('#CVA').prop('checked', true);
                        $("#CVA").click();
                    }
                    if (PAD == 1) {
                        $('#PAD').prop('checked', true);
                        $("#PAD").click();
                    }
                    if ($.trim(data.Table3[0].personal_history) == '' || data.Table3[0].personal_history == null) {
                        $('#PHistory').html('Add Note');
                    }
                    else {
                        $('#PHistory').html(data.Table3[0].personal_history);
                    }
                }
                else {
                    $('#PHistory').html('Add Note');
                }
                if (data.Table4.length > 0) {
                    $('#lab_id').val(data.Table4[0].lab_id);
                }

                if (data.Table5.length > 0) {
                    for (var i = 0; i < data.Table5.length; i++) {
                        var relationship = '';
                        var disease = '', notesfamily, noofyear;
                        if (data.Table5[i].relationship == 1) {
                            relationship = 'Father';
                        }
                        else if (data.Table5[i].relationship == 2) {
                            relationship = 'Mother';
                        }
                        else if (data.Table5[i].relationship == 3) {
                            relationship = 'Brother';
                        }
                        else if (data.Table5[i].relationship == 4) {
                            relationship = 'Sister';
                        }
                        else if (data.Table5[i].relationship == 5) {
                            relationship = 'Paternal GrandFather';
                        }
                        else if (data.Table5[i].relationship == 6) {
                            relationship = 'Paternal GrandMother';
                        }
                        else if (data.Table5[i].relationship == 7) {
                            relationship = 'Maternal GrandFather';
                        }
                        else if (data.Table5[i].relationship == 8) {
                            relationship = 'Maternal GrandMother';
                        }
                        else if (data.Table5[i].relationship == 9) {
                            relationship = 'Both Parents';
                        }
                        else if (data.Table5[i].relationship == 10) {
                            relationship = 'All Family number';
                        }
                        else {
                            relationship = '';
                        }
                        if (data.Table5[i].disease == 1) {
                            disease = 'CVA';
                        }
                        else if (data.Table5[i].disease == 2) {
                            disease = 'Thyroid';
                        }
                        else if (data.Table5[i].disease == 3) {
                            disease = 'Hypertension';
                        }
                        else if (data.Table5[i].disease == 4) {
                            disease = 'Diabetes';
                        }
                        else if (data.Table5[i].disease == 5) {
                            disease = 'Cardiac Diseases';
                        }
                        else if (data.Table5[i].disease == 6) {
                            disease = 'Cancer';
                        }
                        else if (data.Table5[i].disease == 7) {
                            disease = 'Renal Diseases';
                        }
                        else {
                            disease = '';
                        }
                        if (data.Table5[i].no_of_years == null || data.Table5[i].no_of_years == "") noofyear = "-";
                        else noofyear = data.Table5[i].no_of_years;
                        if (data.Table5[i].name == null || data.Table5[i].name == "") notesfamily = '-';
                        else notesfamily = data.Table5[i].name;
                        tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn addicon-btn btn-sm mr20" onclick="familyedit(' + data.Table5[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" onclick="familydelete(' + data.Table5[i].patient_family_history_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                    }
                    $('#tbl_family_body').html(tr);
                }

                if (data.Table6.length > 0) {
                    var date = '';
                    var trr = '', weight_g = [], weight_d = [];
                    for (var i = 0; i < data.Table6.length; i++) {
                        weight_g.push(data.Table6[i].patient_weight);
                        weight_d.push(data.Table6[i].weight_date)
                        if (data.Table6[i].weight_date != '' && data.Table6[i].weight_date != null && data.Table6[i].patient_weight != null && data.Table6[i].patient_weight != '') {
                            date = data.Table6[i].weight_date;
                            trr = trr + '<tr><td>' + data.Table6[i].weight_date + '</td><td>' + data.Table6[i].patient_weight + ' kg</td></tr>';
                        }
                    }
                    $('#weightlist').html(trr);
                    graph1_bpbsall(weight_g, weight_d, 'bmichartview', 'Date');
                }

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

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

                if (data.Table8.length > 0) {
                    if ($('#txtComplaints_1').hasClass('tag-editor-hidden-src')) {   // check whether it is tag editor or normal text area
                        var complaintsVal = [];
                        for (var i = 0; i < data.Table8.length; i++) {
                            complaintsVal.push(data.Table8[i].complaints);
                        }
                        console.log(complaintsVal);
                        $('#txtComplaints_1').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            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.toUpperCase(), '1');
                            // console.log(val);
                            // copy_complaints(val);
                        }
                        function beforeTagDeletecb(field, editor, tags, val) {
                            return true;
                        }
                    }
                }
                if (data.Table9.length > 0) {
                    if ($('#txtdiagnosis').hasClass('tag-editor-hidden-src')) {
                        var diagnosisVal = [];
                        for (var i = 0; i < data.Table9.length; i++) {
                            diagnosisVal.push(data.Table9[i].diagnosis);
                        }
                        $('#txtdiagnosis').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            maxLength: 250,
                            autocomplete: {
                                delay: 0,
                                position: {
                                    collision: 'flip'
                                },
                                source: diagnosisVal
                            },
                            clickDelete: false,
                            beforeTagSave: beforeTagSavecb,
                            beforeTagDelete: beforeTagDeletecb,
                            onChange: onChangecb
                        });

                        function onChangecb(field, editor, tags) {
                        }
                        function beforeTagSavecb(field, editor, tags, tag, val) {
                            diagnosis_insert(val);
                        }
                        function beforeTagDeletecb(field, editor, tags, val) {
                            return true;
                        }
                        $('#divtxtdiagnosis > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                    }
                }
                if (data.Table10.length > 0) {
                    if ($('#txtnotes_1').hasClass('tag-editor-hidden-src')) {
                        var notesVal = [];

                        for (var i = 0; i < data.Table10.length; i++) {
                            notesVal.push(data.Table10[i].notes);

                        }
                        console.log(notesVal);
                        $('#txtnotes_1').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            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.Table11.length > 0) {
                    if ($('#txt_visit_instruction').hasClass('tag-editor-hidden-src')) {
                        var instructionVal = [];

                        for (var i = 0; i < data.Table11.length; i++) {
                            instructionVal.push(data.Table11[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.Table12.length > 0) {
                    if ($('#txtXrayFindings').hasClass('tag-editor-hidden-src')) {
                        var investigationVal = [];

                        for (var i = 0; i < data.Table12.length; i++) {
                            investigationVal.push(data.Table12[i].investigation);

                        }
                        console.log(investigationVal);
                        $('#txtXrayFindings').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            maxLength: 250,
                            forceLowercase: false,
                            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.Table13.length > 0) {
                    if ($('#txtAdvice').hasClass('tag-editor-hidden-src')) {
                        var adviceVal = [];

                        for (var i = 0; i < data.Table13.length; i++) {
                            adviceVal.push(data.Table13[i].advice);

                        }
                        console.log(adviceVal);
                        $('#txtAdvice').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            forceLowercase: false,
                            maxLength: 250,
                            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.Table14.length > 0) {
                    if ($('#txtprodcedure').hasClass('tag-editor-hidden-src')) {
                        var proceduresVal = [];

                        for (var i = 0; i < data.Table14.length; i++) {
                            proceduresVal.push(data.Table14[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.Table15.length > 0) {
                    if ($('#txtCounselling').hasClass('tag-editor-hidden-src')) {
                        var cousellingVal = [];

                        for (var i = 0; i < data.Table15.length; i++) {
                            cousellingVal.push(data.Table15[i].couselling);

                        }
                        console.log(cousellingVal);
                        $('#txtCounselling').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            forceLowercase: false,
                            maxLength: 250,
                            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;
                        }
                    }

                }
                console.log(data.Table16);
                //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;
                        }
                    }
                }

                //xray finding
                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;
                        }
                    }
                }

                if (data.Table18.length > 0) {
                    $('#lab_data_flag').val(data.Table18[0].data_flag);


                }
                else {
                    $('#lab_data_flag').val('0');
                }
                if (data.Table19.length > 0) {
                    $('#phy_data_flag').val(data.Table19[0].data_flag);
                }
                else {
                    $('#phy_data_flag').val('0');
                }

                //mri finding
                if (data.Table20.length > 0) {
                    if ($('#txtmrifinding').hasClass('tag-editor-hidden-src')) {
                        var mrifinVal = [];

                        for (var i = 0; i < data.Table20.length; i++) {
                            mrifinVal.push(data.Table20[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.Table21.length > 0) {
                    if ($('#txtobserv').hasClass('tag-editor-hidden-src')) {
                        var observationVal = [];

                        for (var i = 0; i < data.Table21.length; i++) {
                            observationVal.push(data.Table21[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.Table22.length > 0) {
                    if ($('#txtinvetig').hasClass('tag-editor-hidden-src')) {
                        var investigationVal = [];

                        for (var i = 0; i < data.Table22.length; i++) {
                            investigationVal.push(data.Table22[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.Table23.length > 0) {
                    if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                        var reviewnotesVal = [];

                        for (var i = 0; i < data.Table23.length; i++) {
                            reviewnotesVal.push(data.Table23[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')) {

                        $('#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.Table24.length > 0) {
                    if ($('#txtpastadverseevents').hasClass('tag-editor-hidden-src')) {
                        var significant_adverseVal = [];

                        for (var i = 0; i < data.Table24.length; i++) {
                            significant_adverseVal.push(data.Table24[i].significant_adverse);

                        }
                        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.Table25.length > 0) {
                    if ($('#txtgeneralexamination').hasClass('tag-editor-hidden-src')) {
                        var general_examVal = [];

                        for (var i = 0; i < data.Table25.length; i++) {
                            general_examVal.push(data.Table25[i].general_exam);

                        }
                        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.Table26.length > 0) {
                    if ($('#txtlocalexamination').hasClass('tag-editor-hidden-src')) {
                        var local_examVal = [];

                        for (var i = 0; i < data.Table26.length; i++) {
                            local_examVal.push(data.Table26[i].local_exam);

                        }
                        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.Table27.length > 0) {
                    if ($('#txtabdomengirth').hasClass('tag-editor-hidden-src')) {
                        var abdomenVal = [];

                        for (var i = 0; i < data.Table27.length; i++) {
                            abdomenVal.push(data.Table27[i].abdomen);

                        }
                        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.Table28.length > 0) {
                    $('#medicinefrequency').empty();
                    $('#medicinefrequency_edit').empty();
                    trs = '';
                    var defaultoption = '<option value="0">--select--</option>';
                    frequencyarray = data.Table28;
                    loadfrequencytype(frequencyarray);
                    for (var i = 0; i < data.Table28.length; i++) {
                        trs = trs + '<option value="' + data.Table28[i].frequency_master_id + '">' + data.Table28[i].frequency_name + '</option>';
                    }
                    $('#medicinefrequency').append(defaultoption + trs);
                    // $('.medicinefrequency').append(defaultoption + trs);
                    $('#medicinefrequency_edit').append(defaultoption + trs);
                }

                bp_blood_step_chart();
                //F;
            }

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

            if ($('#doctor_appointment_slot_status').val() == 7) {
                VisitreportId();
                casesheet_select();
            }

            if ($('#EditVisitReportID').val() != '') {
                casesheet_select();

                EditEngage();
                if ($('#appointment_type').val() == 2) {
                    $('#btnvideocall').show();
                    $('#btnvideocall_1').show();
                    $('#btnclicktocall_1').show();
                }
                else {
                    $('#btnvideocall').hide();
                    $('#btnvideocall_1').hide();
                    $('#btnclicktocall_1').hide();
                }
            }
            else {
                VisitreportId();
            }

            PatientNeuropathyLoad();
        }

    });
    if ($('#HProductCode').val() == 2 || $('#HProductCode').val() == 3) {
        $("#csTab_14 a").click();
    }
}

function bp_blood_step_chart() {
    debugger;
    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,
        Dml_Indicator: '2',
        Doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    var BPMin = [], BPMax = [], BPlabel = [], FBS = [], PBS = [], FBSlabel = [], stepVal = [], stepDate = [];
                    if (data.Table.length > 0) {
                        for (var i = 0; i < data.Table.length; i++) {
                            BPMin.push(data.Table[i].patient_bp_min);
                            BPlabel.push(data.Table[i].Pdate);
                        }
                    }
                    if (data.Table1.length > 0) {
                        for (var i = 0; i < data.Table1.length; i++) {
                            BPMax.push(data.Table1[i].patient_bp_max);
                        }
                    }
                    if (data.Table2.length > 0) {
                        for (var i = 0; i < data.Table2.length; i++) {
                            FBS.push(data.Table2[i].patient_blood_sugar_value);
                            FBSlabel.push(data.Table2[i].Pdate)
                        }
                    }
                    if (data.Table3.length > 0) {
                        for (var i = 0; i < data.Table3.length; i++) {
                            PBS.push(data.Table3[i].patient_blood_sugar_value);
                        }
                    }
                    if (data.Table4.length > 0) {
                        for (var i = 0; i < data.Table4.length; i++) {
                            stepVal.push(data.Table4[i].patient_step_record_achieved);
                            stepDate.push(data.Table4[i].Pdate)
                        }
                    }
                    var QL = [], HF = [], QLlabel = [], MA = [], MAlabel = [], HFlabel = [];

                    //commented by nandhini on 26/12/2022 because its temporarly hided in html page
                    //if (data.Table5.length > 0) {
                    //    for (var i = 0; i < data.Table5.length; i++) {
                    //        HF.push(data.Table5[i].score);
                    //        HFlabel.push(data.Table5[i].date);
                    //    }
                    //}

                    //if (data.Table6.length > 0) {
                    //    for (var i = 0; i < data.Table6.length; i++) {
                    //        QL.push(data.Table6[i].score);
                    //        QLlabel.push(data.Table6[i].date)
                    //    }
                    //}

                    //if (data.Table7.length > 0) {
                    //    for (var i = 0; i < data.Table7.length; i++) {
                    //        MA.push(data.Table7[i].score);
                    //        MAlabel.push(data.Table7[i].date)
                    //    }
                    //}

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

            graph2(BPMin, BPMax, BPlabel, 'chartBP', 'Systolic', 'Diastolic');
            graph2(FBS, PBS, FBSlabel, 'chartsugar', 'Fasting blood sugar', 'Postponed blood sugar');
            graph1(stepVal, stepDate, 'chartstep', 'Date');

            //commented by nandhini on 26/12/2022 because its temporarly hided in html page
            // graph1(HF, HFlabel, 'charthf', 'score');
            // graph1(QL, QLlabel, 'chartqa', 'score');
            // graph1(MA, MAlabel, 'chartm','score');

            debugger;
            if ($('#EditVisitReportID').val() != '') {

            }
            else {
                $('.da-load-casestudy').hide();
            }
            diagonsislist();
        }

    });
}

$('#chartBP,#chartstep,#chartsugar').click(function (e) {
    debugger;
    bp_blood_step_chart_overall(e.target.id);
});

function bp_blood_step_chart_overall(domid) {
    debugger;
    $('#loaderimg').show();
    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,
        Dml_Indicator: '100',
        Doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;

                if (jQuery.isEmptyObject((data))) {
                    $('#loaderimg').hide();
                }
                else {
                    var BPMin = [], BPMax = [], BPlabel = [], FBS = [], PBS = [], FBSlabel = [], stepVal = [], stepDate = [];
                    if (data.Table.length > 0) {
                        for (var i = 0; i < data.Table.length; i++) {
                            BPMin.push(data.Table[i].patient_bp_min);
                            BPlabel.push(data.Table[i].Pdate);
                        }
                    }
                    if (data.Table1.length > 0) {
                        for (var i = 0; i < data.Table1.length; i++) {
                            BPMax.push(data.Table1[i].patient_bp_max);
                        }
                    }
                    if (data.Table2.length > 0) {
                        for (var i = 0; i < data.Table2.length; i++) {
                            FBS.push(data.Table2[i].patient_blood_sugar_value);
                            FBSlabel.push(data.Table2[i].Pdate)
                        }
                    }
                    if (data.Table3.length > 0) {
                        for (var i = 0; i < data.Table3.length; i++) {
                            PBS.push(data.Table3[i].patient_blood_sugar_value);
                        }
                    }
                    if (data.Table4.length > 0) {
                        for (var i = 0; i < data.Table4.length; i++) {
                            stepVal.push(data.Table4[i].patient_step_record_achieved);
                            stepDate.push(data.Table4[i].Pdate)
                        }
                    }
                }

            }
            else {
                console.log(data);
            }
            if (domid === "chartBP") {
                $('#bptablevalues').empty();
                graph2_bpbsall(BPMin, BPMax, BPlabel, 'chartBP1', 'Systolic', 'Diastolic');
                if (data.Table5.length > 0) {
                    var j = 0, bp_data_table;
                    var bp_data_table = data.Table5;
                    tr = $('<table class="table table-bordered table-striped dataTable" id="bp_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Systolic Value</th><th>Diastolic Value</th><th>Updated Date</th></tr></thead><tbody>");
                    $.each(bp_data_table, function (i, emp) {
                        j++;
                        row_data = "<tr><td>" + j + "</td><td>" + emp.patient_bp_max + "</td><td>" + emp.patient_bp_min + "</td><td>" + emp.updated_date + "</td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    $.when($('#bptablevalues').append(tr)).then($('#bp_table').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                }
                else {
                    tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="bp_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Systolic Value</th><th>Diastolic Value</th><th>Updated Date</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
            }

            if (domid === "chartsugar") {
                debugger;
                graph2_bpbsall(FBS, PBS, FBSlabel, 'chartsugar1', 'Fasting blood sugar', 'Postponed blood sugar');
                $('#bsvaluetable').empty();
                if (data.Table6.length > 0) {
                    var j = 0, bs_data_table, fbs = '-', pps = '-', k = 0;
                    var bs_data_table = data.Table6;
                    var bs_data_table_1 = data.Table7;
                    tr = $('<table class="table table-bordered table-striped dataTable" id="bs_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Fasting Blood Sugar</th><th>Postprandial Blood Sugar</th><th>Updated Date</th></tr></thead><tbody>");
                    for (var i = 0; i < bs_data_table.length; i++) {
                        if (k < bs_data_table_1.length) {
                            if (bs_data_table[i]["updated_date"] == bs_data_table_1[k]["updated_date"]) {
                                fbs = bs_data_table[i]["patient_blood_sugar_value"];
                                pps = bs_data_table_1[k]["patient_blood_sugar_value"];
                                j++;
                                row_data = "<tr><td>" + j + "</td><td>" + fbs + "</td><td>" + pps + "</td><td>" + bs_data_table[i]["updated_date"] + "</td></tr>";
                                tr.append(row_data);
                                k = k + 1;
                            }
                            else {
                                fbs = bs_data_table[i]["patient_blood_sugar_value"];
                                pps = '-'
                                j++;
                                row_data = "<tr><td>" + j + "</td><td>" + fbs + "</td><td>" + pps + "</td><td>" + bs_data_table[i]["updated_date"] + "</td></tr>";
                                tr.append(row_data);
                                fbs = '-'
                                pps = bs_data_table_1[k]["patient_blood_sugar_value"];
                                j++;
                                row_data = "<tr><td>" + j + "</td><td>" + fbs + "</td><td>" + pps + "</td><td>" + bs_data_table_1[k]["updated_date"] + "</td></tr>";
                                tr.append(row_data);
                                k = k + 1;
                            }
                        }
                        else {
                            fbs = bs_data_table[i]["patient_blood_sugar_value"];
                            pps = '-'
                            j++;
                            row_data = "<tr><td>" + j + "</td><td>" + fbs + "</td><td>" + pps + "</td><td>" + bs_data_table[i]["updated_date"] + "</td></tr>";
                            tr.append(row_data);
                            k = k + 1;
                        }
                    }
                    tr.append("</tbody>");
                    $.when($('#bsvaluetable').append(tr)).then($('#bs_table').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                }
                else {
                    tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="bs_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Fasting Blood Sugar</th><th>Postprandial Blood Sugar</th><th>Updated Date</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
            }
            if (domid === "chartstep") {
                graph1_bpbsall(stepVal, stepDate, 'chartstep1', 'Date');
                $('#setpvaluetable').empty();
                if (data.Table8.length > 0) {
                    var j = 0, step_data_table;
                    var step_data_table = data.Table8;
                    tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="step_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Steps Count</th><th>Updated Date</th></tr></thead><tbody>");
                    $.each(step_data_table, function (i, emp) {
                        j++;
                        row_data = "<tr><td>" + j + "</td><td>" + emp.patient_step_record_achieved + "</td><td>" + emp.updated_date + "</td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    $.when($('#setpvaluetable').append(tr)).then($('#step_table').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                }
                else {
                    tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="step_table" />');
                    tr.append("<thead><tr><th>S No</th><th>Systolic Value</th><th>Diastolic Value</th><th>Updated Date</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
            }
            $('#loaderimg').hide();
            if ($('#EditVisitReportID').val() != '') {
            }
            else {
            }
        }

    });
}

// edit mode data start

function casesheet_select() {
    debugger;
    if ($('#HProductCode').val() == 2 || $('#HProductCode').val() == 3) {
        $("#csTab_14 a").click();
    }
    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
    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: $('#doctorId').val(),
        Visit_report_id: $('#EditVisitReportID').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);
            console.log(data);
            if (data.msg == "Success") {
                //observation
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (data.Table.length > 0) {
                        var current_complaints = data.Table[0].current_complaints;
                        if ($('#txtComplaints_1').hasClass('tag-editor-hidden-src')) {
                            if (current_complaints == '' || current_complaints == null) {

                            }
                            else {

                                var complaints = current_complaints.split(',');
                                var tr = [];
                                console.log(complaints);
                                var tags = $('#txtComplaints_1').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtComplaints_1').tagEditor('removeTag', tags[i]); }
                                if (complaints.length > 0) {
                                    for (var i = 0; i < complaints.length; i++) {
                                        tr.push(complaints[i]);
                                    }
                                }
                                $('#txtComplaints_1').tagEditor('addTag', tr);
                            }

                        }
                        else {
                            $('#txtComplaints_1').val(current_complaints);
                        }

                        var notes = data.Table[0].note;
                        if ($('#txtnotes_1').hasClass('tag-editor-hidden-src')) {
                            if (notes == '' || notes == null) {

                            }
                            else {
                                var notes = notes.split(',');
                                var tr = [];
                                console.log(notes);
                                var tags = $('#txtnotes_1').tagEditor('getTags')[0].tags;
                                for (i = 0; i < tags.length; i++) { $('#txtnotes_1').tagEditor('removeTag', tags[i]); }
                                if (notes.length > 0) {
                                    for (var i = 0; i < notes.length; i++) {
                                        tr.push(notes[i]);
                                    }
                                }
                                $('#txtnotes_1').tagEditor('addTag', tr);
                            }
                        }
                        else {
                            $('#txtnotes_1').val(notes);
                        }
                        $("#btnOSave").html('Update & Next');

                        $('#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');


                        $('#txtPulseRate').val(data.Table[0].pulse_rate);
                        $('#txtHeartRate').val(data.Table[0].heart_rate);

                        $('#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);
                        $('#txtnotes_1').val(data.Table[0].note);
                        $('#txtSPO2').val(data.Table[0].spo2);
                        $('#txtTemperature').val(data.Table[0].temperature);
                        $('input[name="optradioConsciences"][value="' + data.Table[0].level_of_conscience + '"]').prop('checked', true);
                        $('#txtRespiratoryRate').val(data.Table[0].respiratory_rate);
                    }
                    //bp
                    if (data.Table1.length > 0) {
                        $('#txtSys').val(data.Table1[0].patient_bp_max);
                        $('#txtDia').val(data.Table1[0].patient_bp_min);
                    }
                    //Glycemic_type_1
                    if (data.Table2.length > 0) {

                        $("#btntype1").html('Update')
                        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;

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

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

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

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

                        $('#txtFasting').val(txtFasting);
                        $('#txtSimulated').val(txtSimulated);
                    }

                    //Glycemic ParametersBasic
                    if (data.Table3.length > 0) {
                        $('#txtHB').val(data.Table3[0].hemoglobin);
                        $('#txtfastingInsulin').val(data.Table3[0].fasting_insulin);
                        $('#txtfastingInsulin_T').val(data.Table3[0].fasting_inslin_unit);
                        $('#txtnotes_glycemic').val(data.Table3[0].note);
                        $('#txtWBC').val(data.Table3[0].WBC);
                        $('#txtPlatelets').val(data.Table3[0].platelet);
                        $('#txtKetones').val(data.Table3[0].se_ketones);

                    }

                    //Glycemic Parameters HBA1C
                    if (data.Table4.length > 0) {
                        $('#txtHbA1c').val(data.Table4[0].patient_hbac_record_value);
                    }
                    debugger;
                    //Glycemic HBA1C
                    if (data.Table5.length > 0) {

                        for (var i = 0; i < data.Table5.length; i++) {
                            $('#txtBloodsugarV_' + data.Table5[i].patient_blood_sugar_type).val(data.Table5[i].patient_blood_sugar_value);
                            $('#txtBloodsugarT_' + data.Table5[i].patient_blood_sugar_type).val(data.Table5[i].patient_blood_sugar_unit);

                        }
                    }
                    if (data.Table2.length > 0 || data.Table3.length > 0 || data.Table4.length > 0 || data.Table5.length > 0) {
                        $("#btnGlycemic").html('Update & Next');
                    }

                    // renal
                    if (data.Table6.length > 0) {
                        $("#btnRenal").html('Update & Next');
                        $('#txtUrea').val(data.Table6[0].Urea);
                        $('#SelUrea').val(data.Table6[0].urea_unit);
                        $('#txtCreatinine').val(data.Table6[0].creatinine);
                        $('#SelCreatinine').val(data.Table6[0].Creatinine_unit);
                        //commented and added by nandhini, from medway
                        //$('#txtEGFR').val(data.Table6[0].egfr_value);
                        if (data.Table6[0].egfr_value == "0") {
                            $('#txtEGFR').val("Infinity");
                        }
                        else {
                            $('#txtEGFR').val(data.Table6[0].egfr_value);
                        }
                        $('#txtSodium').val(data.Table6[0].Sodium);
                        $('#SelSodium').val(data.Table6[0].sodium_unit);
                        $('#txtPotassium').val(data.Table6[0].Potassium);
                        $('#SelPotassium').val(data.Table6[0].potassium_unit);
                        $('#txtChlorine').val(data.Table6[0].Chlorine);
                        $('#SelChlorine').val(data.Table6[0].chlorine_unit);
                        $('#txtBiCrabonate').val(data.Table6[0].BiCarbonate);
                        $('#SelBicrabonate').val(data.Table6[0].Bicarbonate_unit);
                        $('#txtCalcium').val(data.Table6[0].serium_calcium);
                        $('#SelCalcium').val(data.Table6[0].Calcium_unit);
                        $('#txtPhosphorus').val(data.Table6[0].serium_phosphorous);
                        $('#SelPhosphorus').val(data.Table6[0].Phosphorus_unit);
                        $('#txtMagnesium').val(data.Table6[0].serium_magnesium);
                        $('#SelMagnesium').val(data.Table6[0].Magnesium_unit);
                        $('#txtnotes_renal').val(data.Table6[0].note);
                    }
                    //renal casesheet
                    if (data.Table7.length > 0) {
                        var ACR = data.Table7[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.Table7[0].nephropathy;

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

                        var txtCKDVal = data.Table7[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');
                        }
                        var DCCKD = $('#txtCKD').val();
                        $('#DKindly').html(DCCKD);

                    }

                    //Cholestrol
                    if (data.Table8.length > 0) {
                        $("#btncholestrol").html('Update & Next');
                        $('#txtLDL').val(data.Table8[0].LDL);
                        $('#SelLDL').val(data.Table8[0].LDL_unit);
                        $('#txtTCholesterol').val(data.Table8[0].Total_Cholestrol);
                        $('#SelTCholesterol').val(data.Table8[0].Total_cholestrol_unit);
                        $('#txtVLDL').val(data.Table8[0].VLDL);
                        $('#SelVLDL').val(data.Table8[0].VLDL_unit);
                        $('#txtHDL').val(data.Table8[0].HDL);
                        $('#SeltxtHDL').val(data.Table8[0].HDL_unit);
                        $('#txtTriglycerides').val(data.Table8[0].Triglycerides);
                        $('#SelTriglycerides').val(data.Table8[0].Triglycerides_unit);
                        $('#txtHDLRatio').val(data.Table8[0].T_cholestrol_Hdl_ratio);
                        $('#txtNHDL').val(data.Table8[0].NHDL);
                        $('#SelNHDL').val(data.Table8[0].NHDL_unit);
                        $('#txtnotes_cholesterol').val(data.Table8[0].note);
                    }
                    //Cholestrol casesheet
                    if (data.Table9.length > 0) {
                        var ChkDyslipidemia = data.Table9[0].dyslipedemia;

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

                    }

                    //Opthal
                    if (data.Table10.length > 0) {
                        $("#BtnOpthal").html('Update & Next');
                        $('#dpd12').val(data.Table10[0].last_observation_date);
                        $('#dpd2').val(data.Table10[0].next_suggested_appointment);
                        $('#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);
                        $('#NPDRradio').val(npdr);
                        $('a[data-toggle=NPDRradio][data-title="' + npdr + '"]').addClass('active');

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

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

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

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

                    //cardiac
                    if (data.Table12.length > 0) {
                        $("#btnCardiac").html('Update & Next');
                        $('#txtecg').val(data.Table12[0].ECG);
                        $('#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);
                        $('#txtnotes_cardiac').val(data.Table12[0].note);

                        $('#txtnotes_ASD').val(data.Table12[0].ASD);
                        $('#txtnotes_VSD').val(data.Table12[0].VSD);
                        $('#txtnotes_value').val(data.Table12[0].C_value);
                        $('#txtnotes_Ejection').val(data.Table12[0].fraction);
                        $('#txtnotes_Mitral').val(data.Table12[0].mitral_value);
                        $('#txtnotes_lotic').val(data.Table12[0].lotic_value);
                        $('#txtnotes_Tricuspid').val(data.Table12[0].tricuspid);
                        $('#txtnotes_Pulmonary').val(data.Table12[0].pulmonary);

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


                        if (ecg_abnormal == '1') {
                            $("#Chkecg").prop('checked', true);
                            $("#Chkecg").click();
                        }
                        if (echo_abnormal == '1') {
                            $("#Selecho").prop('checked', true);
                            $("#Selecho").click();
                        }
                        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;
                        }
                        $('#txtDrugs').val(txtDrugs);
                        $('a[data-toggle=txtDrugs][data-title="' + txtDrugs + '"]').removeClass('not-active');
                        $('a[data-toggle=txtDrugs][data-title="' + txtDrugs + '"]').addClass('active');

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

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

                    //Neuropathy
                    if (data.Table13.length > 0) {
                        debugger;
                        var chkANeuropathy = (data.Table13[0].autonomic_neuropathy);
                        $('#chkANeuropathy').val(chkANeuropathy);
                        $('a[data-toggle=chkANeuropathy][data-title="' + chkANeuropathy + '"]').addClass('active');
                    }
                    //Neuropathy casesheet
                    if (data.Table14.length > 0) {

                        $("#btnNeuropathy").html('Update & Next')
                        $('#txtDoppler').val(data.Table14[0].doppler_note);
                        $('#txtnotes_neuropathy').val(data.Table14[0].note);
                        var PeripheralNeuropathy = data.Table14[0].peripharal_neuhropathy;
                        var ABIndex = data.Table14[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');
                    }
                    // cardiac coronary desease
                    if (data.Table15.length > 0) {
                        debugger;
                        $("#btnCardiac").html('Update & Next');

                        $('#L_txtLMCA').val(data.Table15[0].L_LAD);
                        $('#L_LMCAradio').val(data.Table15[0].L_LAD_type);
                        $('a[data-toggle=L_LMCAradio][data-title="' + data.Table15[0].L_LAD_type + '"]').addClass('active');

                        $('#L_txtLAD').val(data.Table15[0].L_LCX);
                        $('#L_LADradio').val(data.Table15[0].L_LCX_type);
                        $('a[data-toggle=L_LADradio][data-title="' + data.Table15[0].L_LCX_type + '"]').addClass('active');

                        $('#L_txtlcx').val(data.Table15[0].L_RCA);
                        $('#L_lcxradio').val(data.Table15[0].L_RCA_type);
                        $('a[data-toggle=L_lcxradio][data-title="' + data.Table15[0].L_RCA_type + '"]').addClass('active');


                        $('#R_txtlad').val(data.Table15[0].R_LAD);
                        $('#R_ladradio').val(data.Table15[0].R_LAD_type);
                        $('a[data-toggle=R_ladradio][data-title="' + data.Table15[0].R_LAD_type + '"]').addClass('active');

                        $('#R_txtlcx').val(data.Table15[0].R_LCX);
                        $('#R_lcxradio').val(data.Table15[0].R_LCX_type);
                        $('a[data-toggle=R_lcxradio][data-title="' + data.Table15[0].R_LCX_type + '"]').addClass('active');

                        $('#R_txtrca').val(data.Table15[0].R_RCA);
                        $('#R_rcaradio').val(data.Table15[0].R_RCA_type);
                        $('a[data-toggle=R_rcaradio][data-title="' + data.Table15[0].R_RCA_type + '"]').addClass('active');
                    }

                    //thyroid
                    if (data.Table16.length > 0) {
                        $("#btnThyroid").html('Update & Next')
                        $('#txtT3').val(data.Table16[0].Free_T3);
                        $('#txtT4').val(data.Table16[0].Free_T4);
                        $('#N_txtT3').val(data.Table16[0].T3);
                        $('#N_txtT4').val(data.Table16[0].T4);
                        $('#txtTSH').val(data.Table16[0].TSH);
                        $('#txtnotes_thyroid').val(data.Table16[0].note);
                        Interpretation();
                    }
                    //ultrasound
                    if (data.Table17.length > 0) {

                        $("#btnUltraSound").html('Update & Next');
                        $('#txtNotes').val(data.Table17[0].notes);
                        var chkLiver = (data.Table17[0].fatty_lives);
                        var chkGS = (data.Table17[0].GS_Calculus);
                        $('#txtUNotes').val(data.Table17[0].USNotes);
                        $('#ctsnotes').val(data.Table17[0].cts_notes);
                        $('#chkLiver').val(chkLiver);
                        $('a[data-toggle=chkLiver][data-title="' + chkLiver + '"]').addClass('active');

                        $('#chkGS').val(chkGS);
                        $('a[data-toggle=chkGS][data-title="' + chkGS + '"]').addClass('active');
                    }
                    //liver function test
                    if (data.Table18.length > 0) {

                        $('#txtSerum_Bilirubin_Total').val(data.Table18[0].serum_bilirubin_total);
                        $('#txtSerum_Bilirubin_Direct').val(data.Table18[0].serum_bilirubin_direct);
                        $('#txtBilirubin_Indirect').val(data.Table18[0].bilirubin_indirect);
                        $('#txtSerum_Protein_Total').val(data.Table18[0].serum_protein_total);
                        $('#txtSerum_Protein_Albumin').val(data.Table18[0].serum_protein_albumin);
                        $('#txtSerum_Protein_Glibulin').val(data.Table18[0].serumproteinglibulin);
                        $('#txtSGOT').val(data.Table18[0].SGOT);
                        $('#txtSGPT').val(data.Table18[0].SGPT);
                        $('#txtSerum_Alkaline_Phosphatase').val(data.Table18[0].serum_alkaline_phosphatase);
                        $('#txtGamma_Glutamyl_Transpeptidase').val(data.Table18[0].gamma_glutamyl_transpeptidase);
                        $('#txtSerum_Magnesium').val(data.Table18[0].serum_magnesium);

                    }
                    //cbc

                    if (data.Table21.length > 0) {

                        $("#btnCBC").html('Update & Next');
                        $('#txtCBCHemoglobin').val(data.Table21[0].hemoglobin),
                            $('#txtCBCHemoglobinUnit').val(data.Table21[0].hemoglobin_unit),
                            $('#txtNucleatedBloodcell').val(data.Table21[0].nucleated_red_blood_cells),
                            $('#txtNucleatedBloodcellPercent').val(data.Table21[0].nucleated_red_blood_cells_percent),
                            $('#txtHematocrit').val(data.Table21[0].hematocrit),
                            $('#txtPlateletCount').val(data.Table21[0].platelet_count),
                            $('#txtPlateletCountUnit').val(data.Table21[0].platelet_count_unit),
                            $('#txtTotalLeucocytesCount').val(data.Table21[0].total_leucocytes_count),
                            $('#txtLymphocytePercent').val(data.Table21[0].lymphocyte_percent),
                            $('#txtMeanCorpuscular').val(data.Table21[0].mean_corpuscular_hemoglobin),
                            $('#txtMeanCorpHemoConc').val(data.Table21[0].mean_corp_hemo_conc),
                            $('#txtMeanCorpuscularVolume').val(data.Table21[0].mean_corpuscular_volume),
                            $('#txtMonocytes').val(data.Table21[0].monocytes),
                            $('#txtNeutrophils').val(data.Table21[0].neutrophils),
                            $('#txtEosinophilsCount').val(data.Table21[0].eosinophils_absolute_count),
                            $('#txtBasophilsCount').val(data.Table21[0].basophils_absolute_count),
                            $('#txtLymphocyteCount').val(data.Table21[0].lymphocytes_absolute_count),
                            $('#txtMonocytesAbsoluteCount').val(data.Table21[0].monocytes_absolute_count),
                            $('#txtNeutrophilsAbsoluteCount').val(data.Table21[0].neutrophils_absolute_count),
                            $('#txtBasophils').val(data.Table21[0].basophils),
                            $('#txtEosinophils').val(data.Table21[0].eosinophils),
                            $('#txtImmatureGranulocytes').val(data.Table21[0].immature_granulocytes),
                            $('#txtImmatureGranulocytesPercent').val(data.Table21[0].immature_granulocytes_percent),
                            $('#txtTotalRBC').val(data.Table21[0].total_rbc),
                            $('#txtRedCellDistributionWidthRD').val(data.Table21[0].redcell_distribution_width),
                            $('#txtRedCellDistributionWidthSD').val(data.Table21[0].redcell_distribution_width_sd)
                    }
                    if (data.Table22.length > 0) {
                        $("#btnUrineRoutine").html('Update & Next');
                        $('#txtSpecificGravity').val(data.Table22[0].specific_gravity);
                        $('#txtSpecificGravityUnit').val(data.Table22[0].specific_gravity_unit);
                        $('#txtUrinaryBilirubin').val(data.Table22[0].urinary_bilirubin),
                            $('#txtUrinaryBilirubinUnit').val(data.Table22[0].urinary_bilirubin_unit),
                            $('#txtUrineBlood').val(data.Table22[0].urine_blood),
                            $('#txtUrobilinogen').val(data.Table22[0].urobilinogen),
                            $('#txtUrobilinogenUnit').val(data.Table22[0].urobilinogen_unit),
                            $('#txtUrinaryGlucose').val(data.Table22[0].urinary_glucose),
                            $('#txtUrineKetone').val(data.Table22[0].urine_ketone),
                            $('#txtUrineKetoneUnit').val(data.Table22[0].urine_ketone_unit),
                            $('#txtUrinaryLeucocytes').val(data.Table22[0].urinary_leucocytes),
                            $('#txtNitrite').val(data.Table22[0].nitrite),
                            $('#txtNitriteUnit').val(data.Table22[0].nitrite_unit),
                            $('#txtPH').val(data.Table22[0].ph),
                            $('#txtUrinaryProtein').val(data.Table22[0].urinary_protein)
                    }

                    //Binding Writing Pad Prescription Images
                    BindWritingPadImages(data.Table23);


                }
            }
            else {
                console.log(data);
            }
            debugger;
            if ($('#EditVisitReportID').val() != '') {
                $('.da-load-casestudy').hide();
            }
            else {
            }
            getlabfile();
        }

    });
}
// edigt mode data end


function bmi(heightft, heightin, Weight) {
    debugger;
    var heightFt = (heightft),
        heightIn = (heightin),
        height = parseFloat(heightft * 12) + parseFloat(heightin);
    var weight = (Weight * 2.20462),
        BMI = calculateBMI(height, weight);
    $('#lblbmi').html(isNaN(BMI) ? '-' : BMI);
    var BmiFlags = $('#lblbmi').html();
    if (BmiFlags <= 18.5) {
        $('#BMI').html('Underweight');
        $('#BMI_head').addClass('dash-notify-above');
    }
    else if (BmiFlags > 18.5 && BmiFlags <= 24.9) {
        $('#BMI').html('Normal');
        $('#BMI_head').addClass('dash-notify-normal');
    }
    else if (BmiFlags > 25.0 && BmiFlags <= 29.9) {
        $('#BMI').html('Overweight');
        $('#BMI_head').addClass('dash-notify-above');
    }
    else if (BmiFlags >= 30.0) {
        $('#BMI').html('Obese');
        $('#BMI_head').addClass('dash-notify-above');
    }
}

function calculateBMI(height, weight) {
    debugger;
    var BMI = (weight / (height * height)) * 703

    return Math.round(BMI * Math.pow(10, 2)) / Math.pow(10, 2);
}
function falgsType_old() {
    debugger;
    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: $('#doctorId').val(),
        Dml_Indicator: '2'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        console.log(data);
                        if (data[0].stage_diabetes == '' || data[0].stage_diabetes == null) {
                            $('#StageDiabetes').html('-');

                        }
                        else if (data[0].stage_diabetes == '0') {
                            $('#StageDiabetes').html('Hypo Glycaemic');
                        }
                        else if (data[0].stage_diabetes == '1') {
                            $('#StageDiabetes').html('Normal');
                        }
                        else if (data[0].stage_diabetes == '2') {
                            $('#StageDiabetes').html('Pre-Diatetic');
                        }
                        else if (data[0].stage_diabetes == '3') {
                            $('#StageDiabetes').html('Diabetic');
                        }

                        if (data[0].type_of_diabetes == '' || data[0].type_of_diabetes == null) {
                            $('#TypeDiabetes').html('-');
                        }
                        else if (data[0].type_of_diabetes == '0') {
                            $('#TypeDiabetes').html('Type1');
                        }
                        else if (data[0].type_of_diabetes == '1') {
                            $('#TypeDiabetes').html('Type2');
                        }
                        else if (data[0].type_of_diabetes == '2') {
                            $('#TypeDiabetes').html('MODY');
                        }
                        else if (data[0].type_of_diabetes == '3') {
                            $('#TypeDiabetes').html('LADA');

                        }
                        else if (data[0].type_of_diabetes == '4') {
                            $('#TypeDiabetes').html('GAD Other');
                        }

                        if (data[0].bp_flag_type == '' || data[0].bp_flag_type == null) {
                            $('#BP').html('-');
                            $('#BP_head_1').addClass('dash-notify-normal');

                        }
                        else if (data[0].bp_flag_type == '0') {
                            $('#BP').html('Normal');
                            $('#BP_head').addClass('dash-notify-normal');
                        }
                        //low bp
                        else if (data[0].bp_flag_type == '1') {
                            $('#BP').html('Low BP');
                            $('#BP_head').addClass('dash-notify-above');
                        }
                        //low bp
                        else if (data[0].bp_flag_type == '2') {
                            $('#BP').html('Low BP');
                            $('#BP_head').addClass('dash-notify-below');
                        }
                        else if (data[0].bp_flag_type == '3') {
                            $('#BP').html('Normal');
                            $('#BP_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].bp_flag_type == '4') {
                            $('#BP').html('Prehypertension');
                            $('#BP_head').addClass('dash-notify-above');
                        }
                        else if (data[0].bp_flag_type == '5') {
                            $('#BP').html('Hypertension Stage 1');
                            $('#BP_head').addClass('dash-notify-above');
                        }
                        else if (data[0].bp_flag_type == '6') {
                            $('#BP').html('Hypertension Stage 2');
                            $('#BP_head').addClass('dash-notify-above');
                        }
                        else if (data[0].bp_flag_type == '7') {
                            $('#BP').html('Hypertension Crisis');
                            $('#BP_head').addClass('dash-notify-above');
                        }



                        var DDietBP = $('#BP').html();
                        $('#DBP').html(DDietBP);

                        if (data[0].dyslipedemia1 == '' || data[0].dyslipedemia1 == null) {
                            $('#Dyslipidimea').html('-');
                            $('.Dyslipidimea_head > i').addClass('dash-notify-normal');
                        }
                        else if (data[0].dyslipedemia1 == '0') {
                            $('#Dyslipidimea').html('No');
                            $('#Dyslipidimea_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].dyslipedemia1 == '1') {
                            $('#Dyslipidimea').html('Yes');
                            $('#Dyslipidimea_head').addClass('dash-notify-below');
                        }


                        if (data[0].pdr == '' || data[0].pdr == null) {
                            $('#PDR').html('-');
                            $('#PDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].pdr == '0') {
                            $('#PDR').html('-');
                            $('#PDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].pdr == '1') {
                            $('#PDR').html('None');
                            $('#PDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].pdr == '2') {
                            $('#PDR').html('Mild');
                            $('#PDR_head').addClass('dash-notify-above');
                        }
                        else if (data[0].pdr == '3') {
                            $('#PDR').html('Moderate');
                            $('#PDR_head').addClass('dash-notify-above');
                        }
                        else if (data[0].pdr == '4') {
                            $('#PDR').html('Severe');
                            $('#PDR_head').addClass('dash-notify-below');
                        }


                        if (data[0].npdr == '' || data[0].npdr == null) {
                            $('#NPDR').html('-');
                            $('#NPDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].npdr == '0') {
                            $('#NPDR').html('-');
                            $('#NPDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].npdr == '1') {
                            $('#NPDR').html('None');
                            $('#NPDR_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].npdr == '2') {
                            $('#NPDR').html('Mild');
                            $('#NPDR_head').addClass('dash-notify-above');
                        }
                        else if (data[0].npdr == '3') {
                            $('#NPDR').html('Moderate');
                            $('#NPDR_head').addClass('dash-notify-above');
                        }
                        else if (data[0].npdr == '4') {
                            $('#NPDR').html('Severe');
                            $('#NPDR_head').addClass('dash-notify-below');
                        }

                        if (data[0].neuropathy_flag == '' || data[0].npdr == null || data[0].npdr == 0) {
                            $('#PNeuropathy').html('-');
                            $('#PNeuropathy_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].neuropathy_flag == '1') {
                            $('#PNeuropathy').html('Normal');
                            $('#PNeuropathy_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].neuropathy_flag == '2') {
                            $('#PNeuropathy').html('Mild');
                            $('#PNeuropathy_head').addClass('dash-notify-above');
                        }
                        else if (data[0].neuropathy_flag == '3') {
                            $('#PNeuropathy').html('Moderate');
                            $('#PNeuropathy_head').addClass('dash-notify-above');
                        }
                        else if (data[0].neuropathy_flag == '4') {
                            $('#PNeuropathy').html('Severe');
                            $('#PNeuropathy_head').addClass('dash-notify-below');
                        }

                        if (data[0].autonomic_neuropathy == '' || data[0].autonomic_neuropathy == null) {
                            $('#ANeuropathy').html('-');
                            $('#ANeuropathy_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].autonomic_neuropathy == '0') {
                            $('#ANeuropathy').html('Absent');
                            $('#ANeuropathy_head').addClass('dash-notify-normal');
                        }
                        else if (data[0].autonomic_neuropathy == '1') {
                            $('#ANeuropathy').html('Present');
                            $('#ANeuropathy_head').addClass('dash-notify-below');
                        }

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

    });
}



function delallergy(id) {
    var PatientData = {
        Patient_id: patient,
        allergy_id: id,
        Dml_Indicator: 'D'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Allergy_Ins_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            Allergies();
            if (jQuery.isEmptyObject((data))) {

            }
            else {
            }
        }
    });
}

function Allergies() {
    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,
        Dml_Indicator: 'DS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Allergy_Ins_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    $('.divallergies').empty();
                    $('.divallergiess').empty();
                    var tr = '', li = '';
                    if (data.length > 0) {

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


                        }
                        $('.divallergies').append(tr);
                        $('.divallergiess').append(li);
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    LoadOpthal();
}

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

$('.btn_allergies').click(function () {
    if ($.trim($('.txtallergies').val()) != "") {
        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,
            allergy_display: $('.txtallergies').val(),
            Dml_Indicator: 'AI'
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Allergy_Ins_Sel',
            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))) {

                    }
                    else {
                        if (data.length > 0) {
                            debugger;
                            if (data[0].StringMsg == "already") {
                                $('#Ptxtallergies').html('Already exists');
                                $('#Ptxtallergies').show();
                                $('#Ptxtallergies').fadeOut(8000);
                                return false;
                            }
                            else {
                                Allergies();
                            }
                        }
                        //Allergies();
                    }
                }
                else {
                    console.log(data);
                }
            }

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

$('.age_edit_btn').click(function () {
    if ($('.age_edit_btn > i').hasClass('fa-pencil')) {
        $('#age').addClass('hide');
        $('#age_inp_block').removeClass('hide');
        var AgeGender = '';
        if ($('#age').html() == 'Age / Gender') {
            AgeGender = $('#age').html().split('/ ');
        }
        else if ($('#age').html() == 'Age / Male') {
            AgeGender = $('#age').html().split('/ ');
        }
        else if ($('#age').html() == 'Age / Female') {
            AgeGender = $('#age').html().split('/ ');
        }
        else if ($('#age').html() == 'Age / Others') {
            AgeGender = $('#age').html().split('/ ');
        }
        else {
            var AgeGender = $('#age').html().split('years ');
        }
        $('#age').val(AgeGender[0]);
        //if (AgeGender[0]=='Age ') {
        //    AgeGender[0] = '';
        //}
        //$('#age_inp').val(AgeGender[0]);
        if (AgeGender[1] == 'Others') {
            AgeGender[1] = 3;
        }
        if (AgeGender[1] == 'Female') {
            AgeGender[1] = 2;
        }
        if (AgeGender[1] == 'Male') {
            AgeGender[1] = 1;
        }
        $('#gender_inp').val(AgeGender[1]);
        $('#Csex').val(AgeGender[1]);
        $('a[data-toggle=Csex][data-title="' + AgeGender[1] + '"]').removeClass('not-active');
        $('a[data-toggle=Csex][data-title="' + AgeGender[1] + '"]').addClass('active');
        $('.age_edit_btn > i').removeClass().addClass('fa fa-check');
        return true;
    }

    if ($('.age_edit_btn > i').hasClass('fa-check')) {
        $('#age_inp_block').addClass('hide');
        $('#age').removeClass('hide');
        $('.age_edit_btn > i').removeClass().addClass('fa fa-pencil');
        var age = $('#age').val();
        if (age == '' || age == 0) {
            age = 'Age / ';
        }
        else {
            age = $('#age_inp').val() + ' years ';
        }
        $('#age').html(age + $('#gender_inp :selected').text());
        //var Age = ($('#age_inp').val());
        var Gender = ($('#gender_inp').val());
        var PatientData = {
            Patient_id: patient,
            //age: Age,
            gender: Gender,
            Dml_Indicator: '12'
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CaseStudy',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    //var age = '';
                    //if ($('#age_inp').val() == '' || $('#age_inp').val() == 0) {
                    //    age = 'Age / ';
                    //}
                    //else {
                    //    age = $('#age_inp').val() + ' years ';
                    //}
                    var age1 = $('#age').val().trim();
                    $('#hndage').val(age1);
                    $('#AAge').val(age1);
                    if (age1 == '' || age1 == 0) {
                        age1 = 'Age /';
                    }
                    else {
                        age1 = age1 + 'years ';
                    }
                    $('.Age').html(age1 + $('#gender_inp :selected').text());
                    var gender = Gender;
                    $('#gender').val(gender);
                    if (gender == '1') {
                        $('#Male').prop('checked', true);
                    }
                    if (gender == '2') {
                        $('#Female').prop('checked', true);
                    }
                    if (gender == '3') {
                        $('#Male').prop('checked', true);
                    }
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {

                    }
                    CreatinineCal();

                }
                else {
                    console.log(data);
                }
            }
        });
    }
});
function filterme(value) {
    value = parseInt(value, 10); // Convert to an integer
    if (value === 1) {
        $('#RangeFilter').removeClass('rangeAll', 'rangePassive').addClass('rangeActive');
        $('.range_span').text('Before Food');
        $('#hndwenttoeat').val(1);
    } else if (value === 2) {
        $('#RangeFilter').removeClass('rangeActive', 'rangePassive').addClass('rangeAll');
        $('.range_span').text('With Food');
        $('#hndwenttoeat').val(2);
    } else if (value === 3) {
        $('#RangeFilter').removeClass('rangeAll', 'rangeActive').addClass('rangePassive');
        $('.range_span').text('After Food');
        $('#hndwenttoeat').val(3);
    }
}

$('.radio_wrapper_1').click(function () {
    var value = $('input[name=when_to_eat]:checked').val();
    if (value == 1) {
        $('.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);
    } else if (value == 2) {
        $('.when_to_eat_disp').text('With Food');
        $('p.before_food').removeClass('text_before_btn');
        $('p.with_food').addClass('text_before_btn');
        $('p.after_food').removeClass('text_before_btn');
        $('#hndwenttoeat').val(2);
    } else if (value == 3) {
        $('.when_to_eat_disp').text('After Food');
        $('p.before_food').removeClass('text_before_btn');
        $('p.with_food').removeClass('text_before_btn');
        $('p.after_food').addClass('text_before_btn');
        $('#hndwenttoeat').val(3);
    }
});

$('.radio_wrapper_2').click(function () {
    var value = $('input[name=duration_switch]:checked').val();
    if (value == 1) {
        $('.duration_disp').text('Days');
        $('p.duration_days').addClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(1);
    } else if (value == 2) {
        $('.duration_disp').text('Week');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').addClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(2);
    } else if (value == 3) {
        $('.duration_disp').text('Month');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').addClass('text_before_btn');
        $('#hndduration').val(3);
    }
});
$('.radio_wrapper_3').click(function () {
    var value = $('input[name=duration_switch_1]:checked').val();
    if (value == 1) {
        $('.duration_disp_1').text('Days');
        $('p.duration_days_1').addClass('text_before_btn_1');
        $('p.duration_week_1').removeClass('text_before_btn_1');
        $('p.duration_month_1').removeClass('text_before_btn_1');
        $('p.duration_year_1').removeClass('text_before_btn_1');
        $('p.duration_life_1').removeClass('text_before_btn_1');
        $('#hndduration_1').val(1);
    } else if (value == 2) {
        $('.duration_disp_1').text('Week');
        $('p.duration_days_1').removeClass('text_before_btn_1');
        $('p.duration_week_1').addClass('text_before_btn_1');
        $('p.duration_month_1').removeClass('text_before_btn_1');
        $('p.duration_year_1').removeClass('text_before_btn_1');
        $('p.duration_life_1').removeClass('text_before_btn_1');
        $('#hndduration_1').val(2);
    } else if (value == 3) {
        $('.duration_disp_1').text('Month');
        $('p.duration_days_1').removeClass('text_before_btn_1');
        $('p.duration_week_1').removeClass('text_before_btn_1');
        $('p.duration_month_1').addClass('text_before_btn_1');
        $('p.duration_year_1').removeClass('text_before_btn_1');
        $('p.duration_life_1').removeClass('text_before_btn_1');
        $('#hndduration_1').val(3);
    }
    else if (value == 4) {
        $('.duration_disp_1').text('Year');
        $('p.duration_days_1').removeClass('text_before_btn_1');
        $('p.duration_week_1').removeClass('text_before_btn_1');
        $('p.duration_month_1').removeClass('text_before_btn_1');
        $('p.duration_year_1').addClass('text_before_btn_1');
        $('p.duration_life_1').removeClass('text_before_btn_1');
        $('#hndduration_1').val(4);
    }
    else if (value == 5) {
        $('.duration_disp_1').text('LifeLong');
        $('p.duration_days_1').removeClass('text_before_btn_1');
        $('p.duration_week_1').removeClass('text_before_btn_1');
        $('p.duration_month_1').removeClass('text_before_btn_1');
        $('p.duration_year_1').removeClass('text_before_btn_1');
        $('p.duration_life_1').addClass('text_before_btn_1');
        $('#hndduration_1').val(5);
        $('#days_1').val("Life Long");
    }
});

function filterme2(value) {
    value = parseInt(value, 10); // Convert to an integer
    if (value === 1) {
        $('#RangeFilter2').removeClass('rangeAll', 'rangePassive').addClass('rangeActive');
        $('.range_span2').text('Days');
        $('#hndduration').val(1);
    } else if (value === 2) {
        $('#RangeFilter2').removeClass('rangeActive', 'rangePassive').addClass('rangeAll');
        $('.range_span2').text('Week');
        $('#hndduration').val(2);
    } else if (value === 3) {
        $('#RangeFilter2').removeClass('rangeAll', 'rangeActive').addClass('rangePassive');
        $('.range_span2').text('Month');
        $('#hndduration').val(3);
    }
}
$('.height_edit_btn').click(function () {
    if ($('.height_edit_btn > i').hasClass('fa-pencil')) {
        $('#get-feet-or-mm').removeClass('hide');
    }
    else {
        add_height();
    }
});

function add_height_old() {
    var heightFT = '', heightIn = '';
    if ($('#sel-get-feet-or-mm').val() == 1) {
        heightFT = $('#height_inp').val();
        heightIn = $('#height_inp2').val();
        var hieghtdb = parseInt(heightFT * 12) + parseInt(heightIn);
        var hieghtout = Math.round(hieghtdb * 2.54);
        if (isNaN(hieghtout)) {
            hieghtout = 0;
        }
        $('#hieght').html(hieghtout);
    }
    else if ($('#sel-get-feet-or-mm').val() == 2) {
        var height = $('#height_inp2').val();
        $('#hieght').html(height);
        var heightdb = height / 2.54;
        heightFT = heightdb / 12;
        heightFT = parseInt(heightFT);
        heightIn = heightdb % 12;
        heightIn = heightIn.toFixed(1);
        heightIn = Math.round(heightIn);


    }

    else {
        $('.height_edit_btn > i').removeClass().addClass('fa fa-pencil');
        $('#hieght_inp_block').addClass('hide');
        $('#get-feet-or-mm').addClass('hide');
    }
    if ($('#sel-get-feet-or-mm').val() == 1 || $('#sel-get-feet-or-mm').val() == 2) {

        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,
            patient_height: heightFT,
            patient_height_metric: heightIn,
            Dml_Indicator: '8'
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CaseStudy',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                    }
                    var Weight = $('#hidwight').val();
                    bmi(heightFT, heightIn, Weight);
                }
                else {
                    console.log(data);
                }
            }
        });
        $('.height_edit_btn > i').removeClass().addClass('fa fa-pencil');
        $('#hieght_inp_block').addClass('hide');
        $('#get-feet-or-mm').addClass('hide');
        bmi_algorithm3();
    }
};


$('#sel-get-feet-or-mm').change(function () {

    $('.height_edit_btn > i').removeClass().addClass('fa fa-check');
    $('.height_edit_btn').removeClass('add_height').addClass('add_height');
    var heightFT = '', heightIn = '';

    var height = $('#hieght').html();
    $('#hieght').html(height);
    var heightdb = height / 2.54;
    heightFT = heightdb / 12;
    heightFT = parseInt(heightFT);
    heightIn = heightdb % 12;
    heightIn = heightIn.toFixed(1);
    heightIn = Math.round(heightIn);

    if (isNaN(heightFT)) {
        heightFT = 0;
    }
    if (isNaN(heightIn)) {
        heightIn = 0;
    }

    if ($('#sel-get-feet-or-mm').val() == 1) {
        $('#hieght_inp_block').removeClass('hide');
        $('.height_inp_1').show();
        $('.height_inp_2').show();
        $('#height_inp').val(heightFT);
        $('#height_inp2').val(heightIn);
    }
    else if ($('#sel-get-feet-or-mm').val() == 2) {
        $('#hieght_inp_block').removeClass('hide');
        $('.height_inp_1').hide();
        $('.height_inp_2').show();
        $('#height_inp2').val($('#hieght').html());
    }
    else {
        $('#hieght_inp_block').addClass('hide');
    }

});


//Height start
$('#selheight_type').change(function () {
    var height_type = $('#selheight_type').val();

    if (height_type == 1) {
        $('#div_heightCentim').hide();
        $('#div_heightFeetinchs').show();
    }
    else {
        $('#div_heightFeetinchs').hide();
        $('#div_heightCentim').show();
    }
});


function add_height() {
    var heightFT = '', heightIn = '', heightcent = '';
    if ($('#selheight_type').val() == 1) {
        heightFT = $('#txtfeet').val();
        heightIn = $('#txtinches').val();
        //var hieghtdb = parseInt(heightFT * 12) + parseInt(heightIn);
        //var hieghtout = Math.round(hieghtdb * 2.54);

        var hieghtout = (heightFT * 30.48) + (heightIn * 2.54);
        hieghtout = hieghtout.toFixed(1);

        if (isNaN(hieghtout)) {
            hieghtout = 0;
        }
        console.log('hieght--->' + hieghtout);
        heightcent = hieghtout;
    }
    else if ($('#selheight_type').val() == 2) {
        var height = $('#txtcentimeter').val();
        heightcent = height;

        //var heightdb = height / 2.54;
        //heightFT = heightdb / 12;
        ////heightFT = parseInt(heightFT);
        //heightFT = heightFT.toFixed(2);
        //heightIn = heightdb % 12;
        //heightIn = heightIn.toFixed(1);
        //heightIn = Math.round(heightIn);

        const feetNew = Math.floor(height / 30.48);
        const inchesNew = (height - feetNew * 30.48) * 0.393701;
        heightFT = feetNew;
        heightIn = inchesNew.toFixed(2);
    }

    if ($('#selheight_type').val() == 1 || $('#selheight_type').val() == 2) {

        var patient
        if ($('#Hdnpatient_id').val() == '') {
            patient = $('#EditVisitReportID').val();
            var patient_id = patient.split('-');
            patient = patient_id[0];
        }
        else {
            patient = $('#Hdnpatient_id').val()
        }
        var Weight = $('#txtweight').val();
        bmi(heightFT, heightIn, Weight);
        var PatientData = {
            Patient_id: patient,
            patient_height: heightFT,
            patient_height_metric: heightIn,
            Dml_Indicator: '8',
            visit_report_id: $('#VisitReportID').val(),
            bmi_set_by: $('#doctorId').val(),
            patient_bmi: $('#lblbmi').html(),
            patient_weight: Weight
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CaseStudy',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                        var trr = '', weight_g = [], weight_d = [];
                        for (var i = 0; i < data.Table.length; i++) {

                            if (data.Table[i].weight_date != '' && data.Table[i].weight_date != null && data.Table[i].patient_weight != null && data.Table[i].patient_weight != '') {
                                weight_g.push(data.Table[i].patient_weight);
                                weight_d.push(data.Table[i].weight_date)
                                date = data.Table[i].weight_date;
                                trr = trr + '<tr><td>' + data.Table[i].weight_date + '</td><td>' + data.Table[i].patient_weight + ' kg</td></tr>';
                            }
                        }
                        graph1_bpbsall(weight_g, weight_d, 'bmichartview', 'Date');
                        $('#weightlist').html(trr);
                        $('.clsheight').html(heightcent);
                        $('.clsheight').val(heightcent);
                        $('#hieght').html(heightcent);
                        $('.clsweight').html(Weight);
                        $('.clsweight').val(Weight);
                        $('.clsbmi').html($('#lblbmi').html());
                        $('.clsbmi').val($('#lblbmi').html());
                        $('.bmiclose').click();
                    }
                }
                else {
                    console.log(data);
                }
            }

        });
        bmi_algorithm3();
    }
};

$('#txtweight').change(function () {
    var heightFT = '', heightIn = '';
    if ($('#selheight_type').val() == 1) {
        heightFT = $('#txtfeet').val();
        heightIn = $('#txtinches').val();
        //var hieghtdb = parseInt(heightFT * 12) + parseInt(heightIn);
        //var hieghtout = Math.round(hieghtdb * 2.54);

        var hieghtout = (heightFT * 30.48) + (heightIn * 2.54);
        hieghtout = hieghtout.toFixed(1);

        if (isNaN(hieghtout)) {
            hieghtout = 0;
        }
        $('#hieght').html(hieghtout);
    }
    else {
        var height = $('#txtcentimeter').val();
        $('#hieght').html(height);
        //var heightdb = height / 2.54;
        //heightFT = heightdb / 12;
        //heightFT = parseInt(heightFT);
        //heightIn = heightdb % 12;
        //heightIn = heightIn.toFixed(1);
        //heightIn = Math.round(heightIn);

        const feetNew = Math.floor(height / 30.48);
        const inchesNew = (height - feetNew * 30.48) * 0.393701;
        heightFT = feetNew;
        heightIn = inchesNew.toFixed(2);
    }
    var Weight = $('#txtweight').val();
    bmi(heightFT, heightIn, Weight);

});

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

    if ($('.wight_edit_btn > i').hasClass('fa-pencil')) {
        $('#wight').addClass('hide');
        $('#wight_inp_block').removeClass('hide');
        var weight = $('#wight').html();
        if (weight == '-') {
            weight = '';
        }
        $('#wight_inp').val(weight);
        $('.wight_edit_btn > i').removeClass().addClass('fa fa-check');
        return true;
    }
    if ($('.wight_edit_btn > i').hasClass('fa-check')) {
        $('#wight_inp_block').addClass('hide');
        $('#wight').removeClass('hide');
        $('.wight_edit_btn > i').removeClass().addClass('fa fa-pencil');
        $('#wight').html($('#wight_inp').val());
        $("#hidwight").val($('#wight_inp').val());

        return true;
    }
});

$('.diab_edit_btn').click(function () {
    if ($('.diab_edit_btn > i').hasClass('fa-pencil')) {
        $('.btn_type').addClass('hide');
        $('#diab_inp_block').removeClass('hide');
        $('#diab_inp').val($('#diabVal').val());
        var yearvaledit = $('#diabetes').html();
        yearvaledit = yearvaledit.replace('History in years', ' ');
        yearvaledit = yearvaledit.replace(' Years', ' ');
        yearvaledit = yearvaledit.split('.');
        if (yearvaledit.length > 1) {
            $('#diabetes_inp').val(yearvaledit[0]);
            $('#diabetes_inp_month').val(yearvaledit[1]);
        }
        else {
            $('#diabetes_inp').val(yearvaledit[0]);
        }

        $('.diab_edit_btn > i').removeClass().addClass('fa fa-check');
        return true;
    }
    if ($('.diab_edit_btn > i').hasClass('fa-check')) {
        $('#diab_inp_block').addClass('hide');
        $('.btn_type').removeClass('hide');
        $('.diab_edit_btn > i').removeClass().addClass('fa fa-pencil');
        $('#diab').html($('#diab_inp option:selected').text());
        $('.diab').html($('#diab_inp option:selected').text());
        $('#diabVal').val($('#diab_inp option:selected').val());
        var yearvalupd = $('#diabetes_inp').val();
        var monthvalupd = $('#diabetes_inp_month').val();
        if (yearvalupd == '' || yearvalupd == 0) {
            if (monthvalupd == '' || monthvalupd == 0) {
                $('#diabetes').html('History in years');
                $('.diabetes').html('History in years');
            }
            else {
                $('#diabetes').html('0.' + monthvalupd + 'History in years');
                $('.diabetes').html('0.' + monthvalupd + 'History in years');
            }
        }
        else {
            $('#diabetes').html(yearvalupd + '.' + monthvalupd + ' Years');
            $('.diabetes').html(yearvalupd + '.' + monthvalupd + ' Years');
        }
        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,
            type_of_diabetes_set_by: $('#doctorId').val(),
            type_of_diabetes: $('#diab_inp').val(),
            Dml_Indicator: '10'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/CaseStudy',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    neuropathy_algorithm27();
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
        diabetes(yearvalupd, monthvalupd)
    }
});


function diabetes(yearvalupd, monthvalupd) {
    var PatientData = {
        Patient_id: patient,
        type_of_diabetes_set_by: $('#doctorId').val(),
        diabetes_of_year: yearvalupd,
        diabetes_of_month: monthvalupd,
        Dml_Indicator: '11'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#txtCHDiabetes').val(yearvalupd);
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#THistory').click(function () {
    $('.div-THistory').hide();
    $('#treatment_block').show();
    if ($('#THistory').html() == 'Add Note') {
        $('#treatment').val('');
    }
    else {
        $('#treatment').val($('#THistory').html());
    }
});

$('#treatment_block').change(function () {
    $('.div-THistory').show();
    $('#treatment_block').hide();
    $('#THistory').html($('#treatment').val());

    TreamentSurgery();

});


$('#SHistory').click(function () {
    $('.div-SHistory').hide();
    $('#surgery_block').show();
    if ($('#SHistory').html() == 'Add Note') {
        $('#surgery').val('');
    }
    else {
        $('#surgery').val($('#SHistory').html());
    }
});

$('#surgery_block').change(function () {
    $('.div-SHistory').show();
    $('#surgery_block').hide();
    $('#SHistory').html($('#surgery').val());
    TreamentSurgery();
});


$('#PHistory').click(function () {
    $('.div-PHistory').hide();
    $('#Personal_block').show();
    if ($('#PHistory').html() == 'Add Note') {
        $('#Personal').val('');
    }
    else {
        $('#Personal').val($('#PHistory').html());
    }
});

$('#Personal_block').change(function () {
    $('.div-PHistory').show();
    $('#Personal_block').hide();
    $('#PHistory').html($('#Personal').val());
    personal_history();

});


function TreamentSurgery() {
    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,
        treatment_history_notes: $('#THistory').html(),
        surgery_history_notes: $('#SHistory').html(),
        Dml_Indicator: '5'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
        }
    });
}

function btnWeight() {
    $('.wight_edit_btn').click();

    var patient
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }
    var bmi_val = '';
    if ($('#bmi').html() != '-') {
        bmi_val = $('#bmi').html();
    }
    var PatientData = {
        Patient_id: patient,
        visit_report_id: $('#VisitReportID').val(),
        bmi_set_by: $('#doctorId').val(),
        patient_bmi: bmi_val,
        patient_weight: $('#wight').html(),
        Dml_Indicator: '9'
    }

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

                }
                else {

                }
                var height = $('#hieght').html();

                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 Weight = $('#hidwight').val();
                bmi(heightFT, heightIn, Weight);
            }
            else {
                console.log(data);
            }
        }

    });
    bmi_algorithm3();

}
function btnallergies() {
    $('.btn_allergies').click();
}
function btndiab() {
    $('.diab_edit_btn').click();
}
$('#gender_inp').change(function () {
    $('.age_edit_btn').click();
})

function page1() {
    debugger;
    history_angina = 0, CoronaryHeart = 0, CVA = 0;
    if ($('#Angina').prop("checked") == true) {
        history_angina = 1;
    }
    if ($('#CoronaryHeart').prop("checked") == true) {
        CoronaryHeart = 1;
    }
    if ($('#CVA').prop("checked") == true) {
        CVA = 1;
    }
    if ($('#PAD').prop("checked") == true) {
        PAD = 1;
    }
    var patient
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }

    var PatientDatass = {
        Patient_id: patient,
        history_angina: history_angina,
        coronary_heart_disease: CoronaryHeart,
        CVA: CVA,
        history_pad: PAD,
        Doctor_id: $('#doctorId').val(),
        Dml_Indicator: '6',
    };
    var cache = [];
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientDatass, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    try {
                        return JSON.parse(JSON.stringify(value));
                    } catch (error) {
                        return;
                    }
                }
                cache.push(value);
            }
            return value;
        }),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    });
    life_style_Activity();
    age_algorithm1();
    Type1_algorithm29();
    bmi_algorithm3();
    diagnostics_algorithm18();
    neuropathy_algorithm27();
}


function life_style_Activity() {
    var lifeData = {
        patient_alcohol_consumption: $('#ChkAlcohol').val(),
        patient_food_perference: $('#ChkFood').val(),
        patient_smoking_habit: $('#ChkSmoking').val(),
        patient_activity_level: $('#ChkActivity').val(),
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'U'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/life_style_Activity',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(lifeData),
        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) {
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
}
//first screen Completed point

// second screen started point
function loadBP() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'BPS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Observation_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))) {

                }
                else {
                    if (data.length > 0) {
                        $('#txtSys').val(data[0].patient_bp_max);
                        $('#txtDia').val(data[0].patient_bp_min);

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

    });
    loadGlycemicParametersType();
}

function page2() {
    if ($('#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 {
        $('#txtCSysBP').val($('#txtSys').val());
        $('#txtCDiaBP').val($('#txtDia').val());
        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 Sys = $('#txtSys').val();
        var Dia = $('#txtDia').val();
        var bp_flag_type;

        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 Dml_Indicator;
        if ($("#btnOSave").html() == "Update &amp; Next") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'I';
        }
        $("#btnOSave").html('Update & Next')
        var ObservationData = {
            observation_primary: $('#observation_id').val(),
            patient_bp_record_id: $('#bp_id').val(),
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            current_complaints: $('#txtComplaints').val(),
            hypoglycemia_episodes: $('#txtHypoglycemic').val(),
            glycemic_variability: Glycemic_variability,
            pulse_rate: $('#txtPulseRate').val(),
            heart_rate: $('#txtHeartRate').val(),
            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(),
            patient_bp_max: $('#txtSys').val(),
            patient_bp_min: $('#txtDia').val(),
            bp_flag_type: bp_flag_type,
            created_by: $('#doctorId').val(),
            note: $('#txtnotes').val(),
            spo2: $('#txtSPO2').val(),
            temperature: $('#txtTemperature').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) {
                            $('#observation_id').val(data[0].observation_id);
                            $('#bp_id').val(data[0].V_patient_bp_record_id);
                        }

                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
}
//second screen completed point

//third screen started point
function loadGlycemicParametersType() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/GlycemicType1_Ins_Sel',
        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.length > 0) {
                        $("#btntype1").html('Update')
                        var chkAg = data[0].Zn_Transporters;
                        var chkGAD = data[0].GAD_Antibiotics_test;
                        var chkICA = data[0].ICA;
                        var chkIAA = data[0].IAA;
                        var txtFasting = data[0].c_peptite_fasting;
                        var txtSimulated = data[0].c_peptid_simulated;

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

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

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

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

                        $('#txtFasting').val(txtFasting);
                        $('#txtSimulated').val(txtSimulated);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
    loadGlycemicParametersBasic();
}


function loadGlycemicParametersBasic() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'BS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Glycemic_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))) {

                }
                else {
                    if (data.length > 0) {
                        $('#txtHB').val(data[0].hemoglobin);
                        $('#txtfastingInsulin').val(data[0].fasting_insulin);
                        $('#txtfastingInsulin_T').val(data[0].fasting_inslin_unit);
                        $('#txtnotes_glycemic').val(data[0].note);
                        $('#txtWBC').val(data[0].WBC);
                        $('#txtPlatelets').val(data[0].platelet);
                        $('#txtKetones').val(data[0].se_ketones);

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

    });
    $("#btnGlycemic").html('Update & Next')
    loadHBA1C();
}

function loadHBA1C() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Glycemic_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))) {

                }
                else {
                    if (data.length > 0) {
                        $('#txtHbA1c').val(data[0].patient_hbac_record_value);
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    loadSugarValue();
}
function loadSugarValue() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'SS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Glycemic_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))) {

                }
                else {
                    for (var i = 0; i < data.length; i++) {
                        $('#txtBloodsugarV_' + data[i].patient_blood_sugar_type).val(data[i].patient_blood_sugar_value);
                        $('#txtBloodsugarT_' + data[i].patient_blood_sugar_type).val(data[i].patient_blood_sugar_unit);

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


$("#btntype1").click(function () {
    var Zn_Transporters = '0', chkGAD = '0', chkICA = '0', chkIAA = '0';
    //commented by tharuni
    //if ($('#chkAg').val()=="true") {
    //    Zn_Transporters = '1';
    //}
    //if ($('#chkGAD').val() == "true") {
    //    chkGAD = '1';
    //}
    //if ($('#chkICA').val() == "true") {
    //    chkICA = '1';
    //}
    //if ($('#chkIAA').val() == "true") {
    //    chkIAA = '1';
    //}

    var Dml_Indicator;
    if ($("#btntype1").html() == "Save") {
        Dml_Indicator = 'I';
    }
    else {
        Dml_Indicator = 'U';
    }
    $("#btntype1").html('Update')
    var Type1Data = {
        glycemic_parameters_type_1: $('#glycemic_parameters_type_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        Zn_Transporters: ($('#chkAg').val() == '') ? 0 : $('#chkAg').val(),
        ICA: ($('#chkICA').val() == '') ? 0 : $('#chkICA').val(),
        GAD_Antibiotics_test: ($('#chkGAD').val() == '') ? 0 : $('#chkGAD').val(),
        IAA: ($('#chkIAA').val() == '') ? 0 : $('#chkIAA').val(),
        c_peptite_fasting: $('#txtFasting').val(),
        c_peptid_simulated: $('#txtSimulated').val(),
        Dml_Indicator: Dml_Indicator
    }
    if (Zn_Transporters == '1') {
        Zn_Transporters = 'Ag Zn Transporter : present,';
    }
    else {
        Zn_Transporters = 'Ag Zn Transporter : Absent,';
    }
    if (chkGAD == '1') {
        chkGAD = 'GAD Antibodies : present,';
    }
    else {
        chkGAD = 'GAD Antibodies : Absent,';
    }
    if (chkICA == '1') {
        chkICA = 'ICA : present,';
    }
    else {
        chkICA = 'ICA : Absent,';
    }
    if (chkIAA == '1') {
        chkIAA = 'IAA : Present,';
    }
    else {
        chkIAA = 'IAA : Absent,';
    }

    $('#typeValue').html('Type 1 Determination -' + Zn_Transporters + chkGAD + chkICA + chkIAA + $('#txtFasting').val() + ',' + $('#txtSimulated').val())

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

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

                }
                else {
                    if (data.length > 0) {
                        $('#glycemic_parameters_type_id').val(data[0].V_glycemic_parameters_type_1);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

    $('#typeValue').show();
    $('#btnGlycemictCancel').click();

});



function page3() {
    if ($('#txtHbA1c').val() == '' && $('#txtfastingInsulin').val() == '' && $('#txtBloodsugarV_1').val() == '' && $('#txtBloodsugarV_2').val() == '' && $('#txtBloodsugarV_3').val() == '' && $('#txtBloodsugarV_4').val() == '' && $('#txtBloodsugarV_5').val() == '' && $('#txtBloodsugarV_6').val() == '' && $('#txtBloodsugarV_7').val() == '' && $('#txtBloodsugarV_8').val() == '' && $('#txtKetones').val() == '' && $('#txtWBC').val() == '' && $('#txtHB').val() == '' && $('#txtPlatelets').val() == '' && $('#txtnotes_glycemic').val() == '') {
    }
    else {
        var value_1 = '', value_2 = '', value_3 = '', value_4 = '', value_5 = '', value_6 = '', value_7 = '', value_8 = ''
        if ($.trim($('#txtBloodsugarV_1').val()) != '') {
            value_1 = 1
        }
        if ($.trim($('#txtBloodsugarV_2').val()) != '') {
            value_2 = 2
        }
        if ($.trim($('#txtBloodsugarV_3').val()) != '') {
            value_3 = 3
        }
        if ($.trim($('#txtBloodsugarV_4').val()) != '') {
            value_4 = 4
        }
        if ($.trim($('#txtBloodsugarV_5').val()) != '') {
            value_5 = 5
        }
        if ($.trim($('#txtBloodsugarV_6').val()) != '') {
            value_6 = 6
        }
        if ($.trim($('#txtBloodsugarV_7').val()) != '') {
            value_7 = 7
        }
        if ($.trim($('#txtBloodsugarV_8').val()) != '') {
            value_8 = 8
        }
        var Dml_Indicator;
        if ($("#btnGlycemic").html() == "Update &amp; Next") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'I';
        }
        $("#btnGlycemic").html('Update & Next')

        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(),
            note: $('#txtnotes_glycemic').val(),
            WBC: $('#txtWBC').val(),
            platelet: $('#txtPlatelets').val(),
            patient_blood_group: $('#Selbloodgroup').val(),
            se_ketones: $('#txtKetones').val(),

            patient_blood_sugar_value_1: $('#txtBloodsugarV_1').val(),
            patient_blood_sugar_unit_1: $('#txtBloodsugarT_1').val(),
            patient_blood_sugar_type_1: value_1,

            patient_blood_sugar_value_2: $('#txtBloodsugarV_2').val(),
            patient_blood_sugar_unit_2: $('#txtBloodsugarT_2').val(),
            patient_blood_sugar_type_2: value_2,

            patient_blood_sugar_value_3: $('#txtBloodsugarV_3').val(),
            patient_blood_sugar_unit_3: $('#txtBloodsugarT_3').val(),
            patient_blood_sugar_type_3: value_3,

            patient_blood_sugar_value_4: $('#txtBloodsugarV_4').val(),
            patient_blood_sugar_unit_4: $('#txtBloodsugarT_4').val(),
            patient_blood_sugar_type_4: value_4,

            patient_blood_sugar_value_5: $('#txtBloodsugarV_5').val(),
            patient_blood_sugar_unit_5: $('#txtBloodsugarT_5').val(),
            patient_blood_sugar_type_5: value_5,

            patient_blood_sugar_value_6: $('#txtBloodsugarV_6').val(),
            patient_blood_sugar_unit_6: $('#txtBloodsugarT_6').val(),
            patient_blood_sugar_type_6: value_6,

            patient_blood_sugar_value_7: $('#txtBloodsugarV_7').val(),
            patient_blood_sugar_unit_7: $('#txtBloodsugarT_7').val(),
            patient_blood_sugar_type_7: value_7,

            patient_blood_sugar_value_8: $('#txtBloodsugarV_8').val(),
            patient_blood_sugar_unit_8: $('#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);
                var data = data.data;
                if (data.msg == "Success") {
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
}

//third screen end point

//fourth screen started point
function CreatinineCal() {
    var gender = $('#gender').val();
    var age = $('#hndage').val();
    if (age == 0) {
        age = 1;
    }
    if (gender == "" || age == "") {
        $('#PtxtEGFR').html('Age / Gender value missing. Enter calculted eGFR');
        $('#PtxtEGFR').show();
        $('#PtxtEGFR').fadeOut(8000);
        $('#txtEGFR').focus();
        return false;
    }
    var Creatinine = $.trim($('#txtCreatinine').val());
    var Creatinineunit = $('#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);
        $('#txtEGFR').val(aa + ' ml/min/1.73m2');
        $('#LC_txtEGFR').val(aa + ' ml/min/1.73m2');
        $('#txtCKDVal').val(aa);
        if (aa >= 90) {
            $('#txtCKD').val('Stage 1');
        }
        if (aa >= 60 && aa <= 89) {
            $('#txtCKD').val('Stage 2');
        }
        if (aa >= 45 && aa <= 59) {
            $('#txtCKD').val('Stage 3A');
        }
        if (aa >= 30 && aa <= 44) {
            $('#txtCKD').val('Stage 3B');
        }
        if (aa >= 15 && aa <= 29) {
            $('#txtCKD').val('Stage 4');
        }
        if (aa < 15) {
            $('#txtCKD').val('Stage 5');
        }
        var DCKD = $('#txtCKD').val();
        $('#DKindly').html(DCKD);
        egfr_algorithm16(aa);
        renal_algorithm17(aa);
        cholestrol_algorithm19(aa);
        HbA1c_algorithm12(aa);
    }
}


function LC_CreatinineCal() {
    var gender = $('#gender').val();
    var age = $('#hndage').val();
    if (age == 0) {
        age = 1;
    }
    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);
        $('#txtEGFR').val(aa + ' ml/min/1.73m2');
        $('#LC_txtEGFR').val(aa + ' ml/min/1.73m2');
        $('#txtCKDVal').val(aa);
        if (aa >= 90) {
            $('#txtCKD,#LC_txtCKD').val('Stage 1');
        }
        if (aa >= 60 && aa <= 89) {
            $('#txtCKD,#LC_txtCKD').val('Stage 2');
        }
        if (aa >= 45 && aa <= 59) {
            $('#txtCKD,#LC_txtCKD').val('Stage 3A');
        }
        if (aa >= 30 && aa <= 44) {
            $('#txtCKD,#LC_txtCKD').val('Stage 3B');
        }
        if (aa >= 15 && aa <= 29) {
            $('#txtCKD,#LC_txtCKD').val('Stage 4');
        }
        if (aa < 15) {
            $('#txtCKD,#LC_txtCKD').val('Stage 5');
        }
        var DCKD = $('#txtCKD').val();
        $('#DKindly').html(DCKD);
        egfr_algorithm16(aa);
        renal_algorithm17(aa);
        cholestrol_algorithm19(aa);
        HbA1c_algorithm12(aa);
    }
}


function loadRenal() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Renal_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))) {

                }
                else {
                    if (data.length > 0) {
                        $("#btnRenal").html('Update & Next');
                        $('#txtUrea').val(data[0].Urea);
                        $('#SelUrea').val(data[0].urea_unit);
                        $('#txtCreatinine').val(data[0].creatinine);
                        $('#SelCreatinine').val(data[0].Creatinine_unit);
                        //commented and added by nandhini, from medway
                        //$('#txtEGFR').val(data[0].egfr_value);
                        if (data[0].egfr_value == "0") {
                            $('#txtEGFR').val("Infinity");
                        }
                        else {
                            $('#txtEGFR').val(data[0].egfr_value);
                        }
                        $('#txtSodium').val(data[0].Sodium);
                        $('#SelSodium').val(data[0].sodium_unit);
                        $('#txtPotassium').val(data[0].Potassium);
                        $('#SelPotassium').val(data[0].potassium_unit);
                        $('#txtChlorine').val(data[0].Chlorine);
                        $('#SelChlorine').val(data[0].chlorine_unit);
                        $('#txtBiCrabonate').val(data[0].BiCarbonate);
                        $('#SelBicrabonate').val(data[0].Bicarbonate_unit);
                        $('#txtCalcium').val(data[0].serium_calcium);
                        $('#SelCalcium').val(data[0].Calcium_unit);
                        $('#txtPhosphorus').val(data[0].serium_phosphorous);
                        $('#SelPhosphorus').val(data[0].Phosphorus_unit);
                        $('#txtMagnesium').val(data[0].serium_magnesium);
                        $('#SelMagnesium').val(data[0].Magnesium_unit);
                        $('#txtnotes_renal').val(data[0].note);
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    loadCRenal();
}
function loadCRenal() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Renal_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))) {

                }
                else {
                    if (data.length > 0) {
                        var ACR = data[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[0].nephropathy;
                        $('#Chknepropathy').val(Chknepropathy);
                        $('a[data-toggle=Chknepropathy][data-title="' + Chknepropathy + '"]').addClass('active');

                        var txtCKDVal = data[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');
                        }
                        var DCCKD = $('#txtCKD').val();
                        $('#DKindly').html(DCCKD);
                    }
                }
            }
            else {
                console.log(data)
            }
        }

    });
    loadCholesterol();
}

function page4() {
    if ($("input[name='acr1']").val() == 0 && $('#txtUrea').val() == '' && $('#txtCreatinine').val() == '' && $('#txtCKD').val() == '' && $('#txtSodium').val() == '' && $('#txtCalcium').val() == '' && $('#txtPotassium').val() == '' && $('#txtPhosphorus').val() == '' && $('#txtChlorine').val() == '' && $('#txtMagnesium').val() == '' && $('#txtBiCrabonate').val() == '' && $('#txtnotes_renal').val() == '' && $('#Chknepropathy').val() == 0) {
    }
    else {
        var ACR = $("input[name='acr1']").val();
        var nephropathy = $('#Chknepropathy').val()
        var Dml_Indicator;
        if ($("#btnRenal").html() == "Update &amp; Next") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'I';
        }
        $("#btnRenal").html('Update & Next')
        var egfr = $('#txtEGFR').val();
        var egfr_value = egfr.split('ml');
        egfr = egfr_value[0];

        //added by nandhini, from medway
        var stage_id = $('#txtCKDVal').val();
        if (egfr == "Infinity ") {
            egfr = '0';
        }
        if (stage_id == "Infinity") {
            stage_id = '0';
        }

        var RenalData = {
            Dml_Indicator: Dml_Indicator,
            visit_report_id: $('#VisitReportID').val(),
            ACR: ACR,
            nephropathy: nephropathy,
            Urea: $('#txtUrea').val(),
            urea_unit: '1',
            egfr_value: egfr,
            creatinine: $('#txtCreatinine').val(),
            Creatinine_unit: $('#SelCreatinine').val(),
            stage_CKD: stage_id,
            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 {
                }
            }
        });
    }
}
//fourth screen end point

//fifth screen started point

function loadCholesterol() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Cholestrol_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))) {

                }
                else {
                    if (data.length > 0) {
                        $("#btncholestrol").html('Update & Next');
                        $('#txtLDL').val(data[0].LDL);
                        $('#SelLDL').val(data[0].LDL_unit);
                        $('#txtTCholesterol').val(data[0].Total_Cholestrol);
                        $('#SelTCholesterol').val(data[0].Total_cholestrol_unit);
                        $('#txtVLDL').val(data[0].VLDL);
                        $('#SelVLDL').val(data[0].VLDL_unit);
                        $('#txtHDL').val(data[0].HDL);
                        $('#SeltxtHDL').val(data[0].HDL_unit);
                        $('#txtTriglycerides').val(data[0].Triglycerides);
                        $('#SelTriglycerides').val(data[0].Triglycerides_unit);
                        $('#txtHDLRatio').val(data[0].T_cholestrol_Hdl_ratio);
                        $('#txtNHDL').val(data[0].NHDL);
                        $('#SelNHDL').val(data[0].NHDL_unit);
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    loadCCholesterol();
}

function loadCCholesterol() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Cholestrol_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Succeess") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (data.length > 0) {
                        var ChkDyslipidemia = data[0].dyslipedemia;

                        $('#ChkDyslipidemia').val(ChkDyslipidemia);
                        $('a[data-toggle=ChkDyslipidemia][data-title="' + ChkDyslipidemia + '"]').addClass('active');
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    LoadCOpthal();
}
function page5() {
    if ($('#txtTCholesterol').val() == '' && $('#txtVLDL').val() == '' && $('#txtLDL').val() == '' && $('#txtTriglycerides').val() == '' && $('#txtHDL').val() == '' && $('#txtHDLRatio').val() == '' && $('#txtnotes_cholesterol').val() == '' && $('#txtNHDL').val() == '' && $('#ChkDyslipidemia').val() == 0) {

    }
    else {
        $('#txtCLDL').val($('#txtLDL').val());
        $('#txtCHDL').val($('#txtHDL').val());
        $('#txtCtotChol').val($('#txtTCholesterol').val());
        var dyslipedemia = $('#ChkDyslipidemia').val();
        var Dml_Indicator;
        if ($("#btncholestrol").html() == "Update &amp; Next") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'I';
        }
        $("#btncholestrol").html('Update & Next')
        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(),
            NHDL: $('#txtNHDL').val(),
            NHDL_unit: $('#SelNHDL').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 {
                }
            }
        });
    }

}


//fifth screen end point


//sixth screen started point

function LoadOpthal() {

    var patient
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }
    var cholestrol = {
        patient_id: patient,
        Dml_Indicator: 'S'
    }

    $.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 {
                    if (data.length > 0) {
                        var npdr = (data[0].npdr);
                        var pdr = (data[0].pdr);
                        var ChkHemorrhage = (data[0].viterous_hemorage);
                        var ChkDetachment = (data[0].retinal_detachment);
                        var ChkRetinopathy = (data[0].retinopathy);
                        $('#NPDRradio').val(npdr);
                        $('a[data-toggle=NPDRradio][data-title="' + npdr + '"]').addClass('active');

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

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

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

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

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

                    }

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


}

function LoadCOpthal() {

    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Opthal_Ins_Sel',
        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 {
                    console.log(data);
                    if (data.length > 0) {
                        $("#BtnOpthal").html('Update & Next');
                        $('#dpd12').val(data[0].last_observation_date);
                        $('#dpd2').val(data[0].next_suggested_appointment);
                        $('#txtnotes_opthal').val(data[0].note);
                    }
                    else {

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

    });
    LoadOpthal();
    loadCardiac();
}


function page6() {
    var Dml_Indicator, ChkDetachment, ChkRetinopathy, ChkHemorrhage, pdr, npdr;
    pdr = $("input[name='pdr']").val();
    npdr = $("input[name='npdr']").val();
    ChkHemorrhage = $('#ChkHemorrhage').val();
    ChkDetachment = $('#ChkDetachment').val();
    ChkRetinopathy = $('#ChkRetinopathy').val();
    if ($("#BtnOpthal").html() == "Update &amp; Next") {
        Dml_Indicator = 'U';
    }
    else {
        Dml_Indicator = 'I';
    }
    $("#BtnOpthal").html('Update & Next')
    var lastObservationDate = $('#dpd12').val();
    var nextSuggestedAppointment = $('#dpd2').val();
    if (lastObservationDate != "") {
        var lastdate = lastObservationDate.split('/');
        lastObservationDate = lastdate[2] + "-" + lastdate[1] + "-" + lastdate[0];
    }
    if (nextSuggestedAppointment != "") {
        var Nextdate = nextSuggestedAppointment.split('/');
        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: $('#doctorId').val(),
        note: $('#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) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {
            }
        }
    });

}

//sixth screen end point

//seventh screen starting point

$("#btnCSave").click(function () {
    ASCVDCalculation();
    ASCVD_Risk_Score_algorithm24();
});

function loadCardiac() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Cardiac_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))) {

                }
                else {
                    if (data.length > 0) {
                        $("#btnCardiac").html('Update & Next');
                        $('#txtecg').val(data[0].ECG);
                        $('#txtecho').val(data[0].ECHO);
                        var R_tmt = (data[0].TMT_test);
                        var ecg_abnormal = (data[0].ecg_abnormal);
                        var echo_abnormal = (data[0].echo_abnormal);
                        $('#txtnotes_cardiac').val(data[0].note);

                        $('#txtnotes_ASD').val(data[0].ASD);
                        $('#txtnotes_VSD').val(data[0].VSD);
                        $('#txtnotes_value').val(data[0].C_value);
                        $('#txtnotes_Ejection').val(data[0].fraction);
                        $('#txtnotes_Mitral').val(data[0].mitral_value);
                        $('#txtnotes_lotic').val(data[0].lotic_value);
                        $('#txtnotes_Tricuspid').val(data[0].tricuspid);
                        $('#txtnotes_Pulmonary').val(data[0].pulmonary);

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


                        if (ecg_abnormal == '1') {
                            $("#Chkecg").prop('checked', true);
                            $("#Chkecg").click();
                        }
                        if (echo_abnormal == '1') {
                            $("#Selecho").prop('checked', true);
                            $("#Selecho").click();
                        }



                        var txtDrugs = data[0].ON_Hypertension_drugs;
                        var txtStatin = data[0].ON_statin;
                        var txtTherapy = data[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;
                        }


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

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

                        $('#txtTherapy').val(txtTherapy);
                        $('a[data-toggle=txtTherapy][data-title="' + txtTherapy + '"]').removeClass('not-active');
                        $('a[data-toggle=txtTherapy][data-title="' + txtTherapy + '"]').addClass('active');
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    LoadCNeuropathy();
    LoadPatient_level_cardiac();
}
function page7() {
    //var ascvd_score = $('#calASCVD').html();
    //ascvd_score = ascvd_score.replace(' %', ' ');
    //ascvd_score = ascvd_score.replace(': ', ' ');
    var ascvd_score = '';
    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';
    }
    if ($('#txtDrugs').val() == 1) {
        ON_Hypertension_drugs = '1';
    }
    if ($('#txtStatin').val() == 1) {
        ON_statin = '1';
    }
    if ($('#txtTherapy').val() == 1) {
        ON_Aspirin_Theraphy = '1';
    }
    if ($("#btnCardiac").html() == "Update &amp; Next") {
        Dml_Indicator = 'U';
    }
    else {
        Dml_Indicator = 'I';
    }
    $("#btnCardiac").html('Update & Next')
    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,
        ascvd_score: ascvd_score,
        ON_Hypertension_drugs: ON_Hypertension_drugs,
        ON_statin: ON_statin,
        ON_Aspirin_Theraphy: ON_Aspirin_Theraphy,
        note: $('#txtnotes_cardiac').val(),
        ASD: $('#txtnotes_ASD').val(),
        VSD: $('#txtnotes_VSD').val(),
        C_value: $('#txtnotes_value').val(),
        fraction: $('#txtnotes_Ejection').val(),
        mitral_value: $('#txtnotes_Mitral').val(),
        lotic_value: $('#txtnotes_lotic').val(),
        tricuspid: $('#txtnotes_Tricuspid').val(),
        pulmonary: $('#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) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    });

    patient_level_cardiac();
};

function patient_level_cardiac() {
    debugger;
    var Cardiac = {
        L_LAD: $('#L_txtLMCA').val(),
        L_LAD_type: $('#L_LMCAradio').val(),
        L_LCX: $('#L_txtLAD').val(),
        L_LCX_type: $('#L_LADradio').val(),
        L_RCA: $('#L_txtlcx').val(),
        L_RCA_type: $('#L_lcxradio').val(),
        R_LAD: $('#R_txtlad').val(),
        R_LAD_type: $('#R_ladradio').val(),
        R_LCX: $('#R_txtlcx').val(),
        R_LCX_type: $('#R_lcxradio').val(),
        R_RCA: $('#R_txtrca').val(),
        R_RCA_type: $('#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) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    });
}

function LoadPatient_level_cardiac() {

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

                }
                else {
                    if (data.length > 0) {
                        $("#btnCardiac").html('Update & Next');

                        $('#L_txtLMCA').val(data[0].L_LAD);
                        $('#L_LMCAradio').val(data[0].L_LAD_type);
                        $('a[data-toggle=L_LMCAradio][data-title="' + data[0].L_LAD_type + '"]').addClass('active');

                        $('#L_txtLAD').val(data[0].L_LCX);
                        $('#L_LADradio').val(data[0].L_LCX_type);
                        $('a[data-toggle=L_LADradio][data-title="' + data[0].L_LCX_type + '"]').addClass('active');

                        $('#L_txtlcx').val(data[0].L_RCA);
                        $('#L_lcxradio').val(data[0].L_RCA_type);
                        $('a[data-toggle=L_lcxradio][data-title="' + data[0].L_RCA_type + '"]').addClass('active');


                        $('#R_txtlad').val(data[0].R_LAD);
                        $('#R_ladradio').val(data[0].R_LAD_type);
                        $('a[data-toggle=R_ladradio][data-title="' + data[0].R_LAD_type + '"]').addClass('active');

                        $('#R_txtlcx').val(data[0].R_LCX);
                        $('#R_lcxradio').val(data[0].R_LCX_type);
                        $('a[data-toggle=R_lcxradio][data-title="' + data[0].R_LCX_type + '"]').addClass('active');

                        $('#R_txtrca').val(data[0].R_RCA);
                        $('#R_rcaradio').val(data[0].R_RCA_type);
                        $('a[data-toggle=R_rcaradio][data-title="' + data[0].R_RCA_type + '"]').addClass('active');

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

    });
}

function ASCVDCalculation() {

    var points = '', CPoints = '', SPoints = '', HPoints = '', BPoints = '';
    var Age = '', gender = '', smoker, HDL = '', ON_Hypertension_drugs = 0;
    gender = $("#Csex").val();
    Age = $('#AAge').val();
    var cholesterol = $('#txtCtotChol').val();
    HDL = $('#txtCHDL').val();
    var bloodpressure = $('#txtSys').val();
    smoker = $('#smoking').val();
    if (smoker == 266919005) {
        smoker = 0
    }
    else {
        smoker = 1
    }

    if (Age == '') {
        $('#PAAge').show();
        $('#PAAge').fadeOut(8000);
        $('#PAAge').html('Enter the Age');
        $("#PAAge").val('');
        $("#PAAge").focus();
        return false;
    }
    if (gender == '') {
        $('#Psex').show();
        $('#Psex').fadeOut(8000);
        $('#Psex').html('Select the Gender');
        $("#Psex").val('');
        $("#Psex").focus();
        return false;
    }
    if ($('#txtCSysBP').val() == '') {
        $('#PtxtCSysBP').show();
        $('#PtxtCSysBP').fadeOut(8000);
        $('#PtxtCSysBP').html('Enter the SysBp');
        $("#PtxtCSysBP").val('');
        $("#PtxtCSysBP").focus();
        return false;
    }
    if ($('#txtCDiaBP').val() == '') {
        $('#PtxtCDiaBP').show();
        $('#PtxtCDiaBP').fadeOut(8000);
        $('#PtxtCDiaBP').html('Enter the DiaBp');
        $("#PtxtCDiaBP").val('');
        $("#PtxtCDiaBP").focus();
        return false;
    }
    if ($('#txtCLDL').val() == '') {
        $('#PtxtCLDL').show();
        $('#PtxtCLDL').fadeOut(8000);
        $('#PtxtCLDL').html('Enter the LDL');
        $("#PtxtCLDL").val('');
        $("#PtxtCLDL").focus();
        return false;
    }
    if ($('#txtCHDL').val() == '') {
        $('#PtxtCHDL').show();
        $('#PtxtCHDL').fadeOut(8000);
        $('#PtxtCHDL').html('Enter the HDL');
        $("#PtxtCHDL").val('');
        $("#PtxtCHDL").focus();
        return false;
    }
    if ($('#txtCtotChol').val() == '') {
        $('#PtxtCtotChol').show();
        $('#PtxtCtotChol').fadeOut(8000);
        $('#PtxtCtotChol').html('Enter the Total Cholesterol');
        $("#PtxtCtotChol").val('');
        $("#PtxtCtotChol").focus();
        return false;
    }

    if ($('#txtCHDiabetes').val() == '') {
        $('#PtxtCHDiabetes').show();
        $('#PtxtCHDiabetes').fadeOut(8000);
        $('#PtxtCHDiabetes').html('Enter the History of Diabetes');
        $("#PtxtCHDiabetes").val('');
        $("#PtxtCHDiabetes").focus();
        return false;
    }

    if ($('#txtDrugs').val() == 1) {
        ON_Hypertension_drugs = '1';
    }


    if (gender == 1) {
        if (Age >= 20 && Age <= 34) {
            points = -9;
        }
        else if (Age >= 35 && Age <= 39) {
            points = -4;
        }
        else if (Age >= 40 && Age <= 44) {
            points = 0;
        }
        else if (Age >= 45 && Age <= 49) {
            points = 3;
        }
        else if (Age >= 50 && Age <= 54) {
            points = 6;
        }
        else if (Age >= 55 && Age <= 59) {
            points = 8;
        }
        else if (Age >= 60 && Age <= 64) {
            points = 10;
        }
        else if (Age >= 65 && Age <= 69) {
            points = 11;
        }
        else if (Age >= 70 && Age <= 74) {
            points = 12;
        }
        else if (Age >= 75 && Age <= 79) {
            points = 13;
        }
    }
    else {

        if (Age >= 20 && Age <= 34) {
            points = -7;
        }
        else if (Age >= 35 && Age <= 39) {
            points = -3;
        }
        else if (Age >= 40 && Age <= 44) {
            points = 0;
        }
        else if (Age >= 45 && Age <= 49) {
            points = 3;
        }
        else if (Age >= 50 && Age <= 54) {
            points = 6;
        }
        else if (Age >= 55 && Age <= 59) {
            points = 8;
        }
        else if (Age >= 60 && Age <= 64) {
            points = 10;
        }
        else if (Age >= 65 && Age <= 69) {
            points = 12;
        }
        else if (Age >= 70 && Age <= 74) {
            points = 13;
        }
        else if (Age >= 75 && Age <= 79) {
            points = 14;
        }
    }
    if (gender == 1) {
        if (Age >= 20 && Age <= 39) {
            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 4;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 7;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 9;
            }
            else if (cholesterol >= 280) {
                CPoints = 11;
            }

        }
        if (Age >= 40 && Age <= 49) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 3;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 5;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 6;
            }
            else if (cholesterol >= 280) {
                CPoints = 8;
            }

        }
        if (Age >= 50 && Age <= 59) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 2;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 3;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 4;
            }
            else if (cholesterol >= 280) {
                CPoints = 5;
            }

        }
        if (Age >= 60 && Age <= 69) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 1;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 1;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 2;
            }
            else if (cholesterol >= 280) {
                CPoints = 3;
            }

        }
        if (Age >= 70 && Age <= 79) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 0;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 0;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 1;
            }
            else if (cholesterol >= 280) {
                CPoints = 1;
            }
        }
    }
    else {

        if (Age >= 20 && Age <= 39) {
            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 4;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 8;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 11;
            }
            else if (cholesterol >= 280) {
                CPoints = 13;
            }

        }
        if (Age >= 40 && Age <= 49) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 3;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 6;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 8;
            }
            else if (cholesterol >= 280) {
                CPoints = 10;
            }

        }
        if (Age >= 50 && Age <= 59) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 2;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 4;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 5;
            }
            else if (cholesterol >= 280) {
                CPoints = 7;
            }

        }
        if (Age >= 60 && Age <= 69) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 1;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 2;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 3;
            }
            else if (cholesterol >= 280) {
                CPoints = 4;
            }

        }
        if (Age >= 70 && Age <= 79) {

            if (cholesterol <= 160) {

                CPoints = 0;
            }
            else if (cholesterol >= 160 && cholesterol <= 199) {
                CPoints = 1;
            }
            else if (cholesterol >= 200 && cholesterol <= 239) {
                CPoints = 1;
            }
            else if (cholesterol >= 240 && cholesterol <= 279) {
                CPoints = 2;
            }
            else if (cholesterol >= 280) {
                CPoints = 2;
            }
        }
    }
    if (gender == 1) {
        if (smoker == 0) {
            SPoints = 0;
        }
        else {
            if (Age >= 20 && Age <= 39) {
                SPoints = 8;
            }
            if (Age >= 40 && Age <= 49) {
                SPoints = 5;
            }
            if (Age >= 50 && Age <= 59) {
                SPoints = 3;
            }
            if (Age >= 60 && Age <= 69) {
                SPoints = 1;
            }
            if (Age >= 70 && Age <= 79) {
                SPoints = 1;
            }
        }
    }
    else {
        if (smoker == 0) {
            SPoints = 0;
        }
        else {
            if (Age >= 20 && Age <= 39) {
                SPoints = 9;
            }
            if (Age >= 40 && Age <= 49) {
                SPoints = 7;
            }
            if (Age >= 50 && Age <= 59) {
                SPoints = 4;
            }
            if (Age >= 60 && Age <= 69) {
                SPoints = 2;
            }
            if (Age >= 70 && Age <= 79) {
                SPoints = 1;
            }
        }
    }
    if (gender == 1) {
        if (HDL >= 60) {
            HPoints = -1;
        }
        if (HDL >= 50 && HDL <= 59) {
            HPoints = 0;
        }
        if (HDL >= 40 && HDL <= 49) {
            HPoints = 1;
        }
        if (HDL < 40) {
            HPoints = 2;
        }
    }
    else {
        if (HDL >= 60) {
            HPoints = -1;
        }
        if (HDL >= 50 && HDL <= 59) {
            HPoints = 0;
        }
        if (HDL >= 40 && HDL <= 49) {
            HPoints = 1;
        }
        if (HDL < 40) {
            HPoints = 2;
        }
    }
    if (gender == 1) {
        if (ON_Hypertension_drugs == 1) {
            if (bloodpressure < 120) {
                BPoints = 0;
            }
            if (bloodpressure >= 120 && bloodpressure <= 129) {
                BPoints = 1;
            }
            if (bloodpressure >= 130 && bloodpressure <= 139) {
                BPoints = 2;
            }
            if (bloodpressure >= 140 && bloodpressure <= 149) {
                BPoints = 2;
            }
            if (bloodpressure >= 150 && bloodpressure <= 159) {
                BPoints = 2;
            }
            if (bloodpressure >= 160) {
                BPoints = 3;
            }
        }
        else {
            if (bloodpressure < 120) {
                BPoints = 0;
            }
            if (bloodpressure >= 120 && bloodpressure <= 129) {
                BPoints = 0;
            }
            if (bloodpressure >= 130 && bloodpressure <= 139) {
                BPoints = 1;
            }
            if (bloodpressure >= 140 && bloodpressure <= 149) {
                BPoints = 1;
            }
            if (bloodpressure >= 150 && bloodpressure <= 159) {
                BPoints = 1;
            }
            if (bloodpressure >= 160) {
                BPoints = 2;
            }
        }
    }
    else {
        if (ON_Hypertension_drugs == 1) {
            if (bloodpressure < 120) {
                BPoints = 0;
            }
            if (bloodpressure > 120 && bloodpressure <= 129) {
                BPoints = 3;
            }
            if (bloodpressure >= 130 && bloodpressure <= 139) {
                BPoints = 4;
            }
            if (bloodpressure >= 140 && bloodpressure <= 149) {
                BPoints = 5;
            }
            if (bloodpressure >= 150 && bloodpressure <= 159) {
                BPoints = 5;
            }
            if (bloodpressure >= 160) {
                BPoints = 6;
            }
        }
        else {
            if (bloodpressure < 120) {
                BPoints = 0;
            }
            if (bloodpressure >= 120 && bloodpressure <= 129) {
                BPoints = 1;
            }
            if (bloodpressure >= 130 && bloodpressure <= 139) {
                BPoints = 2;
            }
            if (bloodpressure >= 140 && bloodpressure <= 149) {
                BPoints = 3;
            }
            if (bloodpressure >= 150 && bloodpressure <= 159) {
                BPoints = 3;
            }
            if (bloodpressure >= 160) {
                BPoints = 4;
            }
        }
    }
    var totTotal = 0;
    totTotal = points + CPoints + SPoints + HPoints + BPoints;
    var totpercentage;
    if (gender == 1) {
        if (totTotal <= 0) {
            totpercentage = 1;
        }
        if (totTotal >= 1 && totTotal <= 4) {
            totpercentage = 1;
        }
        if (totTotal >= 5 && totTotal <= 6) {
            totpercentage = 2;
        }
        if (totTotal == 7) {
            totpercentage = 3;
        }
        if (totTotal == 8) {
            totpercentage = 4;
        }
        if (totTotal == 9) {
            totpercentage = 5;
        }
        if (totTotal == 10) {
            totpercentage = 6;
        }
        if (totTotal == 11) {
            totpercentage = 8;
        }
        if (totTotal == 12) {
            totpercentage = 10;
        }
        if (totTotal == 13) {
            totpercentage = 12;
        }
        if (totTotal == 14) {
            totpercentage = 16;
        }
        if (totTotal == 15) {
            totpercentage = 20;
        }
        if (totTotal == 16) {
            totpercentage = 25;
        }
        if (totTotal > 16) {
            totpercentage = 30;
        }
    }
    else {

        if (totTotal < 9) {
            totpercentage = 1;
        }
        if (totTotal >= 9 && totTotal <= 12) {
            totpercentage = 1;
        }
        if (totTotal >= 13 && totTotal <= 14) {
            totpercentage = 2;
        }
        if (totTotal == 15) {
            totpercentage = 3;
        }
        if (totTotal == 16) {
            totpercentage = 4;
        }
        if (totTotal == 17) {
            totpercentage = 5;
        }
        if (totTotal == 18) {
            totpercentage = 6;
        }
        if (totTotal == 19) {
            totpercentage = 8;
        }
        if (totTotal == 20) {
            totpercentage = 11;
        }
        if (totTotal == 21) {
            totpercentage = 14;
        }
        if (totTotal == 22) {
            totpercentage = 17;
        }
        if (totTotal == 23) {
            totpercentage = 22;
        }
        if (totTotal == 24) {
            totpercentage = 27;
        }
        if (totTotal > 25) {
            totpercentage = 30;
        }
    }

    $('#calASCVD').html(': ' + totpercentage + ' %');
    $('#cariac_pop_close_btn').click();
    ASCVD_Risk_Score_algorithm24(totpercentage);

}
//seventh screen end point

//eight screen starting point

function LoadNeuropathy() {
    var patient
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }
    var Neuropathy = {
        patient_id: patient,
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Neuropathy_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Neuropathy),
        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 chkANeuropathy = (data[0].autonomic_neuropathy);
                        $('#chkANeuropathy').val(chkANeuropathy);
                        $('a[data-toggle=chkANeuropathy][data-title="' + chkANeuropathy + '"]').addClass('active');

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

function LoadCNeuropathy() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Neuropathy_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))) {

                }
                else {
                    if (data.length > 0) {
                        $("#btnNeuropathy").html('Update & Next')
                        $('#txtDoppler').val(data[0].doppler_note);
                        $('#txtnotes_neuropathy').val(data[0].note);
                        var PeripheralNeuropathy = data[0].peripharal_neuhropathy;
                        var ABIndex = data[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');

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

    });
    LoadThyroid();
}

function page8() {
    debugger;
    insert_foot();

    //for (i = 1; i <= 30; i++) {
    //    if ($('#l_point_' + i).hasClass('red')) {
    //        insert_foot('1', i, '1');
    //    }
    //    if ($('#l_point_' + i).hasClass('green')) {
    //        insert_foot('1', i, '2');
    //    }
    //    if ($('#l_point_' + i).hasClass('blue')) {
    //        insert_foot('1', i, '3');
    //    }
    //    if ($('#l_point_' + i).hasClass('yellow')) {
    //        insert_foot('1', i, '4');
    //    }
    //    if ($('#l_point_' + i).hasClass('orange')) {
    //        insert_foot('1', i, '5');
    //    }
    //    if (!$('#l_point_' + i).hasClass('red') && !$('#l_point_' + i).hasClass('green') && !$('#l_point_' + i).hasClass('blue') && !$('#l_point_' + i).hasClass('yellow') && !$('#l_point_' + i).hasClass('orange')) {
    //        insert_foot('1', i, '0');
    //    }
    //}

    //for (i = 1; i <= 30; i++) {
    //    if ($('#r_point_' + i).hasClass('red')) {
    //        insert_foot('2', i, '1');
    //    }
    //    if ($('#r_point_' + i).hasClass('green')) {
    //        insert_foot('2', i, '2');
    //    }
    //    if ($('#r_point_' + i).hasClass('blue')) {
    //        insert_foot('2', i, '3');
    //    }
    //    if ($('#r_point_' + i).hasClass('yellow')) {
    //        insert_foot('2', i, '4');
    //    }
    //    if ($('#r_point_' + i).hasClass('orange')) {
    //        insert_foot('2', i, '5');
    //    }
    //    if (!$('#r_point_' + i).hasClass('red') && !$('#r_point_' + i).hasClass('green') && !$('#r_point_' + i).hasClass('blue') && !$('#r_point_' + i).hasClass('yellow') && !$('#r_point_' + i).hasClass('orange')) {
    //        insert_foot('2', i, '0');
    //    }
    //}
    var peripharal_neuhropathy = $("input[name='per_neu']").val();
    var AB_index = $("input[name='AB_index']").val();
    var ANeuropathy = $('#chkANeuropathy').val();

    if ($("#btnNeuropathy").html() == "Update &amp; Next") {
        Dml_Indicator = 'U';
    }
    else {
        Dml_Indicator = 'I';
    }
    $("#btnNeuropathy").html('Update & Next')
    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: $('#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 {
            }
        }
    });
}
function insert_foot() {
    debugger;
    var generalInfoArray = new Array();
    var indicator = 'II'

    for (i = 1; i <= 30; i++) {
        debugger;
        var generalInfo = {};

        if ($('#l_point_' + i).hasClass('red')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '1',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#l_point_' + i).hasClass('green')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '2',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#l_point_' + i).hasClass('blue')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '3',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#l_point_' + i).hasClass('yellow')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '4',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#l_point_' + i).hasClass('orange')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '5',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if (!$('#l_point_' + i).hasClass('red') && !$('#l_point_' + i).hasClass('green') && !$('#l_point_' + i).hasClass('blue') && !$('#l_point_' + i).hasClass('yellow') && !$('#l_point_' + i).hasClass('orange')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '1',
                generalInfo.point_no = i,
                generalInfo.point_type = '0',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }

        if ($('#r_point_' + i).hasClass('red')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '1',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#r_point_' + i).hasClass('green')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '2',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#r_point_' + i).hasClass('blue')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '3',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#r_point_' + i).hasClass('yellow')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '4',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if ($('#r_point_' + i).hasClass('orange')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '5',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }
        if (!$('#r_point_' + i).hasClass('red') && !$('#r_point_' + i).hasClass('green') && !$('#r_point_' + i).hasClass('blue') && !$('#r_point_' + i).hasClass('yellow') && !$('#r_point_' + i).hasClass('orange')) {

            generalInfo.Patient_id = $('#Hdnpatient_id').val();
            generalInfo.leg_id = '2',
                generalInfo.point_no = i,
                generalInfo.point_type = '0',
                generalInfo.neuropathy_flag = '1',
                generalInfo.Dml_Indicator = indicator

            generalInfoArray.push(generalInfo);
            generalInfo = {}

        }

    }

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

function PatientNeuropathyLoad() {
    var patient
    if ($('#Hdnpatient_id').val() == '') {
        patient = $('#EditVisitReportID').val();
        var patient_id = patient.split('-');
        patient = patient_id[0];
    }
    else {
        patient = $('#Hdnpatient_id').val()
    }
    var PatientNeuropathy = {
        Dml_Indicator: 'S',
        patient_id: patient
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/PatientNeuropathy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientNeuropathy),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var datalenth = data1.length;
                    $('#footIdValue').val(datalenth);

                    if (datalenth > 0) {
                        var j = 1;
                        for (var i = 0; i < 30; i++) {

                            if (data1[i].leg_id == 2) {
                                if (data1[i].point_type == 1) {
                                    $('#r_point_' + (i + 1)).addClass('red').html('&#9673;');
                                }
                                if (data1[i].point_type == 2) {
                                    $('#r_point_' + (i + 1)).addClass('green').html('&#9673;');
                                }
                                if (data1[i].point_type == 3) {
                                    $('#r_point_' + (i + 1)).addClass('blue').html('&#9673;');
                                }
                                if (data1[i].point_type == 4) {
                                    $('#r_point_' + (i + 1)).addClass('yellow').html('&#9673;');
                                }
                                if (data1[i].point_type == 5) {
                                    $('#r_point_' + (i + 1)).addClass('orange').html('&#9673;');
                                }
                            }
                        }
                        var k = 0;

                        for (var j = 30; j < 60; j++) {

                            if (data1[j].leg_id == 1) {

                                if (data1[j].point_type == 1) {
                                    $('#l_point_' + (k + 1)).addClass('red').html('&#9673;');
                                }
                                if (data1[j].point_type == 2) {
                                    $('#l_point_' + (k + 1)).addClass('green').html('&#9673;');
                                }
                                if (data1[j].point_type == 3) {
                                    $('#l_point_' + (k + 1)).addClass('blue').html('&#9673;');
                                }
                                if (data1[j].point_type == 4) {
                                    $('#l_point_' + (k + 1)).addClass('yellow').html('&#9673;');
                                }
                                if (data1[j].point_type == 5) {
                                    $('#l_point_' + (k + 1)).addClass('orange').html('&#9673;');
                                }
                                k++;

                            }
                        }
                    }

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


//eight screen end point


//nineth screen starting point

function Interpretation() {
    var VT3, VT4, VTSH;
    var T3 = $('#txtT3').val();
    var T4 = $('#txtT4').val();
    var TSH = $('#txtTSH').val();

    if (T3 < 1.4) {
        VT3 = 'Decreased';
    }
    else if (T3 > 1.4 && T3 < 4.4) {
        VT3 = 'Within Range';
    }

    else {
        VT3 = 'Raised';
    }

    if (T4 < 0.8) {
        VT4 = 'Decreased';
    }
    else if (T4 > 0.8 && T4 < 1.8) {
        VT4 = 'Within Range';
    }
    else {
        VT4 = 'Raised';
    }

    if (TSH < 0.45) {
        VTSH = 'Decreased';
    }
    else if (TSH > 0.45 && TSH < 4.5) {
        VTSH = 'Within Range';
    }
    else {
        VTSH = 'Raised';
    }
    var li = '';
    $('#Interpretation').empty();
    if (VTSH == 'Within Range' && VT3 == 'Decreased' && VT4 == 'Within Range') {
        li = "<li>Isolated Low T3-often seen in elderly & associated Non-Thyroidal illness. In elderly the drop in T3 level can be upto 25%</li>";

    }
    else if (VTSH == 'Raised' && VT3 == 'Within Range' && VT4 == 'Within Range') {

        li = "<li>Isolated High TSHespecially in the range of 4.7 to 15 mlU/ml is commonly associated with Physiological & Biological TSH Variability</li><br><li>Subclinical Autoimmune Hypothyroidism</li><br><li>Intermittent T4 therapy for hypothyroidism</li><br><li>Recovery phase after Non-Thyroidal illness</li>";
    }
    else if (VTSH == 'Raised' && VT3 == 'Decreased' && VT4 == 'Decreased') {
        li = "<li>Chronic Autoimmune Thyroidities</li><br><li>Post thyroidectomy, Post radioidine</li><br><li>Hypothyroid phase of transient thyroiditis</li>";

    }
    else if ((VTSH == 'Raised' || VTSH == 'Within Range') && VT3 == 'Raised' && (VT4 == 'Raised' || VT4 == 'Raised')) {

        li = "<li>Interfering antibodies to thyroid hormone (anti – TPO antibodies)</li><br><li>Intermittent T4 therapy or T4 overdose</li><br><li>Drug Interference – Amiodarone, Heparin, Beta Blocker, steroids, antiepileptics</li>";

    }
    else if (VTSH == 'Decreased' && (VT3 == 'Raised' || VT3 == 'Within Range') && (VT4 == 'Raised' || VT4 == 'Within Range')) {
        li = "<li>Isolated Low TSH – especially in the range of 0.1 to 0.4 often seen in elderly & associated with Non Thyroidal illness</li><br><li>Subclinical Hyperthyroidism</li><br><li>Thyroxine Ingestion</li>";
    }
    else if (VTSH == 'Decreased' && VT3 == 'Decreased' && VT4 == 'Decreased') {

        li = "<li>Central Hypothyroidism</li><br><li>Non-Thyroidal illness</li><br><li>Recent treatment for hyperthyroidism (TSH remains suppressed)</li>";

    }
    else if (VTSH == 'Decreased' && VT3 == 'Raised' && VT4 == 'Raised') {
        li = "<li>Primary Hyperthyroidism (Graces disease) multinodular goiter, toxic nodule</li><br><li>Transient thyroiditis: Postpartum, silent (lymphocytic), Post viral (granulomatous, subacute, DeQuervain’s Gestational Thyrotoxicosis with hyperemesis gravidarum </li>";
    }
    else if ((VTSH == 'Decreased' || VTSH == 'Within Range') && VT3 == 'Raised' && VT4 == 'Within Range') {
        li = "<li>T3 toxicosis</li><br><li>Non-thyroidal illness</li>";
    }
    $('#Interpretation').append(li);
}

function LoadThyroid() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Thyroid_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))) {

                }
                else {
                    if (data.length > 0) {
                        $("#btnThyroid").html('Update & Next')
                        $('#txtT3').val(data[0].Free_T3);
                        $('#txtT4').val(data[0].Free_T4);
                        $('#N_txtT3').val(data[0].T3);
                        $('#N_txtT4').val(data[0].T4);
                        $('#txtTSH').val(data[0].TSH);
                        $('#txtnotes_thyroid').val(data[0].note);
                        Interpretation();
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });
    XRayUltrasound();
}
function page9() {
    if ($('#txtT3').val() == '' && $('#txtT4').val() == '' && $('#txtTSH').val() == '' && $('#txtnotes_thyroid').val() == '' && $('#N_txtT3').val() == '' && $('#N_txtT4').val() == '') {
    }
    else {
        var Dml_Indicator;
        if ($("#btnThyroid").html() == "Update &amp; Next") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'I';
        }
        $("#btnThyroid").html('Update & Next')
        var cholestrol = {
            visit_report_id: $('#VisitReportID').val(),
            Free_T3: $('#txtT3').val(),
            Free_T3_unit: $('#SelT3').val(),
            Free_T4: $('#txtT4').val(),
            Free_T4_unit: $('#SelT4').val(),
            T3: $('#N_txtT3').val(),
            T3_unit: $('#N_SelT3').val(),
            T4: $('#N_txtT4').val(),
            T4_unit: $('#N_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(cholestrol),
            success: function (data) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }
}

//nineth screen end point


//tenth screen starting point
$('#labuploadfile').change(function () {
    labUpload();
});

function labUpload() {
    var uploadpath = $('#labuploadfile').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#labuploadfile").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: '/CaseStudy/UploadPhotoFiles',
            type: "POST",
            contentType: false, // Not to set any content header
            processData: false, // Not to process data
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    $('#hndlabuploadfile').val(emp);
                });
            }
        });
    }
}


$('#btnlabupload').click(function () {
    if ($('#txtlabupload').val() == '') {
        $('#Ptxtlabupload').show();
        $('#Ptxtlabupload').fadeOut(8000);
        $('#Ptxtlabupload').html('Enter File Name');
        $('#txtlabupload').focus();
        $('#txtlabupload').val('');
        return false;
    }
    if ($('#labuploadfile').val() == '') {
        $('#Plabuploadfile').show();
        $('#Plabuploadfile').fadeOut(8000);
        $('#Plabuploadfile').html('Upload File');
        $('#labuploadfile').focus();
        $('#labuploadfile').val('');
        return false;
    }
    else {
        $('.da-load-labupload').show();
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var currentdate = d.getFullYear() + '-' +
            (month < 10 ? '0' : '') + month + '-' +
            (day < 10 ? '0' : '') + day;
        var fileupload = {
            patient_id: patient,
            prescription_scan_id: '2',
            visit_report_id: $('#VisitReportID').val(),
            patient_testname: $('#txtlabupload').val(),
            patient_test_taken_date: currentdate,
            extension: ".jpg",
            Base64: $('#hndlabuploadfile').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/labupload',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(fileupload),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    getlabfile();
                    $('#txtlabupload').val('');
                    $('#labuploadfile').val('');
                    $('.da-load-labupload').hide();
                }
                else {
                    console.log(data);
                }
            }
        });
    }
});
function getlabfile() {
    debugger;
    var visitreportid = ($('#VisitReportID').val() != null && $('#VisitReportID').val() != "" ? $('#VisitReportID').val() : $('#EditVisitReportID').val())
    var fileupload = {
        visit_report_id: $('#VisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/getlabupload',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(fileupload),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success" || data.msg == "No Record Founds") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#laduploadtbl tbody').empty();
                    var tr = '';
                    if (data.status == false) {
                    }
                    else {
                        if (data.patientlabrecord.length > 0) {
                            debugger;
                            for (var i = 0; i < data.patientlabrecord.length; i++) {
                                debugger;
                                var photourl = '<a href="' + $('#hdngetlabfilepath').val() + "/" + data.patientlabrecord[i].patient_lab_record_path + '" target="_blank">' + data.patientlabrecord[i].patient_lab_record_path + '</a>';
                                var patient_testname = data.patientlabrecord[i].patient_testname;
                                var id = data.patientlabrecord[i].patient_lab_record_id;
                                var delbtn = '<button class="btn deleteicon-btn btn-sm" onclick=labfileuploaddel("' + id + '")><i class="fa fa-trash" aria-hidden="true"></i></button>';
                                tr = tr + '<tr><td>' + patient_testname + '</td><td>' + photourl + '</td><td>' + delbtn + '</td></tr>';
                            }
                            $('#laduploadtbl').append(tr);
                        }
                    }
                }
                nextAppoinment();
            }
            else {
                console.log(data);
            }
        }
    });
}

function labfileuploaddel(val) {
    var fileupload = {
        patient_lab_record_id: val,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/dellabupload',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(fileupload),
        success: function (data) {
            getlabfile();
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data = JSON.parse(data);
            }
        }
    });
}

function XRayUltrasound() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/UltraSound_Xray_Ins',
        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.length > 0) {
                        $("#btnUltraSound").html('Update & Next');
                        $('#txtNotes').val(data[0].notes);
                        var chkLiver = (data[0].fatty_lives);
                        var chkGS = (data[0].GS_Calculus);
                        $('#txtUNotes').val(data[0].USNotes);
                        $('#ctsnotes').val(data[0].cts_notes)
                        $('#chkLiver').val(chkLiver);
                        $('a[data-toggle=chkLiver][data-title="' + chkLiver + '"]').addClass('active');

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

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

    });
    getlabfile();
}

function page10() {
    var fatty_lives = $('#chkLiver').val(),
        GS_Calculus = $('#chkGS').val();
    var Dml_Indicator;
    if ($("#btnUltraSound").html() == "Update &amp; Next") {
        Dml_Indicator = 'U';
    }
    else {
        Dml_Indicator = 'I';
    }
    $("#btnUltraSound").html('Update & Next');
    var cholestrol = {
        visit_report_id: $('#VisitReportID').val(),
        notes: $('#txtNotes').val(),
        fatty_lives: fatty_lives,
        GS_Calculus: GS_Calculus,
        UNOTES: $('#txtUNotes').val(),
        cts_notes: $('#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(cholestrol),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {
            }
        }
    });
}

//tenth screen ending point

//eleven screen starting point
function page11() {
    $("#btnliverfun").html('Update & Next');
    var lever = {
        serum_bilirubin_total: $('#txtSerum_Bilirubin_Total').val(),
        serum_bilirubin_direct: $('#txtSerum_Bilirubin_Direct').val(),
        bilirubin_indirect: $('#txtBilirubin_Indirect').val(),
        serum_protein_total: $('#txtSerum_Protein_Total').val(),
        serum_protein_albumin: $('#txtSerum_Protein_Albumin').val(),
        serumproteinglibulin: $('#txtSerum_Protein_Glibulin').val(),
        SGOT: $('#txtSGOT').val(),
        SGPT: $('#txtSGPT').val(),
        serum_alkaline_phosphatase: $('#txtSerum_Alkaline_Phosphatase').val(),
        gamma_glutamyl_transpeptidase: $('#txtGamma_Glutamyl_Transpeptidase').val(),
        serum_magnesium: $('#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) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    });
}

function page14() {

}
//cbc page 15 start
function page16() {

    if ($('#txtCBCHemoglobin').val() == '' && $('#txtNucleatedBloodcell').val() == '' && $('#txtNucleatedBloodcellPercent').val() == '' && $('#txtHematocrit').val() == '' && $('#txtPlateletCount').val() == '' && $('#txtTotalLeucocytesCount').val() == '' && $('#txtLymphocytePercent').val() == '' && $('#txtMeanCorpuscular').val() == '' && $('#txtMeanCorpHemoConc').val() == '' && $('#txtMeanCorpuscularVolume').val() == '' && $('#txtMonocytes').val() == '' && $('#txtNeutrophils').val() == '' && $('#txtEosinophilsCount').val() == '' && $('#txtBasophilsCount').val() == '' && $('#txtLymphocyteCount').val() == '' && $('#txtMonocytesAbsoluteCount').val() == '' && $('#txtNeutrophilsAbsoluteCount').val() == '' && $('#txtBasophils').val() == '' && $('#txtEosinophils').val() == '' && $('#txtImmatureGranulocytes').val() == '' && $('#txtImmatureGranulocytesPercent').val() == '' && $('#txtTotalRBC').val() == '' && $('#txtRedCellDistributionWidthRD').val() == '' && $('#txtRedCellDistributionWidthSD').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').val(),
            hemoglobin_unit: $('#txtCBCHemoglobinUnit').val(),
            nucleated_red_blood_cells: $('#txtNucleatedBloodcell').val(),
            nucleated_red_blood_cells_percent: $('#txtNucleatedBloodcellPercent').val(),
            hematocrit: $('#txtHematocrit').val(),
            platelet_count: $('#txtPlateletCount').val(),
            platelet_count_unit: $('#txtPlateletCountUnit').val(),
            total_leucocytes_count: $('#txtTotalLeucocytesCount').val(),
            lymphocyte_percent: $('#txtLymphocytePercent').val(),
            mean_corpuscular_hemoglobin: $('#txtMeanCorpuscular').val(),
            mean_corp_hemo_conc: $('#txtMeanCorpHemoConc').val(),
            mean_corpuscular_volume: $('#txtMeanCorpuscularVolume').val(),
            monocytes: $('#txtMonocytes').val(),
            neutrophils: $('#txtNeutrophils').val(),
            eosinophils_absolute_count: $('#txtEosinophilsCount').val(),
            basophils_absolute_count: $('#txtBasophilsCount').val(),
            lymphocytes_absolute_count: $('#txtLymphocyteCount').val(),
            monocytes_absolute_count: $('#txtMonocytesAbsoluteCount').val(),
            neutrophils_absolute_count: $('#txtNeutrophilsAbsoluteCount').val(),
            basophils: $('#txtBasophils').val(),
            eosinophils: $('#txtEosinophils').val(),
            immature_granulocytes: $('#txtImmatureGranulocytes').val(),
            immature_granulocytes_percent: $('#txtImmatureGranulocytesPercent').val(),
            total_rbc: $('#txtTotalRBC').val(),
            redcell_distribution_width: $('#txtRedCellDistributionWidthRD').val(),
            redcell_distribution_width_sd: $('#txtRedCellDistributionWidthSD').val()

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

                }
                else {
                }
            }
        });
    }
}

//cbc page 15 end

//urine routine page 16 start
function page17() {
    if ($('#txtSpecificGravity').val() == '' && $('#txtUrinaryBilirubin').val() == '' && $('#txtUrineBlood').val() == '' && $('#txtUrobilinogen').val() == '' && $('#txtUrinaryGlucose').val() == '' && $('#txtUrineKetone').val() == '' && $('#txtUrinaryLeucocytes').val() == '' && $('#txtNitrite').val() == '' && $('#txtPH').val() == '' && $('#txtUrinaryProtein').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').val(),
            specific_gravity_unit: $('#txtSpecificGravityUnit').val(),
            urinary_bilirubin: $('#txtUrinaryBilirubin').val(),
            urinary_bilirubin_unit: $('#txtUrinaryBilirubinUnit').val(),
            urine_blood: $('#txtUrineBlood').val(),
            urobilinogen: $('#txtUrobilinogen').val(),
            urobilinogen_unit: $('#txtUrobilinogenUnit').val(),
            urinary_glucose: $('#txtUrinaryGlucose').val(),
            urine_ketone: $('#txtUrineKetone').val(),
            urine_ketone_unit: $('#txtUrineKetoneUnit').val(),
            urinary_leucocytes: $('#txtUrinaryLeucocytes').val(),
            nitrite: $('#txtNitrite').val(),
            nitrite_unit: $('#txtNitriteUnit').val(),
            ph: $('#txtPH').val(),
            urinary_protein: $('#txtUrinaryProtein').val()

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

                }
                else {
                }
            }
        });
    }
}

//eleven screen ending pointing


//new functions

function loadmedicine() {
    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'
    }
    $.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 {
                    if (data1.length > 0) {
                        MedicineDataBinding(data1);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
    //commented by nandhini for performance issue on 20/09/2022 and lab prescription section removed already.
    //LoadLab();
}

function loadwhentoeat() {
    debugger;
    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="0">--select--</option>';
                    whentotakearray = data1;

                    loadwhentotake(whentotakearray)
                    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);
                    // $('.hndwenttoeat').append(defaultoption + trs);
                    copyprescriptionlist();
                }

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

    });
}

$('#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);
    }
});

$('#report').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/CaseStudy/labAutoCompletelist?TestName=' + $('#report').val() + "&testid=" + 1 + "&labid=" + $('#lab_id').val() + "&labdatatype=" + $('#lab_data_flag').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    response($.map(data, function (item) {
                        return { label: item.testname, value: item.testname };
                    }))
                }
                else {
                    console.log(data);
                }
            }
        })
    }
});

$('#ADD_Medicine').on("click", function () {
    debugger;
    $('#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 ($('#txtNoDurationMedicine').val() == "" || $('#txtNoDurationMedicine').val() == null || $('#txtNoDurationMedicine').val() == "0") {
        if ($('#days').val().length == 0 || $('#days').val() == '') {
            $('#Pdays').show();
            $('#Pdays').fadeOut(8000);
            $('#Pdays').html('Enter Duration');
            $('#days').focus();
            $('#ADD_Medicine').attr('disabled', false);
            return false;
        }
    }
    if (mor > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#mor').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (aft > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#aft').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (nit > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#nit').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    var Durations = $('#hndduration').val();

    var WhenEat = $('#hndwenttoeat').val();
    var day = (($('#days').val() == null || $('#days').val() == "") ? 1 : $('#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() == null || $('#days').val() == "") ? 1 : $('#days').val()));
    var mdescription = {
        Dml_Indicator: 'I',
        patient_id: patient,
        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: $('#doctorId').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        instructions: $('#prescriptionNotes').val(),
        medicine_unit: $('#SelUnit').val(),
        generic_name: $('#txtGenericName').val(),
        max_quantity: max_quantity,
        priority: priority,
        pharmacy_id: $('#txtPharmacyID').val(),
        medicine_id: $('#txtMedicineID').val(),
        medicine_frequency: $('#medicinefrequency').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;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.length > 0) {
                        MedicineDataBinding(data1);
                    }
                    $('#SelMedicineType').val('0');
                    $('#food').val('1');
                    $('#txtMedicineID').val('');
                    $('#txtNoDurationMedicine').val('');
                    $('#medicine_name').val('');
                    // $('#days').val('');
                    $('#dosage').val('');
                    $('input:checkbox').prop('checked', false);
                    $('#mor').val(0);
                    $('#aft').val(0);
                    $('#eve').val(0);
                    $('#nit').val(0);
                    $('#prescriptionNotes').val('');
                    $('#txtGenericName').val('');
                    $('#txtGenericName').prop('readonly', true);
                    $('#lblGenericName').html('Select Generic');
                    $('#txtGenericName').show();
                    //when_to eat reset
                    $('#before_food').prop('checked', true);
                    $('#with_food').prop('checked', false);
                    $('#after_food').prop('checked', false);
                    $('.when_to_eat_disp').text('Before Food');
                    $('p.before_food').addClass('text_before_btn');
                    $('p.with_food').removeClass('text_before_btn');
                    $('p.after_food').removeClass('text_before_btn');
                    $('#hndwenttoeat').val(1);
                    $('#medicinefrequency').val(0);
                    //duration reset
                    //$('#duration_days').prop('checked', true);
                    //$('#duration_week').prop('checked', false);
                    //$('#duration_month').prop('checked', false);
                    //$('p.duration_days').addClass('text_before_btn');
                    //$('p.duration_week').removeClass('text_before_btn');
                    //$('p.duration_month').removeClass('text_before_btn');
                    //$('.duration_disp').html('Days');
                    //$('#hndduration').val(1);
                    //$('#setDurationUnit').text('Days');
                    $('#duration_days').prop('checked', false);
                    $('#duration_week').prop('checked', false);
                    $('#duration_month').prop('checked', true);
                    $('p.duration_days').removeClass('text_before_btn');
                    $('p.duration_week').removeClass('text_before_btn');
                    $('p.duration_month').addClass('text_before_btn');
                    $('.duration_disp').html('Month');
                    $('#hndduration').val(3);
                    $('#setDurationUnit').text('Month');

                    $('#prescriptionNotesToggle').hide();
                    $("input[name='optradio']").prop('checked', false);
                    $('#days').val('');
                }
            }
            else {
                console.log(data1);
            }
            $('#ADD_Medicine').attr('disabled', false);
            $('#hndwenttoeat').val('');
        }

    });
});

//binding medicine prescription 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;
        }

        //added by nandhini for no duration medicine 
        //comment by pidanson for magna 
        //if (emp.no_duration == 1) {
        //    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>" + (emp.frequency_name != null && emp.frequency_name != "" ? emp.frequency_name : "") + "</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);
}

function medicineedit(medicine_id) {
    debugger;
    $('#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 data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                var medval = '';
                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;
                        $('#txtMedicineID').val(emp.medicine_id);
                        $('#txtNoDurationMedicine').val(emp.no_duration);

                        $("#high").prop("checked", false);
                        $("#medium").prop("checked", false);
                        $("#low").prop("checked", false);

                        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_);
                        $('#medicinefrequency').val(emp.medicine_frequency);
                        $('#days').val((emp.no_duration == 0 ? 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();
                        $('#txtGenericName').prop('readonly', false);
                        //$('#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 () {
    $('#tbl-medicine tbody').empty();
    $('#tbl-medicine').empty();
    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() == null || $('#days').val() == "") ? 1 : $('#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 ($('#txtNoDurationMedicine').val() == "" || $('#txtNoDurationMedicine').val() == null || $('#txtNoDurationMedicine').val() == "0") {
        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() == null || $('#days').val() == "") ? 1 : $('#days').val()));

    var medicineType = $('#dosage').val();

    var mdescription = {
        Dml_Indicator: 'U',
        patient_id: patient,
        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: $('#doctorId').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,
        pharmacy_id: $('#txtPharmacyID').val(),
        medicine_id: $('#txtMedicineID').val(),
        medicine_frequency: $('#medicinefrequency').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) {
            $('#ADD_Medicine').show();
            $('#Update_Medicine').hide();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                var medval = '';
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    if (data1.length > 0) {
                        MedicineDataBinding(data1);
                    }
                    $('#SelMedicineType').val('0');
                    $('#food').val('1');
                    $('#txtMedicineID').val('');
                    $('#txtNoDurationMedicine').val('');
                    $('#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('');
                    $('#txtGenericName').prop('readonly', true);
                    $('#lblGenericName').html('Select Generic');
                    $('#txtGenericName').show();
                    $('#lblGenericName').show();
                    //when_to eat reset
                    $('#before_food').prop('checked', true);
                    $('#with_food').prop('checked', false);
                    $('#after_food').prop('checked', false);
                    $('.when_to_eat_disp').text('Before Food');
                    $('p.before_food').addClass('text_before_btn');
                    $('p.with_food').removeClass('text_before_btn');
                    $('p.after_food').removeClass('text_before_btn');
                    $('#hndwenttoeat').val(1);
                    $('#medicinefrequency').val(0);
                    //duration reset
                    //$('#duration_days').prop('checked', true);
                    //$('#duration_week').prop('checked', false);
                    //$('#duration_month').prop('checked', false);
                    //$('p.duration_days').addClass('text_before_btn');
                    //$('p.duration_week').removeClass('text_before_btn');
                    //$('p.duration_month').removeClass('text_before_btn');
                    //$('.duration_disp').html('Days');
                    //$('#hndduration').val(1);

                    $('#duration_days').prop('checked', false);
                    $('#duration_week').prop('checked', false);
                    $('#duration_month').prop('checked', true);
                    $('p.duration_days').removeClass('text_before_btn');
                    $('p.duration_week').removeClass('text_before_btn');
                    $('p.duration_month').addClass('text_before_btn');
                    $('.duration_disp').html('Month');
                    $('#hndduration').val(3);
                    $('#setDurationUnit').text('Month');

                    $('#prescriptionNotesToggle').hide();
                    $("input[name='optradio']").prop('checked', false);
                    $('#days').val('');
                }
            }
            else {
                console.log(data1)
            }
        }
    });
});

function deleteMedi(id) {
    debugger;

    $('#tbl-medicine tbody').empty();
    $('#tbl-medicine').empty();
    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 = '';
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    if (data1.length > 0) {
                        MedicineDataBinding(data1);
                    }
                    $('#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(data);
            }
        }
    });
}



//old functions
//Prescription starting point
function loadMedicineType() {
    debugger;
    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#doctorId').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;
                    loadmedicinetype(medicinetypearray);

                    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);
                    // $('.SelMedicineType').append(default_opt + medicine);
                }
            }
            else {
                console.log(data);
            }
        }
    });
    loadwhentoeat();

}
function copyprescriptionlist() {
    var visiti = $('#VisitReportID').val();
    visiti = visiti.split('-');
    if (visiti[1] == "V001") {
        $('#copymed').hide();
    }
    else {
        $('#copymed').show();
        var VisitreportId = {
            patient_id: patient,
            visit_report_id: $('#VisitReportID').val(),
            Dml_Indicator: 'CPL',
            doctor_id: $('#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 Copy_prescription_id(visit_report_id) {
debugger;
    $('.ClsCopy_prescription').hide();
    var VisitreportId = {
        patient_id: patient,
        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((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) {
                        bindingprescriptiontable(data1)
                        // MedicineDataBinding(data1);
                        $('#pres_popupcls').click();
                    }
                    else {

                        toastr.success("Medicine deleted");
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function dosage() {
    $('#txtNoDurationMedicine').val('');
    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(),
                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) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        var data1 = data1.data;
                        debugger;
                        if (data1.Table1.length > 0) {
                            if (data1.Table[0].generic_name == '' || data1.Table[0].generic_name == null) {
                                //$('#SelMedicineType').val(data1.Table[0].medicine_type_id);
                                //$('#txtGenericName').val(data1.Table1[0].generic_name);
                                //$('#lblGenericName').html('Select Generic');
                                $('#txtGenericName').val('');
                                $('#txtGenericName').prop('readonly', false);
                            }
                            else {
                                //$('#SelMedicineType').val(data1.Table1[0].medicine_type_id);
                                $('#txtGenericName').val(data1.Table[0].generic_name);
                                $('#txtGenericName').prop('readonly', true);
                                //$('#lblGenericName').html(data1.Table1[0].generic_name);
                            }
                            $('#hndwenttoeat').val(data1.Table1[0].how_to_take);

                            if (data1.Table1[0].no_duration == "1") {
                                $('#days').val("");
                            }
                            else {
                                $('#days').val(data1.Table1[0].days_to_take);
                            }
                            $('#medicinefrequency').val(data1.Table1[0].medicine_frequency);
                            $('#duration_days').prop('checked', true);
                            $('#duration_week').prop('checked', false);
                            $('#duration_month').prop('checked', false);
                            $('p.duration_days').addClass('text_before_btn');
                            $('p.duration_week').removeClass('text_before_btn');
                            $('p.duration_month').removeClass('text_before_btn');
                            $('.duration_disp').html('Days');
                            $('#hndduration').val(1);
                            $('#setDurationUnit').text('Days');

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

                        if (data1.Table.length > 0) {
                            $('#txtNoDurationMedicine').val(data1.Table[0].no_duration);
                        }
                        else if (data1.Table2.length > 0) {
                            $('#txtNoDurationMedicine').val(data1.Table2[0].no_duration);
                        }

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


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

    }

})

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

    //var Genericname = $('#lblGenericName').html();
    //$('#txtGenericName').show();
    //if (Genericname == 'Select Generic') {
    //    $('#txtGenericName').val('');
    //}
    //else {
    //    $('#txtGenericName').val($('#lblGenericName').html());
    //}
});

function prescriptionNotes_change() {

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

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

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

function page12() {

}

$('#BtnCPrPrint').on('click', function () {

});

$('#BtnCPrPrint1').on('click', function () {
    Engageclosed();
});


$('#btnTemplate').click(function () {
    if ($.trim($('#templateName').val()) == "") {
        $('#PtemplateName').show();
        $('#PtemplateName').fadeOut(8000);
        $('#PtemplateName').html('Enter The Patient Name');
        $('#templateName').focus();
        $('#templateName').val('');
        return false;
    }
    saveprescription(2)
    return false

    /*  $("#myTemplateTitle").modal("hide");
      $('#loaderimg').show();
      var Template = {
          template_name: $('#templateName').val(),
          visit_report_id: $('#VisitReportID').val(),
          doctor_id:$('#doctorId').val(),
          Dml_Indicator:'I'
      }
      $.ajax({
          async: true,
          type: 'POST',
          url: '/CaseStudy/Medicine_template',
          contentType: 'application/json; charset=UTF-8',
          data: JSON.stringify(Template),
          success: function (data) {
              var data1 = JSON.parse(data);
              if (data1.msg == "Success") {
                  var data1 = data1.data;
                  $('#loaderimg').hide();
                  if (jQuery.isEmptyObject((data1))) {
                  }
                  else {
                      if (data1.length > 0) {
                          toastr.success('Template Saved Successfully',
                           {
                               closeButton: false,
                               progressBar: true,
                               allowHtml: true,
                               timeOut: 0,
                           })
                          setTimeout(function () {
                              templatelist();
                          }, 2000);
                          
                      }
                      else {
                          toastr.warning("Unable to save the template, Please try again");
                      }
                  }
              }
              else {
                  console.log(data);
              }
          }
      });*/
});



function templatelist() {
    var Template = {
        doctor_id: $('#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 copytemplate(medicineTemplateId) {
    $('.Clscopytemplate').hide();
    $('#loaderimg').show();

    var VisitreportId = {
        medicine_template_id: medicineTemplateId,
        patient_id: patient,
        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);
                        bindingprescriptiontable(data1)
                    }
                }
                $('.Clscopytemplate').show();
                $('#loaderimg').hide();
            }
            else {
                console.log(data);
            }
        }
    });
}

//Prescription ending point

//lab starting point
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) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                $('#labtype').empty();

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

                }
                else {
                    var Country;
                    $.each(data1, function (i, emp) {
                        Country = Country + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';
                    });
                    $('#labtype').append(Country);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function labtemlatelist() {
    var Template = {
        doctor_id: $('#doctorId').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Lab_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                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=1"><div class="pull-left">Click To Add Investigation Template</div><div class="clearfix"></div></a>';
                }
                else {
                    if (data.length <= 0) {
                        tr = tr + '<a href="/Template/Index?Type=1"><div class="pull-left">Click To Add Investigation Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" onclick=labtemplatelist(' + data[i].lab_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div></a><br>';
                        }
                    }
                }
                $('#labtemplatelist').html(tr);
            }
            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;
    }
    $('#loaderimg').show();
    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: $('#doctorId').val(),
        Patient_id: patient,
        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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#loaderimg').hide();
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    $('#tbl-scan > 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='btn addicon-btn btn-sm mr20' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        $('#tbl-scan > tbody:last').append(value);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

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

    var SelFacility = $("#report").val();
    var SelFacilityId = $("#labtype").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: patient,
            visit_report_id: $('#VisitReportID').val(),
            lab_prescription: SelFacility,
            lab_type: SelFacilityId,
            suggested_date: suggeteddate,
            slot_start_time: $('#Hdnappointment_date').val(),
            labtypetest: $('#labtypetest').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);
                if (data.msg == "Success") {
                    var data = data.data;
                    var tr = '';
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {
                        $('#tbl-scan > 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='btn addicon-btn btn-sm mr20' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                            $('#tbl-scan > tbody:last').append(value);
                        }
                    }
                    $('#report').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 LoadLab() {
    var VisitreportId = {
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_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))) {

                }
                else {
                    $('#tbl-scan > 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='btn addicon-btn btn-sm mr20' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                        $('#tbl-scan > tbody:last').append(value);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#Update_Lab_record').click(function () {
    var table_id = $('#hdn_scan_id').val();
    var SelFacility = $("#report").val();
    var SelFacilityId = $("#labtype").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').show();
    $('#Update_Lab_record').hide();


    if (SelFacility.length > 0 && SelFacilityId.length > 0) {
        var SelFacility = $("#report").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: patient,
                visit_report_id: $('#VisitReportID').val(),
                lab_prescription: SelFacility,
                lab_type: $('#labtype').val(),
                suggested_date: suggeteddate,
                slot_start_time: $('#Hdnappointment_date').val(),
                prescription_scan_id: $('#hdn_scan_id').val(),
                labtypetest: $('#labtypetest').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);
                    if (data.msg == "Success") {
                        var data = data.data;
                        var tr = '';
                        if (jQuery.isEmptyObject((data))) {

                        }
                        else {
                            $('#tbl-scan > 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='btn addicon-btn btn-sm mr20' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                                $('#tbl-scan > tbody:last').append(value);
                            }
                        }
                        $('#report').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 deleteRow(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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    $('#tbl-scan > 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='btn addicon-btn btn-sm mr20' onclick='scanedit(\"" + data[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='deleteRow(\"" + (data[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>"

                        $('#tbl-scan > tbody:last').append(value);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function scanedit(scan_id) {
    $('#Add_Lab_record').hide();
    $('#Update_Lab_record').show();
    $('#hdn_scan_id').val(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 {
                    for (var i = 0; i < data.length; i++) {
                        var lab_type = data[0].lab_type;
                        $('#report').val(data[0].lab_prescription);
                        $('#datepickerscan').val(data[0].suggested_date);
                        $('#checkboxs').prop('value', lab_type); // by D
                        $('a[data-toggle="checkboxs"]').not('[data-title="' + lab_type + '"]').removeClass('active').addClass('not-active'); // by D
                        $('a[data-toggle="checkboxs"][data-title="' + lab_type + '"]').removeClass('not-active').addClass('active'); // by D
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#BtnLabSubmit').click(function () {
    debugger;
    close = false;
    formChanged = false;
    var r, msg = "Are you sure, you want to close video chat?";
    if ($('#appointment_type').val() == "2" && ($('#videomodal').is(':visible'))) {
        r = confirm(msg);
        if (r == true) {
            $('.da-load-casestudy').show();
            if ($('#tblDietChart_body tr').length > 0) {
                deletediet();
            }
            else {
                SaveGeneralInformation();
                saveprescription(1)
                debugger;
                if ($('#assesed_by').val() != 0) {
                    save_assesed();
                }
            }
        }
    }
    else {
        $('.da-load-casestudy').show();
        if ($('#tblDietChart_body tr').length > 0) {
            deletediet();
        }
        else {
            debugger;
            saveprescription(1)
            SaveGeneralInformation();
            if ($('#assesed_by').val() != 0) {
                save_assesed();
            }

        }
    }
    //SaveGeneralInformation();
    //SaveObservedNutrition();
});


$('#btnSaveOnly').click(function () {
    debugger;
    close = true;
    formChanged = false;
    var r, msg = "Are you sure, you want to close video chat?";
    if ($('#appointment_type').val() == "2" && ($('#videomodal').is(':visible'))) {
        r = confirm(msg);
        if (r == true) {
            $('.da-load-casestudy').show();
            if ($('#tblDietChart_body tr').length > 0) {
                deletediet();
            }
            else {

                SaveGeneralInformation();
                saveprescription(1)
                debugger;
                if ($('#assesed_by').val() != 0) {
                    save_assesed();
                }
            }
        }
    }
    else {
        $('.da-load-casestudy').show();
        if ($('#tblDietChart_body tr').length > 0) {
            deletediet();
        }
        else {
            debugger;
            SaveGeneralInformation();
            saveprescription(1)
            if ($('#assesed_by').val() != 0) {
                save_assesed();
            }

        }
    }
});

function save_assesed() {
    debugger;
    var visit_data = {
        visit_report_id: $('#VisitReportID').val(),
        Dml_Indicator: 'SA',
        assesed_by: $('#assesed_by').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(visit_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                }
            }
        }
    })
}

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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                insertdiet();
            }
            else {
                console.log(data);
            }
        }
    });
}


function Labtextcheck() {
    var scan = $("input[name='scan']:checked").val();
    var report = $('#report').val();
    var datepickerscan = $('#datepickerscan').val();

    if (scan != "" && report != "" && datepickerscan != "") {
        var sldate = datepickerscan.split('/');
        var s_lab_date = sldate[2] + "-" + sldate[1] + "-" + sldate[0];
        var sms = {
            Dml_Indicator: 'I',
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            lab_prescription: report,
            lab_type: scan,
            suggested_date: s_lab_date,
            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) {

            }
        });
    }
}

$('#btnsaveclose').click(function () {
    SaveGeneralInformation();
    //diagnosis();
});

function pagess14() {
    //var r, msg = "Are you sure, you want to close video chat?";
    //if ($("#videocallnew").hasClass("ui-popup-active")) {
    //    if ($('#appointment_type').val() == "2") {
    //        r = confirm(msg);
    //        if (r == true) {
    //            Engagecloseds();
    //        }
    //        else {
    //            $('#loaderimg').hide();
    //        }
    //    }
    //}
    //else {
    //    Engagecloseds();
    //}
    Engagecloseds();
}

function Engagecloseds() {
    debugger;
    var Dml_Indicator = '', check_staus = '';
    if ($('#Hdnappointment_date').val() == '' || $('#Hdnappointment_date').val() == null) {
        Dml_Indicator = 'ECO';
        check_staus = 5;
    }
    else {
        Dml_Indicator = 'VCO';
        check_staus = 3;
    }
    var Engage = {
        patient_id: $('#Hdnpatient_id').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        check_by: $('#doctorId').val(),
        check_staus: check_staus,
        Dml_Indicator: Dml_Indicator,
        visit_report_id: $('#EditVisitReportID').val(),
        patient_checkin_id: $('#patient_checkin_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engage),
        success: function (data) {
            console.log(data);
            var data = JSON.parse(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                var hospitalid = '', branchid = '', visitid = '', patientid = '', doctorid = '', doctorname = '', hospitalname = '', email_id = '', phone_number = '', patient_name = '', branch_mobileno = '', print_date = '';
                if (data.length > 0) {
                    branchid = data[0].branch_id;
                    visitid = data[0].visitreportid;
                    patientid = data[0].patientid;
                    doctorid = data[0].doctorid;
                    hospitalid = data[0].hospitalid;
                    doctorname = data[0].doctorname;
                    hospitalname = data[0].hospitalname;
                    email_id = data[0].patientemailid;
                    phone_number = data[0].phonenumber;
                    patient_name = data[0].patient_name;
                    branch_mobileno = data[0].branch_mobile_no;
                    print_date = data[0].printdate;
                }
                if (!close) {
                    if (!isBookAppointment) {
                        debugger;
                        $('.da-load-casestudy').hide();
                        $('#loaderimg').hide();
                        if ($('#HCasesheetPrintType').val() == 0) {
                            window.location.href = '/PatientDashboard/PPDF?visitreportid=' + $('#VisitReportID').val() + '&lantype=' + $('#sellangs').val() + '&btnval=1';
                        }
                        else {

                            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,
                                patient_name: patient_name,
                                branch_mobileno: branch_mobileno,
                                print_date: print_date
                            }
                            $.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');
                                    window.location.href = '/Dashboard';
                                }
                            });


                            //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.location.href = link;
                            //        window.open(link, '_blank');
                            //        window.location.href = '/Dashboard';

                            //    }
                            //});
                        }
                    }
                    else {
                        isBookAppointment = false;
                    }
                }
                else {
                    window.location.href = '/Dashboard';
                }
            }
            else {
                console.log
            }
        }

    });
}

function CloseCasestudy() {
    debugger;
    close = true;
    var r, msg = "Are you sure, you want to close video chat?";
    if ($('#appointment_type').val() == "2" && ($('#videomodal').is(':visible'))) {
        r = confirm(msg);
        if (r == true) {
            $('.da-load-casestudy').show();
            SaveGeneralInformation();
            //diagnosis();
            //Engagecloseds();
        }
        else {
        }
    }
    else {
        $('.da-load-casestudy').show();
        SaveGeneralInformation();
        //diagnosis();
        //Engagecloseds();
    }
}
function rightcasesheetclose() {
    pagess14();
}

// lab ending point


//next Appoinment starting point

function nextAppoinment() {
    debugger;
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/VisitReport_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            $('.da-load-casestudy').hide();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                console.log(data);
                $("#btnNext").html('Update');
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    console.log(data);
                    if (data.length > 0) {
                        $('#datepickern').val(data[0].next_appointment_date);
                        $('#txtNANotes').val(data[0].next_appointment_notes);
                        $('#txtTestRequest').val(data[0].test_request_text);
                        $('#selTestRequest').val(data[0].test_request_val);
                        var procedure = data[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[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 xrayfind = data[0].xray_findings;
                        if ($('#txtXrayFindings').hasClass('tag-editor-hidden-src')) {
                            if (xrayfind == '' || xrayfind == null) {
                                $('#divtxtInvestigation > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var xrayfindsplit = xrayfind.split(',');
                                var tr = [];
                                if (xrayfindsplit.length > 0) {
                                    for (var i = 0; i < xrayfindsplit.length; i++) {
                                        tr.push(xrayfindsplit[i]);
                                    }
                                    $('#txtXrayFindings').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtInvestigation > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtXrayFindings').val(xrayfind);
                        }

                        //MRI findings
                        var xmrifind = data[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);
                        }


                        var advice = data[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);
                        }

                        var lab_findings = data[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[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);
                        }
                        debugger;
                        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);
                        $('#txt_visit_followup').val(data[0].followup);
                        debugger;
                        // $('#txtpastadverseevents').val(data[0].past_adverse_events);
                        var past_adverse_events = data[0].past_adverse_events;
                        if ($('#txtpastadverseevents').hasClass('tag-editor-hidden-src')) {
                            if (past_adverse_events == '' || past_adverse_events == null) {
                                $('#divtxtpastadverseevents > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var past_adverse_eventssplit = past_adverse_events.split(',');
                                var tr = [];
                                if (past_adverse_eventssplit.length > 0) {
                                    for (var i = 0; i < past_adverse_eventssplit.length; i++) {
                                        tr.push(past_adverse_eventssplit[i]);
                                    }
                                    $('#txtpastadverseevents').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtpastadverseevents > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtpastadverseevents').val(past_adverse_events);
                        }

                        //$('#txtgeneralexamination').val(data[0].general_examination);

                        var general_exam = data[0].general_examination;
                        if ($('#txtgeneralexamination').hasClass('tag-editor-hidden-src')) {
                            if (general_exam == '' || general_exam == null) {
                                $('#divtxtgeneralexamination > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var general_examsplit = general_exam.split(',');
                                var tr = [];
                                if (general_examsplit.length > 0) {
                                    for (var i = 0; i < general_examsplit.length; i++) {
                                        tr.push(general_examsplit[i]);
                                    }
                                    $('#txtgeneralexamination').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtgeneralexamination > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtgeneralexamination').val(general_exam);
                        }

                        //$('#txtlocalexamination').val(data[0].local_examination);

                        var local_exam = data[0].local_examination;
                        if ($('#txtlocalexamination').hasClass('tag-editor-hidden-src')) {
                            if (local_exam == '' || local_exam == null) {
                                $('#divtxtlocalexamination > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var local_examsplit = local_exam.split(',');
                                var tr = [];
                                if (local_examsplit.length > 0) {
                                    for (var i = 0; i < local_examsplit.length; i++) {
                                        tr.push(local_examsplit[i]);
                                    }
                                    $('#txtlocalexamination').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtlocalexamination > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtlocalexamination').val(local_exam);
                        }

                        //$('#txtabdomengirth').val(data[0].abdomen_girth);

                        var abdomen = data[0].abdomen_girth;
                        if ($('#txtabdomengirth').hasClass('tag-editor-hidden-src')) {
                            if (abdomen == '' || abdomen == null) {
                                $('#divtxtabdomengirth > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                            }
                            else {
                                var abdomensplit = abdomen.split(',');
                                var tr = [];
                                if (abdomensplit.length > 0) {
                                    for (var i = 0; i < abdomensplit.length; i++) {
                                        tr.push(abdomensplit[i]);
                                    }
                                    $('#txtabdomengirth').tagEditor('addTag', tr);
                                }
                                else {
                                    $('#divtxtabdomengirth > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                                }
                            }
                        }
                        else {
                            $('#txtabdomengirth').val(abdomen);
                        }

                        $('#ChkDentalType').val(data[0].dental_type);
                        $('a[data-toggle=ChkDentalType][data-title="' + data[0].dental_type + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkDentalType][data-title="' + data[0].dental_type + '"]').addClass('active');


                        $('#txtdental_procedure_done').val(data[0].dental_procedure_done);
                        $('#txtdental_procedure_remaining').val(data[0].dental_procedure_remaining);

                        $('#txtdentalhardtissue').val(data[0].dental_hard_tissue);
                        $('#txtdentalsofttissue').val(data[0].dental_soft_tissue);

                        var past_medical_history = data[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[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();

                            }

                        }

                        //review notes
                        var reviewNotes = data[0].review_notes;
                        if ($('#txtReviewNotes').hasClass('tag-editor-hidden-src')) {
                            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);
                        }

                        //counselling
                        var counselling = data[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);
                        }


                        //observation                       
                        var observVal = data[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);
                        }


                        //investigation                       
                        var investigVal = data[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);
                        }

                        $('#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 diagnosis = data[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);
                        }

                        $('#chkalcholintake').val(data[0].alchol_intake);
                        $('a[data-toggle=chkalcholintake][data-title="' + data[0].alchol_intake + '"]').removeClass('not-active');
                        $('a[data-toggle=chkalcholintake][data-title="' + data[0].alchol_intake + '"]').addClass('active');

                        $('#chksubstanceintake').val(data[0].substance_intake);
                        $('a[data-toggle=chksubstanceintake][data-title="' + data[0].substance_intake + '"]').removeClass('not-active');
                        $('a[data-toggle=chksubstanceintake][data-title="' + data[0].substance_intake + '"]').addClass('active');

                        $('#chksmoking').val(data[0].smoking);
                        $('a[data-toggle=chksmoking][data-title="' + data[0].smoking + '"]').removeClass('not-active');
                        $('a[data-toggle=chksmoking][data-title="' + data[0].smoking + '"]').addClass('active');

                        $('#chkspecialreligious').val(data[0].special_religious);
                        $('a[data-toggle=chkspecialreligious][data-title="' + data[0].special_religious + '"]').removeClass('not-active');
                        $('a[data-toggle=chkspecialreligious][data-title="' + data[0].special_religious + '"]').addClass('active');
                    }
                    else {
                        $('#divtxtdiagnosis > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');
                    }
                }
            }
            else {
                console.log(data);
            }

            LoadDentalCasesheetData();

        }
    });
}

$('#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 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();
    NextUpdate();
}

function NextInsert() {
    if ($('#datepickern').val().length > 0) {
        var sdate = $('#datepickern').val().split('/');
        var cdate = '';
        if (sdate.length > 1) {
            cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
        }
        var today_date = new Date();
        var now = new Date();
        var date = today_date.getFullYear() + "-" + (today_date.getMonth() + 1) + "-" + today_date.getDate();
        var Dml_Indicator;
        if ($("#btnNext").html() == "Save") {
            Dml_Indicator = 'U';
        }
        else {
            Dml_Indicator = 'UU';
        }
        var prescription_note = "";
        var visit_report_id = "";
        var next_appointment_date = cdate;
        var medicine_prescription_id = "";
        var prescription_scan_id = "";
        var create_visit_report = {
            Dml_Indicator: Dml_Indicator,
            prescription_note: prescription_note,
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            next_appointment_date: next_appointment_date,
            created_on: date,
            doctor_id: $('#doctorId').val()
        }
        $.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) {
            }
        });
    }
}

function NextUpdate() {
    var sdate = $('#datepickern').val().split('/');
    var cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
    var Dml_Indicator;
    if ($("#btnNext").html() == "Save") {
        Dml_Indicator = 'U';
    }
    else {
        Dml_Indicator = 'UU';
    }
    var prescription_note = "";
    var visit_report_id = "";
    var next_appointment_date = cdate;
    var medicine_prescription_id = "";
    var prescription_scan_id = "";

    var create_visit_report = {
        Dml_Indicator: Dml_Indicator,
        prescription_note: prescription_note,
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        next_appointment_date: next_appointment_date,
        doctor_id: $('#doctorId').val()
    }
    $.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) {

        }

    });
}


function diagnosis() {
    debugger;
    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();

    // 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 com = $('#txtComplaints_1').val().replaceAll(/,/g, ", ");
    var Sys = $('#txtSys').val();
    var Dia = $('#txtDia').val();
    var bp_flag_type;

    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 sdate = $('#datepickern').val().split('/');
    var cdate = '';
    if (sdate.length > 1) {
        cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];
    }

    const str1 = $('#txtdiagnosis').val().replaceAll(/,/g, ", ")
    debugger;
    var create_visit_report = {
        Dml_Indicator: 'DU',
        diagnosis: $('#txtdiagnosis').val().replaceAll(/,/g, ", "),
        treatment_procedure: $('#txtprodcedure').val(),
        visit_report_id: $('#VisitReportID').val(),
        complaints: com,
        next_appointment_date: cdate,
        Notes: $('#txtnotes_1').val().replaceAll(/,/g, ", "),
        instruction: $('#txt_visit_instruction').val(),
        observation_val: $('#txtobserv').val(),
        investigation: $('#txtinvetig').val(),
        pulse_rate: $('#txtPulseRate').val(),
        patient_bp_max: $('#txtSys').val(),
        patient_bp_min: $('#txtDia').val(),
        bp_flag_type: bp_flag_type,
        created_by: $('#doctorId').val(),
        spo2: $('#txtSPO2').val(),
        temperature: $('#txtTemperature').val(),
        patient_id: $('#Hdnpatient_id').val(),
        level_of_conscience: $('input:radio[name=optradioConsciences]:checked').val(),
        vas: $('#emoNPDRradio').val(),
        vasduration: $('#txtvasduration').val(),
        vaslocation: $('#txtvaslocation').val(),
        vaspaincharacter: paincharacter1,
        vasfullrisk: frsfa1,
        xray_findings: $('#txtXrayFindings').val(),
        advice: $('#txtAdvice').val().replaceAll(/,/g, ", "),
        counselling: $('#txtCounselling').val(),
        xray_findings_new: $('#txtxrayfind').val(),
        lab_findings: $('#txtlabfinding').val(),
        respiratory_rate: $('#txtRespiratoryRate').val(),
        followup: $('#txt_visit_followup').val(),
        alchol_intake: $('#chkalcholintake').val(),
        substance_intake: $('#chksubstanceintake').val(),
        smoking: $('#chksmoking').val(),
        special_religious: $('#chkspecialreligious').val(),
        review_notes: $('#txtReviewNotes').val(),
        next_appointment_notes: $('#txtNANotes').val(),
        mri_findings: $('#txtmrifinding').val(),

        past_medical_history: pastmedicalhistory1,
        past_adverse_events: $('#txtpastadverseevents').val(),
        general_examination_chk: generalexamination1,
        general_examination: $('#txtgeneralexamination').val(),
        local_examination: $('#txtlocalexamination').val(),
        abdomen_girth: $('#txtabdomengirth').val(),

        dental_type: $('#ChkDentalType').val(),
        dental_procedure_done: $('#txtdental_procedure_done').val(),
        dental_procedure_remaining: $('#txtdental_procedure_remaining').val(),
        test_request_text: $('#txtTestRequest').val(),
        test_request_val: $('#selTestRequest').val(),

        dental_hard_tissue: $('#txtdentalhardtissue').val(),
        dental_soft_tissue: $('#txtdentalsofttissue').val()
    }
    debugger;
    console.log(create_visit_report);
    $.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);
            console.log(data);
            if (data.msg == "Success") {
                pagess14();
            }
            else {
                console.log(data);
            }
        }

    });
}
//next Appointment ending point 



//life style
//Diet

function Notes() {
    var Notesdata = {
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'S'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Dietgoal',
        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 {
                    if (data1.length > 2) {
                        $.each(data1, function (i, emp) {
                            $('#DFood').html(emp.lifestyle_food_preference);
                            $('#DAlchohol').html(emp.lifestyle_alcohol_consumptionl);
                            $('#DCigaratte').html(emp.lifestyle_smoking_value);
                        });
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
    var DDietBP = $('#BP').html();
    var DDietCKD = $('#txtCKD').val();

    $('#Dkidly').html(DDietCKD);
    $('#DBP').html(DDietBP);
}

function loadNotes() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Dietgoal',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        $("#btnDiet").html('Update & Next');

                        var benifits = '';
                        var diet_goal_duration = data[0].diet_goal_duration;
                        var kcal = data[0].kcal;

                        $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').removeClass('not-active');
                        $('a[data-toggle=Etime][data-title="' + diet_goal_duration + '"]').addClass('active');

                        if (kcal == '1500') {
                            $('a[data-toggle=Kcal][data-title=kcal1]').removeClass('not-active');
                            $('a[data-toggle=Kcal][data-title=kcal1]').addClass('active');
                        }
                        if (kcal == '1800') {
                            $('a[data-toggle=Kcal][data-title=kcal2]').removeClass('not-active');
                            $('a[data-toggle=Kcal][data-title=kcal2]').addClass('active');
                        }
                        if (kcal == '2000') {
                            $('a[data-toggle=Kcal][data-title=kcal3]').removeClass('not-active');
                            $('a[data-toggle=Kcal][data-title=kcal3]').addClass('active');
                        }
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            tr = tr + "<tr><td style='display:none;'>" + data[i].type_of_food + "</td>";
                            tr = tr + " <td>" + data[i].type_of_food + "</td>";
                            tr = tr + " <td>" + data[i].no_of_servings + ' Per day' + "</td>";
                            tr = tr + " <td>" + data[i].instructions + "</td>";
                            tr = tr + "</tr>"
                            if (j == 1) {
                                benifits = data[i].benefits;
                                if (benifits == null || benifits == '') {
                                    benifits = '';
                                }
                            }
                            var rowcount = $.trim($('#TableRowCount').val());
                            var tot_row = (Number(rowcount) + 1);
                            $('#TableRowCount').val(tot_row);
                            var sess_data = data[i].type_of_food + "," + data[i].type_of_food + "," + data[i].no_of_servings + "," + data[i].instructions;
                            var ikey = 'row' + tot_row;
                            sessionStorage.setItem(ikey, sess_data);
                        }
                        $('#tblDietChart').append(tr);
                        $('#benifits').html(benifits);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function minval(val) {
    $('#txtdurationweek').val(val);
    var week = $("input[name='Chk_weeks']:checked").length;
    var dur = $('#txtdurationweek').val();
    var tot = (parseFloat(dur) / parseFloat(week)).toFixed();
    tot = isFinite(tot) && tot || 0;
    $('#txtDailyDuration').val(tot);
}

//function loadExercise() {
//    var VisitreportId = {
//        visit_report_id: $('#EditVisitReportID').val(),
//        Dml_Indicator: 'CS'
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/CaseStudy/ExcerciseGoalSet',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(VisitreportId),
//        success: function (data) {
//            if (jQuery.isEmptyObject((data))) {
//            }
//            else {
//                var ExerciseValue = '';
//                var tr = '';
//                var data = JSON.parse(data);
//                if (data.length > 0) {
//                    var excercise_goal_duration_days = data[0].excercise_goal_duration_days;
//                    $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').removeClass('not-active');
//                    $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').addClass('active');
//                    $('#Etimes').val(excercise_goal_duration_days);
//                    $('#txtdurationweek').val(data[0].excercise_duration_per_week);
//                    var monday = data[0].monday_flag;
//                    var tuesday = data[0].tuesday_flag;
//                    var wednesday = data[0].wednesday_flag;
//                    var thusday = data[0].thursday_flag;
//                    var friday = data[0].friday_flag;
//                    var saturday = data[0].saturday_flag;
//                    var sunday = data[0].sunday_flag;
//                    if (monday == 1 && tuesday == 1 && wednesday == 1 && thusday == 1 && friday == 1 && saturday == 1 && sunday == 1) {
//                        $('#Chk_weeks').val('7');
//                    }
//                    else if (monday == 1 && tuesday == 1 && wednesday == 1 && thusday == 1 && friday == 1 && saturday == 1) {
//                        $('#Chk_weeks').val('6');
//                    }
//                    else if (monday == 1 && tuesday == 1 && wednesday == 1 && thusday == 1 && friday == 1) {
//                        $('#Chk_weeks').val('5');
//                    }
//                    else if (monday == 1 && tuesday == 1 && wednesday == 1 && thusday == 1) {
//                        $('#Chk_weeks').val('4');
//                    }
//                    else if (tuesday == 1 && wednesday == 1 && thusday == 1) {
//                        $('#Chk_weeks').val('3');
//                    }
//                    else if (wednesday == 1 && thusday == 1 && friday == 1) {
//                        $('#Chk_weeks').val('2');
//                    }
//                    else if (monday == 1 && tuesday == 1 && wednesday == 1) {
//                        $('#Chk_weeks').val('1');
//                    }
//                    else {
//                        $('#Chk_weeks').val('0');
//                    }
//                    $('#txtDailyDuration').html(data[0].excercise_duration_per_day);

//                    if (data[0].type_of_excercise == 1) {
//                        ExerciseValue = 'Aerobic excercises';
//                    }
//                    if (data[0].type_of_excercise == 2) {
//                        ExerciseValue = 'Brisk walking';
//                    }
//                    if (data[0].type_of_excercise == 3) {
//                        ExerciseValue = 'jogging';
//                    }
//                    if (data[0].type_of_excercise == 4) {
//                        ExerciseValue = 'swimming';
//                    }
//                    if (data[0].type_of_excercise == 5) {
//                        ExerciseValue = 'cycling';
//                    }
//                    if (data[0].type_of_excercise == 6) {
//                        ExerciseValue = 'resistance excercise';
//                    }
//                    tr = tr + '<a class="btn btn-primary btn-lg not-active" data-toggle="TypeExerciseBtn" data-title=' + data[0].type_of_excercise + ' onclick="Instruction(' + data[0].type_of_excercise + ')">' + ExerciseValue + '</a>';
//                    $('.TypeExercise').append(tr);
//                    $('#txtEInstruction').val(data[0].excercise_instructions);
//                    $('#txtEDInstruction').html(data[0].excercise_instruction);
//                    $('#txtExBenefits').html(data[0].excercise_benefits);
//                    $('#TypeExercise').val(data[0].type_of_excercise);
//                    $('#TypeExerciseBtn').val(data[0].type_of_excercise);
//                }
//            }
//        }
//    });
//    DeitPlan();
//    loadAlgorithm();
//}
function loadExercise() {
    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: 'CS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ExcerciseGoalSet',
        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 {
                    var treatment_description = [];
                    var ExerciseValue = '';
                    var tr = '';
                    console.log(data);
                    $('#P_ExerciseTable').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {


                            var excercise_goal_duration_days = data[i].excercise_goal_duration_days;
                            $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').removeClass('not-active');
                            $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').addClass('active');
                            $('#txtdurationweek').val(data[i].excercise_duration_per_week);
                            var monday = data[i].monday_flag;
                            var tuesday = data[i].tuesday_flag;
                            var wednesday = data[i].wednesday_flag;
                            var thusday = data[i].thursday_flag;
                            var friday = data[i].friday_flag;
                            var saturday = data[i].saturday_flag;
                            var sunday = data[i].sunday_flag;

                            var SuggestedDays = ''; var suggestedDaysCount = 0;
                            if (monday == 1) {

                                SuggestedDays = 'Mon';
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (tuesday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Tue';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Tue';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (wednesday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Wed';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Wed';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (thusday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Thu';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Thu';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (friday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Fri';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Fri';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (saturday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Sat';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Sat';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (sunday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Sun';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + '  Sun';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }

                            if (data[0].type_of_excercise == 1) {
                                ExerciseValue = 'Aerobic excercises';
                            }
                            if (data[0].type_of_excercise == 2) {
                                ExerciseValue = 'Brisk walking';
                            }
                            if (data[0].type_of_excercise == 3) {
                                ExerciseValue = 'jogging';
                            }
                            if (data[0].type_of_excercise == 4) {
                                ExerciseValue = 'swimming';
                            }
                            if (data[0].type_of_excercise == 5) {
                                ExerciseValue = 'cycling';
                            }
                            if (data[0].type_of_excercise == 6) {
                                ExerciseValue = 'resistance excercise';
                            }
                            var t = data[i].treatment.split(",");
                            var j = 0;
                            for (var k = 0; k < t.length; k++) {
                                treatment_description[j] = $("#Treatment option[value='" + t[k] + "']").text();
                                j++;
                            }
                            var treatment_description_1 = treatment_description.toString();
                            treatment_description = [];
                            var s = data[i].choose_region.split(",");
                            var n = 0;
                            var choose_Region = [];
                            for (var m = 0; m < s.length; m++) {
                                choose_Region[m] = $("#SelRegion option[value='" + s[m] + "']").text();
                                n++;
                            }
                            var sellRegion = choose_Region.toString();
                            choose_Region = [];
                            tr = tr + "<tr><td>" + sellRegion + "</td><td>" + data[i].op_type + "</td><td>" + data[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].excercise_duration_per_day + "</td><td>" + data[i].sitting + "</td><td>" + data[i].instruction + "</td><td>" + treatment_description_1 + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Exercise' onclick='EditExercise(\"" + data[i].excercise_goal_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Exercise' onclick='DeleteExercise(\"" + (data[i].excercise_goal_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";


                        }
                        $('#P_ExerciseTable').html(tr);
                        // tr = tr + '<span class="btn btn-default  btn-xs btn-rect-bordered" onclick=Instruction(' + data[0].type_of_excercise + ')>' + ExerciseValue + '</span>';
                        //commented for multiple 
                        //tr = tr + '<a class="btn btn-primary btn-lg not-active" data-toggle="TypeExerciseBtn" data-title=' + data[0].type_of_excercise + ' onclick="Instruction(' + data[0].type_of_excercise + ')">' + ExerciseValue + '</a>';
                        //$('.TypeExercise').append(tr);
                        //$('#txtEInstruction').val(data[0].excercise_instructions);
                        //$('#txtEDInstruction').html(data[0].excercise_instruction);
                        //$('#txtExBenefits').html(data[0].excercise_benefits);
                        //$('#TypeExercise').val(data[0].type_of_excercise);
                        //$('#TypeExerciseBtn').val(data[0].type_of_excercise);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
    loadAlgorithm();
}



jQuery('#D3M').change(function () {
    DietBP = $('#BP').html();
    DietCKD = $('#txtCKD').val();
    foodtypes = $('#DFood').html();
    if (foodtypes == 'Vegetarian') {
        foodvalue = '1'
    }
    else if (foodtypes == 'Non-Vegetarian') {
        foodvalue = '2'
    }
    else if (foodtypes == 'Eggetarian') {
        foodvalue = '3'
    }
    else if (foodtypes == 'Vegan') {
        foodvalue = '4'
    }
    else {
        foodvalue = '1'
    }
    if ($(this).prop('checked')) {
        var endDate, StartDate;
        var today = new Date();

        var endDate = new Date();
        var month = endDate.getMonth();
        endDate.setDate(today.getDate() + 90);

        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 (DietBP == 'Normal') {
            DietBP = 0;
        }
        else {
            DietBP = 1;
        }
        if (DietCKD == 'Stage 3A' || DietCKD == 'Stage 3B' || DietCKD == 'Stage 4' || DietCKD == 'Stage 5') {
            DietCKD = 1;
        }
        else {
            DietCKD = 0;
        }

        var PlanDuration = {
            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: '90',
            diet_goal_status: '',
            sodium_restriction: DietBP,
            potassium_restriction: '',
            ckd_restriction: DietCKD,
            diet_goal_set_by: $('#doctorId').val(),
            Dml_Indicator: 'I'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Dietgoal',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PlanDuration),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        if (data.length > 2) {
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    else {

    }
});
var DietBP = '';
var DietCKD = '';
var foodtypes = '';
var foodvalue = '';
var kcal;

jQuery('#Etime').change(function () {
    return false;
    var diet_goal_duration = $('#Etime').val();
    DietBP = $('#BP').html();
    DietCKD = $('#txtCKD').val();
    foodtypes = $('#DFood').html();
    if (foodtypes == 'Vegetarian') {
        foodvalue = '1'
    }
    else if (foodtypes == 'Non-Vegetarian') {
        foodvalue = '2'
    }
    else if (foodtypes == 'Eggetarian') {
        foodvalue = '3'
    }
    else if (foodtypes == 'Vegan') {
        foodvalue = '4'
    }
    else {
        foodvalue = '1'
    }
    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 (DietBP == 'Normal') {
        DietBP = 0;
    }
    else {
        DietBP = 1;
    }
    if (DietCKD == 'Stage 3A' || DietCKD == 'Stage 3B' || DietCKD == 'Stage 4' || DietCKD == 'Stage 5') {
        DietCKD = 1;
    }
    else {
        DietCKD = 0;
    }

    var PlanDuration = {
        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: '',
        sodium_restriction: DietBP,
        potassium_restriction: '',
        ckd_restriction: DietCKD,
        diet_goal_set_by: $('#doctorId').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Dietgoal',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PlanDuration),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 2) {
                        $.each(data1, function (i, emp) {
                            $('#diet_goal_id').val(emp.diet_goal_id);
                        });

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

jQuery('#D6M').change(function () {
    DietBP = $('#BP').html();
    DietCKD = $('#txtCKD').val();
    foodtypes = $('#DFood').html();
    if ($(this).prop('checked')) {
        var endDate, StartDate;
        var today = new Date();

        var endDate = new Date();
        var month = endDate.getMonth();
        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 (DietBP == 'Normal') {
            DietBP = 0;
        }
        else {
            DietBP = 1;
        }

        if (DietCKD == 'Stage 3A' || DietCKD == 'Stage 3B' || DietCKD == 'Stage 4' || DietCKD == 'Stage 5') {
            DietCKD = 1;
        }
        else {
            DietCKD = 0;
        }
        if (foodtypes == 'Vegetarian') {
            foodvalue = '1';
        }
        else if (foodtypes == 'Non-Vegetarian') {
            foodvalue = '2';
        }
        else if (foodtypes == 'Eggetarian') {
            foodvalue = '3';
        }
        else if (foodtypes == 'Vegan') {
            foodvalue = '4';
        }
        else {
            foodvalue = '1';
        }
        var PlanDuration = {
            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: '180',
            diet_goal_status: '',
            sodium_restriction: DietBP,
            potassium_restriction: '',
            ckd_restriction: DietCKD,
            diet_goal_set_by: $('#doctorId').val(),
            Dml_Indicator: 'I'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Dietgoal',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PlanDuration),
            success: function (data) {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data = data1.data;
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        if (data.length > 2) {
                            $.each(data1, function (i, emp) {
                                $('#diet_goal_id').val(emp.diet_goal_id);
                            });
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
    else {
    }
});

jQuery('#Kcal').change(function () {
    var CalVal = $('#Kcal').val();
    if (CalVal == 'kcal1') {
        kcal = 1500;
        DietChart(kcal);
    }
    else if (CalVal == 'kcal2') {
        kcal = 1800;
        DietChart(kcal);
    }
    else if (CalVal == 'kcal3') {
        kcal = 2000;
        DietChart(kcal);
    }
});

function DietChart(kcal) {

    DietBP = $('#BP').html();
    DietCKD = $('#txtCKD').val();
    if (DietBP == 'Normal') {
        DietBP = 0;
    }
    else {
        DietBP = 1;
    }
    if (DietCKD == 'Stage 3A' || DietCKD == 'Stage 3B' || DietCKD == 'Stage 4' || DietCKD == 'Stage 5') {
        DietCKD = 1;
    }
    else {
        DietCKD = 0;
    }
    foodtypes = $('#DFood').html();
    if (foodtypes == 'Vegetarian') {
        foodvalue = '1';
    }
    else if (foodtypes == 'Non-Vegetarian') {
        foodvalue = '2';
    }
    else if (foodtypes == 'Eggetarian') {
        foodvalue = '3';
    }
    else if (foodtypes == 'Vegan') {
        foodvalue = '4';
    }
    else {
        foodvalue = '1';
    }
    var PlanDuration = {
        sodium_restriction: DietBP,
        ckd_restriction: DietCKD,
        type_of_food: foodvalue,
        kcal: kcal,
        Dml_Indicator: 'S'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/DietgoalChart',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PlanDuration),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var DietChart = '';
                    var benifits = '', j = 0, tr = '';
                    $('#tblDietChart tbody').empty();
                    $.each(data1, function (i, emp) {
                        j++;
                        tr = tr + "<tr><td style='display:none;'>" + emp.diet_food_id + "</td>";
                        tr = tr + " <td>" + emp.type_of_food + "</td>";
                        tr = tr + " <td>" + emp.no_of_servings + ' Per day' + "</td>";
                        tr = tr + " <td>" + emp.instructions + "</td>";
                        tr = tr + "</tr>"
                        if (j == 1) {
                            benifits = emp.benifits;
                        }
                        else {
                            benifits = benifits + ',' + emp.benifits;
                        }
                        var rowcount = $.trim($('#TableRowCount').val());
                        var tot_row = (Number(rowcount) + 1);
                        $('#TableRowCount').val(tot_row);
                        var sess_data = emp.diet_food_id + "," + emp.type_of_food + "," + emp.no_of_servings + "," + emp.instructions;
                        var ikey = 'row' + tot_row;
                        sessionStorage.setItem(ikey, sess_data);

                    });
                    $('#tblDietChart').append(tr);
                    $('#benifits').append(benifits);
                }
            }
            else {
                console.log(data1)
            }
        }
    });
}

function page13() {
}

//exercise code started
$('#P_Exercise_Add').click(function () {
    ExerciseSet();

});

//function ExerciseSet() {
//    if ($('#TypeExercise').val() != 0 || $('#txtdurationweek').val() != 0 || $('#Chk_weeks').val() != 0 || $('#txtEInstruction').val() != '') {
//        var excercise_intensity = '3';
//        if ($('#HightIntensity').val() == '2') {
//            excercise_intensity = '2';
//        }
//        var days = $('#Etimes').val();
//        if (days == "") {
//            days = "90";
//        }
//        var endDate, StartDate;
//        var today = new Date();

//        var endDate = new Date();
//        var month = endDate.getMonth();
//        if (days == 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();
//        var mon = 0, tue = 0, wed = 0, thu = 0, fri = 0, sat = 0, sun = 0;
//        if ($('#Chk_weeks').val() == 1) {
//            mon = 1, tue = 1, wed = 1, thu = 0, fri = 0, sat = 0, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 2) {
//            mon = 0, tue = 0, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 3) {
//            mon = 0, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 4) {
//            mon = 1, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 5) {
//            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 6) {
//            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 0;
//        }
//        else if ($('#Chk_weeks').val() == 7) {
//            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 1;
//        }
//        else {
//            $('#PChk_weeks').show();
//            $('#PChk_weeks').fadeOut(8000);
//            $('#PChk_weeks').html('Please Select Suggested Days of the week');
//            $('#Chk_weeks').val(0);
//            $('#Chk_weeks').focus();
//        }
//        var HospitalFacilityData = {
//            patient_id: patient,
//            visit_report_id: $('#VisitReportID').val(),
//            excercise_goal_priority: '',
//            excercise_goal_description: '',
//            excercise_goal_start_date: StartDate,
//            excercise_goal_end_date: endDate,
//            excercise_goal_duration_days: days,
//            excercise_instructions: $('#txtEInstruction').val(),
//            excercise_intensity: excercise_intensity,
//            excercise_goal_set_by: $('#doctorId').val(),
//            excercise_goal_status: '1',
//            Dml_Indicator: 'I',

//            type_of_excercise: $('#TypeExerciseBtn').val(),
//            excercise_description: $('#txtEInstruction').val(),
//            excercise_instruction: $('#txtEDInstruction').html(),
//            excercise_benefits: $('#txtExBenefits').html(),
//            excercise_duration_per_week: $('#txtdurationweek').val(),
//            excercise_duration_per_day: $('#txtDailyDuration').html(),
//            monday_flag: mon,
//            tuesday_flag: tue,
//            wednesday_flag: wed,
//            thursday_flag: thu,
//            friday_flag: fri,
//            saturday_flag: sat,
//            sunday_flag: sun
//        }
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/caseStudy/ExcerciseGoalSet',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(HospitalFacilityData),
//            success: function (data) {
//            }
//        });
//    }
//    SaveGeneralInformation();
//}
function ExerciseSet() {
    debugger;
    if ($.trim($('#SelRegion :selected').val()) == "" || $('#SelRegion :selected').val() == "0") {
        $('#PSelRegion').show();
        $('#PSelRegion').fadeOut(8000);
        $('#PSelRegion').html('Choose Region');
        $('#SelRegion').focus();
        $('#SelRegion :selected').val('0');
        return false;
    }
    if ($.trim($('#Chk_weeks :selected').val()) == "" || $('#Chk_weeks :selected').val() == "0") {
        $('#PChk_weeks').show();
        $('#PChk_weeks').fadeOut(8000);
        $('#PChk_weeks').html('Choose Days');
        $('#Chk_weeks').focus();
        $('#Chk_weeks :selected').val('0');
        return false;
    }
    else {
        var treatment1 = $("#Treatment").val().toString();
        var selRegion1 = $("#SelRegion").val().toString();
        var excercise_intensity = '3';
        if ($('#HightIntensity').val() == '2') {
            excercise_intensity = '2';
        }
        var days = '90';
        var endDate, StartDate;
        var today = new Date();

        var endDate = new Date();
        var month = endDate.getMonth();
        if (days == 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();
        var mon = 0, tue = 0, wed = 0, thu = 0, fri = 0, sat = 0, sun = 0;
        if ($('#Chk_weeks').val() == 1) {
            mon = 1, tue = 1, wed = 1, thu = 0, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 2) {
            mon = 0, tue = 0, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 3) {
            mon = 0, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 4) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 5) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 6) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 7) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 1;
        }
        else {
            $('#PChk_weeks').show();
            $('#PChk_weeks').fadeOut(8000);
            $('#PChk_weeks').html('Please Select Suggested Days of the week');
            $('#Chk_weeks').val(0);
            $('#Chk_weeks').focus();
        }
        var Durations = $('#hndduration_1').val();
        var day_1 = $('#days_1').val();
        if (day_1 == '' || day_1 == null) {
        }
        else {
            var days_1 = 0;
            if (Durations == 1) {
                days_1 = day_1;
            }
            else if (Durations == 2) {
                days_1 = ((day_1) * (7));
            }
            else if (Durations == 3) {
                days_1 = ((day_1) * (30));
            }
            else if (Durations == 4) {
                days_1 = ((day_1) * (365));
            }
            else if (Durations == 5) {
                days_1 = "Life Long"
            }
            else {

            }
        }
        var daily = $('#txtDailyDuration').val().split(" ");
        var HospitalFacilityData = {
            patient_id: patient,
            visit_report_id: $('#VisitReportID').val(),
            excercise_goal_priority: '',
            excercise_goal_description: '',
            excercise_goal_start_date: StartDate,
            excercise_goal_end_date: endDate,
            excercise_goal_duration_days: days,
            excercise_instructions: $('#txtEInstruction').val(),
            excercise_intensity: excercise_intensity,
            excercise_goal_set_by: $('#doctorId').val(),
            excercise_goal_status: '1',
            Dml_Indicator: 'I',

            type_of_excercise: $('#TypeExerciseBtn').val(),
            excercise_description: $('#txtEInstruction').val(),
            excercise_instruction: $('#txtEDInstruction').html(),
            excercise_benefits: $('#txtExBenefits').html(),
            excercise_duration_per_week: $('#txtdurationweek').val(),
            excercise_duration_per_day: $('#txtDailyDuration').val(),
            monday_flag: mon,
            tuesday_flag: tue,
            wednesday_flag: wed,
            thursday_flag: thu,
            friday_flag: fri,
            saturday_flag: sat,
            sunday_flag: sun,
            sitting: $('#txtSittings').val(),
            treatment_1: treatment1,
            days_to_take: days_1,
            choose_region: selRegion1
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/ExcerciseGoalSet',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(HospitalFacilityData),
            success: function (data) {
                var data = JSON.parse(data);
                console.log(data);
                debugger;
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        var tr = '';
                        var treatment_description = [];
                        console.log(data);
                        $('#P_ExerciseTable').empty();
                        if (data.length > 0) {
                            for (var i = 0; i < data.length; i++) {

                                var monday = data[i].monday_flag;
                                var tuesday = data[i].tuesday_flag;
                                var wednesday = data[i].wednesday_flag;
                                var thusday = data[i].thursday_flag;
                                var friday = data[i].friday_flag;
                                var saturday = data[i].saturday_flag;
                                var sunday = data[i].sunday_flag;

                                var SuggestedDays = ''; var suggestedDaysCount = 0;
                                if (monday == 1) {

                                    SuggestedDays = 'Mon';
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (tuesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Tue';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Tue';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (wednesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Wed';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Wed';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (thusday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Thu';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Thu';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (friday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Fri';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Fri';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (saturday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sat';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Sat';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (sunday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sun';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + '  Sun';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                var t = data[i].treatment.split(",");
                                var j = 0;
                                for (var k = 0; k < t.length; k++) {
                                    treatment_description[j] = $("#Treatment option[value='" + t[k] + "']").text();
                                    j++;
                                }
                                var treatment_description_1 = treatment_description.toString();
                                treatment_description = [];
                                var s = data[i].choose_region.split(",");
                                var n = 0;
                                var choose_Region = [];
                                for (var m = 0; m < s.length; m++) {
                                    choose_Region[m] = $("#SelRegion option[value='" + s[m] + "']").text();
                                    n++;
                                }

                                tr = tr + "<tr><td>" + choose_Region.toString() + "</td><td>" + data[i].op_type + "</td><td>" + data[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].excercise_duration_per_day + "</td><td>" + data[i].sitting + "</td><td>" + data[i].instruction + "</td><td>" + treatment_description_1 + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Exercise' onclick='EditExercise(\"" + data[i].excercise_goal_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Exercise' onclick='DeleteExercise(\"" + (data[i].excercise_goal_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                            }
                        }
                        $('#P_ExerciseTable').html(tr);
                        $('#txtSittings').val('');
                        $('#txtEInstruction').val('');
                        $('#txtDailyDuration').val('');
                        $('#SelRegion').val('').change();
                        //$('ul li').remove();

                        $('#SelPrePostOP').val('');
                        $('#SelPrePostOP').empty();
                        $('#TypeExercise').val('');
                        $('#TypeExercise').empty();
                        $('#TypeExerciseBtn').val('');
                        $('#Treatment').val('').change();
                        $('#duration_days_1').prop('checked', true);
                        $('#duration_week_1').prop('checked', false);
                        $('#duration_month_1').prop('checked', false);
                        $('p.duration_days_1').addClass('text_before_btn_1');
                        $('p.duration_week_1').removeClass('text_before_btn_1');
                        $('p.duration_month_1').removeClass('text_before_btn_1');
                        $('.duration_disp').html('Days');
                        $('#hndduration_1').val(1);
                        $('#setDurationUnit_1').text("Days");
                        $('#days_1').val('');
                        $('#Chk_weeks').val(0);
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
}
$('#P_Update_Exercise').click(function () {
    if ($.trim($('#SelRegion :selected').val()) == "" || $('#SelRegion :selected').val() == "0") {
        $('#PSelRegion').show();
        $('#PSelRegion').fadeOut(8000);
        $('#PSelRegion').html('Choose Region');
        $('#SelRegion').focus();
        $('#SelRegion :selected').val('0');
        return false;
    }
    if ($.trim($('#Chk_weeks :selected').val()) == "" || $('#Chk_weeks :selected').val() == "0") {
        $('#PChk_weeks').show();
        $('#PChk_weeks').fadeOut(8000);
        $('#PChk_weeks').html('Choose Days');
        $('#Chk_weeks').focus();
        $('#Chk_weeks :selected').val('0');
        return false;
    }
    else {
        var treatment_description = [];
        var treatment1 = $("#Treatment").val().toString();
        var selRegion1 = $("#SelRegion").val().toString();
        var excercise_intensity = '3';
        if ($('#HightIntensity').val() == '2') {
            excercise_intensity = '2';
        }
        var days = '90';
        var endDate, StartDate;
        var today = new Date();

        var endDate = new Date();
        var month = endDate.getMonth();
        if (days == 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();
        var mon = 0, tue = 0, wed = 0, thu = 0, fri = 0, sat = 0, sun = 0;
        if ($('#Chk_weeks').val() == 1) {
            mon = 1, tue = 1, wed = 1, thu = 0, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 2) {
            mon = 0, tue = 0, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 3) {
            mon = 0, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 4) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 0, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 5) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 0, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 6) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 0;
        }
        else if ($('#Chk_weeks').val() == 7) {
            mon = 1, tue = 1, wed = 1, thu = 1, fri = 1, sat = 1, sun = 1;
        }
        else {
            $('#PChk_weeks').show();
            $('#PChk_weeks').fadeOut(8000);
            $('#PChk_weeks').html('Please Select Suggested Days of the week');
            $('#Chk_weeks').val(0);
            $('#Chk_weeks').focus();
        }
        var Durations = $('#hndduration_1').val();
        var day_1 = $('#days_1').val();
        if (day_1 == '' || day_1 == null) {
        }
        else {
            var days_1 = 0;
            if (Durations == 1) {
                days_1 = day_1;
            }
            else if (Durations == 2) {
                days_1 = ((day_1) * (7));
            }
            else if (Durations == 3) {
                days_1 = ((day_1) * (30));
            }
            else if (Durations == 4) {
                days_1 = ((day_1) * (365));
            }
            else if (Durations == 5) {
                days_1 = "Life Long"
            }
            else {

            }
        }
        var HospitalFacilityData = {
            patient_id: patient,
            visit_report_id: $('#VisitReportID').val(),
            excercise_goal_priority: '',
            excercise_goal_description: '',
            excercise_goal_start_date: StartDate,
            excercise_goal_end_date: endDate,
            excercise_goal_duration_days: days,
            excercise_instructions: $('#txtEInstruction').val(),
            excercise_intensity: excercise_intensity,
            excercise_goal_set_by: $('#doctorId').val(),
            excercise_goal_status: '1',
            Dml_Indicator: 'U',

            type_of_excercise: $('#TypeExerciseBtn').val(),
            excercise_description: $('#txtEInstruction').val(),
            excercise_instruction: $('#txtEDInstruction').html(),
            excercise_benefits: $('#txtExBenefits').html(),
            excercise_duration_per_week: $('#txtdurationweek').val(),
            excercise_duration_per_day: $('#txtDailyDuration').val(),
            monday_flag: mon,
            tuesday_flag: tue,
            wednesday_flag: wed,
            thursday_flag: thu,
            friday_flag: fri,
            saturday_flag: sat,
            sunday_flag: sun,
            sitting: $('#txtSittings').val(),
            excercise_goal_id: $('#HdnExerciseGoalID').val(),
            treatment_1: treatment1,
            days_to_take: days_1,
            choose_region: selRegion1
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/ExcerciseGoalSet',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(HospitalFacilityData),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        var tr = '';
                        $('#P_ExerciseTable').empty();
                        if (data.length > 0) {
                            for (var i = 0; i < data.length; i++) {
                                var monday = data[i].monday_flag;
                                var tuesday = data[i].tuesday_flag;
                                var wednesday = data[i].wednesday_flag;
                                var thusday = data[i].thursday_flag;
                                var friday = data[i].friday_flag;
                                var saturday = data[i].saturday_flag;
                                var sunday = data[i].sunday_flag;

                                var SuggestedDays = ''; var suggestedDaysCount = 0;
                                if (monday == 1) {

                                    SuggestedDays = 'Mon';
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (tuesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Tue';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Tue';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (wednesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Wed';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Wed';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (thusday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Thu';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Thu';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (friday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Fri';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Fri';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (saturday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sat';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Sat';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (sunday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sun';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + '  Sun';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                var t = data[i].treatment.split(",");
                                var j = 0;
                                for (var k = 0; k < t.length; k++) {
                                    treatment_description[j] = $("#Treatment option[value='" + t[k] + "']").text();
                                    j++;
                                }
                                var treatment_description_1 = treatment_description.toString();
                                treatment_description = [];
                                var s = data[i].choose_region.split(",");
                                var n = 0;
                                var choose_Region = [];
                                for (var m = 0; m < s.length; m++) {
                                    choose_Region[m] = $("#SelRegion option[value='" + s[m] + "']").text();
                                    n++;
                                }

                                tr = tr + "<tr><td>" + choose_Region.toString() + "</td><td>" + data[i].op_type + "</td><td>" + data[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].excercise_duration_per_day + "</td><td>" + data[i].sitting + "</td><td>" + data[i].instruction + "</td><td>" + treatment_description_1 + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Exercise' onclick='EditExercise(\"" + data[i].excercise_goal_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Exercise' onclick='DeleteExercise(\"" + (data[i].excercise_goal_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                            }
                        }
                        $('#P_ExerciseTable').html(tr);
                        $('#txtSittings').val('');
                        $('#txtEInstruction').val('');
                        $('#txtDailyDuration').val('');
                        $('#SelRegion').val('').change();
                        $('#SelPrePostOP').val('');
                        $('#SelPrePostOP').empty();
                        $('#TypeExercise').val('');
                        $('#TypeExercise').empty();
                        $('#TypeExerciseBtn').val('');
                        $('#HdnExerciseGoalID').val('');
                        //$('ul li').remove();
                        $('#Treatment').val('').change();
                        $('#P_Exercise_Add').show();
                        $('#P_Update_Exercise').hide();
                        $('#duration_days_1').prop('checked', true);
                        $('#duration_week_1').prop('checked', false);
                        $('#duration_month_1').prop('checked', false);
                        $('p.duration_days_1').addClass('text_before_btn_1');
                        $('p.duration_week_1').removeClass('text_before_btn_1');
                        $('p.duration_month_1').removeClass('text_before_btn_1');
                        $('#setDurationUnit_1').text("Days");
                        $('.duration_disp').html('Days');
                        $('#hndduration_1').val(1);
                        $('#days_1').val('');
                        $('#Chk_weeks').val(0);

                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
});
function EditExercise(exercise_goal_id) {
    var treatment_description = [];
    $('#HdnExerciseGoalID').val(exercise_goal_id);

    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'ES',
        excercise_goal_id: exercise_goal_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/ExcerciseGoalSet',
        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 {
                    var ExerciseValue = '';
                    var tr = '';
                    console.log(data);
                    if (data.length > 0) {
                        //for (var i = 0; i < data.length; i++) {
                        var excercise_goal_duration_days = data[0].excercise_goal_duration_days;
                        $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').removeClass('not-active');
                        $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').addClass('active');
                        $('#txtdurationweek').val(data[0].excercise_duration_per_week);
                        var monday = data[0].monday_flag;
                        var tuesday = data[0].tuesday_flag;
                        var wednesday = data[0].wednesday_flag;
                        var thursday = data[0].thursday_flag;
                        var friday = data[0].friday_flag;
                        var saturday = data[0].saturday_flag;
                        var sunday = data[0].sunday_flag;

                        //if (monday == 1) {
                        //    $('#emo').prop('checked', true);
                        //    // $('a[data-toggle=Etimes][data-title="' + excercise_goal_duration_days + '"]').addClass('active');
                        //}
                        //if (tuesday == 1) {
                        //    $('#etu').prop('checked', true);
                        //}
                        //if (wednesday == 1) {
                        //    $('#ewe').prop('checked', true);
                        //}
                        //if (thusday == 1) {
                        //    $('#ethu').prop('checked', true);
                        //}
                        //if (friday == 1) {
                        //    $('#efri').prop('checked', true);
                        //}
                        //if (saturday == 1) {
                        //    $('#esat').prop('checked', true);
                        //}
                        //if (sunday == 1) {
                        //    $('#esu').prop('checked', true);
                        //}
                        $('#txtDailyDuration').val(data[0].excercise_duration_per_day);

                        if (data[0].type_of_excercise == 1) {
                            ExerciseValue = 'Aerobic excercises';
                        }
                        if (data[0].type_of_excercise == 2) {
                            ExerciseValue = 'Brisk walking';
                        }
                        if (data[0].type_of_excercise == 3) {
                            ExerciseValue = 'jogging';
                        }
                        if (data[0].type_of_excercise == 4) {
                            ExerciseValue = 'swimming';
                        }
                        if (data[0].type_of_excercise == 5) {
                            ExerciseValue = 'cycling';
                        }
                        if (data[0].type_of_excercise == 6) {
                            ExerciseValue = 'resistance excercise';
                        }





                        // tr = tr + '<span class="btn btn-default  btn-xs btn-rect-bordered" onclick=Instruction(' + data[0].type_of_excercise + ')>' + ExerciseValue + '</span>';
                        //commented for multiple 
                        tr = tr + '<a class="btn btn-primary btn-lg not-active" data-toggle="TypeExerciseBtn" data-title=' + data[0].type_of_excercise + ' onclick="Instruction(' + data[0].type_of_excercise + ')">' + ExerciseValue + '</a>';
                        $('#TypeExercise').append(tr);
                        $('#txtEInstruction').val(data[0].excercise_instructions);
                        $('#txtEDInstruction').html(data[0].excercise_instruction);
                        $('#txtExBenefits').html(data[0].excercise_benefits);
                        $('#TypeExercise').val(data[0].type_of_excercise);
                        $('#TypeExerciseBtn').val(data[0].type_of_excercise);
                        // $("#SelRegion option:contains(" + data[0].region + ")").attr('selected', true);
                        $('#txtSittings').val(data[0].sitting);
                        //if (data[0].region == "SHOULDER REHAB") {
                        //    $('#SelRegion').val(['1']).trigger('change');
                        //}
                        //else if (data[0].region == "ELBOW REHAB") {
                        //    $('#SelRegion').val(['2']).trigger('change');
                        //}
                        var s = data[0].choose_region.split(",");
                        $('#SelRegion').val(s).trigger('change');
                        //$("#Treatment option:contains(" + t + ")").attr('selected', true);
                        var t = data[0].treatment.split(",");
                        $('#Treatment').val(t).trigger('change');
                        debugger;
                        selectExerciseType(data[0].op_type, data[0].type_of_excercise);

                        $('#P_Exercise_Add').hide();
                        $('#P_Update_Exercise').show();
                        $('#days_1').val(data[0].days_to_take);
                        $('#duration_days').prop('checked', true);
                        $('#duration_week').prop('checked', false);
                        $('#duration_month').prop('checked', false);
                        $('p.duration_days').addClass('text_before_btn_1');
                        $('p.duration_week').removeClass('text_before_btn_1');
                        $('p.duration_month').removeClass('text_before_btn_1');
                        $('.duration_disp_1').html('Days');
                        $('#hndduration_1').val(1);
                        debugger;
                        if (monday == 1 && tuesday == 1 && wednesday == 1) {
                            $('#Chk_weeks').val(1);
                        }
                        if (wednesday == 1 && thursday == 1 && friday == 1) {
                            $('#Chk_weeks').val(2);
                        }
                        if (tuesday == 1 && wednesday == 1 && thursday == 1) {
                            $('#Chk_weeks').val(3);
                        }
                        if (monday == 1 && tuesday == 1 && wednesday == 1 && thursday == 1) {
                            $('#Chk_weeks').val(4);
                        }
                        if (monday == 1 && tuesday == 1 && wednesday == 1 && thursday == 1 && friday == 1) {
                            $('#Chk_weeks').val(5);
                        }
                        if (monday == 1 && tuesday == 1 && wednesday == 1 && thursday == 1 && friday == 1 && saturday == 1) {
                            $('#Chk_weeks').val(6);
                        }
                        if (monday == 1 && tuesday == 1 && wednesday == 1 && thursday == 1 && friday == 1 && saturday == 1 && sunday == 1) {
                            $('#Chk_weeks').val(7);
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

}
function selectExerciseType(op_type, exercise_type) {
    if ($('#SelRegion').val() == '' || $('#SelRegion').val() == null && $('#SelRegion').val() == 0) {
        return false;
    }
    var where_condition = "";
    var selText = [];
    var i = 0;
    $("#SelRegion option:selected").each(function () {
        var $this = $(this);
        if ($this.length) {
            selText[i] = $this.text();
            i++;
        }
    });
    //if ($("#SelRegion").val().length == 1) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '"';
    //}
    //else if ($("#SelRegion").val().length == 2) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '"';
    //}
    //else if ($("#SelRegion").val().length == 3) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '"';
    //}
    //else if ($("#SelRegion").val().length == 4) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '"';
    //}
    //else if ($("#SelRegion").val().length == 5) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '"';
    //}
    //else if ($("#SelRegion").val().length == 6) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '"';
    //}
    //else if ($("#SelRegion").val().length == 7) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '"';
    //}
    //else if ($("#SelRegion").val().length == 8) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '" or region="' + selText[7] + '"';
    //}
    //else if ($("#SelRegion").val().length == 9) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '" or region="' + selText[7] + '" or region="' + selText[8] + '"';
    //}

    if ($("#SelRegion").val().length == 1) {
        where_condition = where_condition + "region ='" + selText[0] + "'";
    }
    else if ($("#SelRegion").val().length == 2) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "'";
    }
    else if ($("#SelRegion").val().length == 3) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "'";
    }
    else if ($("#SelRegion").val().length == 4) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "'";
    }
    else if ($("#SelRegion").val().length == 5) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "'";
    }
    else if ($("#SelRegion").val().length == 6) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "'";
    }
    else if ($("#SelRegion").val().length == 7) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "'";
    }
    else if ($("#SelRegion").val().length == 8) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "'";
    }
    else if ($("#SelRegion").val().length == 9) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "' or region='" + selText[8] + "'";
    }


    var Exercise = {
        Dml_Indicator: "OS",
        condition: where_condition
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Type_Exercise',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Exercise),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    console.log(data);
                    var tr = '<option value=0>--Select--</option>';
                    $('#SelPrePostOP').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<option value=' + (i + 1) + '>' + data[i].op_type + '</option>';
                        }
                        $('#SelPrePostOP').append(tr);


                        $("#SelPrePostOP option:contains(" + op_type + ")").attr('selected', 'selected');
                    }


                    if ($('#SelRegion').val() == '' || $('#SelRegion').val() == null && $('#SelRegion').val() == 0) {
                        return false;
                    }
                    if ($('#SelPrePostOP').val() == '' || $('#SelPrePostOP').val() == null && $('#SelPrePostOP').val() == 0) {
                        return false;
                    }
                    var excercise_intensity_high = '3';
                    if ($('#HightIntensity').val() == '2') {
                        excercise_intensity_high = '2';
                    }
                    where_condition = where_condition + " ) and op_type='" + $('#SelPrePostOP option:selected').text() + "'";
                    var Exercise = {
                        excercise_intensity_high: excercise_intensity_high,
                        Dml_Indicator: "ES",
                        // region: $('#SelRegion option:selected').text(),
                        condition: where_condition,
                        op_type: $('#SelPrePostOP option:selected').text()
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/Type_Exercise',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(Exercise),
                        success: function (data) {
                            var data = JSON.parse(data);
                            // var data = data.data;
                            if (data.msg == "Success") {
                                var data = data.data;
                                if (jQuery.isEmptyObject((data))) {
                                }
                                else {
                                    var regionRow = '';
                                    var tr = '<option value=0>--Select--</option>', ExerciseValue = '';
                                    $('.TypeExercise').empty();
                                    if (data.length > 0) {
                                        for (var i = 0; i < data.length; i++) {

                                            tr = tr + '<option value=' + data[i].type_of_excercise + '>' + data[i].excercise_description + '</option>';


                                        }
                                        $('#TypeExercise').append(tr);
                                        $('#TypeExercise').val(exercise_type);
                                    }
                                }
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });

                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function DeleteExercise(exercise_goal_id) {
    var visit_id;
    if ($('#VisitReportID').val() != '') visit_id = $('#VisitReportID').val();
    else visit_id = $('#EditVisitReportID').val();
    var HospitalFacilityData = {
        visit_report_id: visit_id,
        excercise_goal_id: exercise_goal_id,
        Dml_Indicator: 'D'
    }
    var j = 0;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/ExcerciseGoalSet',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalFacilityData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#P_ExerciseTable').empty();
                }
                else {
                    debugger;
                    var tr = '';
                    var treatment_description = [];
                    console.log(data);
                    $('#P_ExerciseTable').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {

                            var monday = data[i].monday_flag;
                            var tuesday = data[i].tuesday_flag;
                            var wednesday = data[i].wednesday_flag;
                            var thusday = data[i].thursday_flag;
                            var friday = data[i].friday_flag;
                            var saturday = data[i].saturday_flag;
                            var sunday = data[i].sunday_flag;

                            var SuggestedDays = ''; var suggestedDaysCount = 0;
                            if (monday == 1) {

                                SuggestedDays = 'Mon';
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (tuesday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Tue';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Tue';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (wednesday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Wed';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Wed';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (thusday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Thu';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Thu';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (friday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Fri';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Fri';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (saturday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Sat';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + ',  Sat';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            if (sunday == 1) {
                                if (SuggestedDays == '') {
                                    SuggestedDays = '  Sun';
                                }
                                else {
                                    SuggestedDays = SuggestedDays + '  Sun';
                                }
                                suggestedDaysCount = suggestedDaysCount + 1;
                            }
                            var t = data[i].treatment.split(",");
                            for (var k = 0; k < t.length; k++) {
                                treatment_description[j] = $("#Treatment option[value='" + t[k] + "']").text();
                                j++;
                            }
                            var treatment_description_1 = treatment_description.toString();
                            treatment_description = [];
                            var s = data[i].choose_region.split(",");
                            var n = 0;
                            var choose_Region = [];
                            for (var m = 0; m < s.length; m++) {
                                choose_Region[m] = $("#SelRegion option[value='" + s[m] + "']").text();
                                n++;
                            }
                            var sellRegion = choose_Region.toString();
                            choose_Region = [];
                            tr = tr + "<tr><td>" + sellRegion + "</td><td>" + data[i].op_type + "</td><td>" + data[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].excercise_duration_per_day + "</td><td>" + data[i].sitting + "</td><td>" + data[i].instruction + "</td><td>" + treatment_description_1 + "</td><td><button class='btn addicon-btn btn-sm mr20' title='Edit Exercise' onclick='EditExercise(\"" + data[i].excercise_goal_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Exercise' onclick='DeleteExercise(\"" + (data[i].excercise_goal_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        }
                    }
                    $('#P_ExerciseTable').html(tr);

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


$("input[name='Chk_weeks']").change(function () {
});

$('#Chk_weeks').change(function () {
    var week = $('#Chk_weeks').val();
    if (week == "1" || week == "2") {
        week = "3";
    }
    var dur = $('#txtdurationweek').val();
    var tot = (dur / week).toFixed();
    tot = isFinite(tot) && tot || 0;
    $('#txtDailyDuration').html(tot);
});

$('#txtdurationweek').change(function () {
    var week = $('#Chk_weeks').val();
    var dur = $('#txtdurationweek').val();
    var tot = (dur / week).toFixed();
    tot = isFinite(tot) && tot || 0;
    $('#txtDailyDuration').html(tot);
});

$("input[name='Etimes']").change(function () {
});

var chkexercise = 0;
//$('#PlanDuration-section_Exercise').click(function () {
//    chkexercise++;
//    if (chkexercise == 1) {
//        var excercise_intensity_high = '3';
//        if ($('#HightIntensity').val() == '2') {
//            excercise_intensity_high = '2';
//        }
//        var Exercise = {
//            excercise_intensity_high: excercise_intensity_high,
//            Dml_Indicator: "S"
//        }
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/caseStudy/Type_Exercise',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(Exercise),
//            success: function (data) {
//                if (jQuery.isEmptyObject((data))) {
//                }
//                else {
//                    var data = JSON.parse(data);
//                    var tr = '<option value=0>--Select--</option>', ExerciseValue = '';
//                    $('.TypeExercise').empty();
//                    if (data.length > 0) {
//                        for (var i = 0; i < data.length; i++) {
//                            if (data[i].type_of_excercise == 1) {
//                                ExerciseValue = 'Aerobic excercises';
//                            }
//                            if (data[i].type_of_excercise == 2) {
//                                ExerciseValue = 'Brisk walking';
//                            }
//                            if (data[i].type_of_excercise == 3) {
//                                ExerciseValue = 'jogging';
//                            }
//                            if (data[i].type_of_excercise == 4) {
//                                ExerciseValue = 'swimming';
//                            }
//                            if (data[i].type_of_excercise == 5) {
//                                ExerciseValue = 'cycling';
//                            }
//                            if (data[i].type_of_excercise == 6) {
//                                ExerciseValue = 'resistance excercise';
//                            }
//                            tr = tr + '<option value=' + data[i].type_of_excercise + '>' + ExerciseValue + '</option>';
//                        }
//                        $('#TypeExercise').append(tr);
//                        loadExercise();
//                    }
//                }
//            }
//        });
//    }
//});
$('#PlanDuration-section_Exercise').click(function () {
    chkexercise++;
    if (chkexercise == 1) {
        var excercise_intensity_high = '3';
        if ($('#HightIntensity').val() == '2') {
            excercise_intensity_high = '2';
        }
        var Exercise = {
            excercise_intensity_high: excercise_intensity_high,
            Dml_Indicator: "RS"
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Type_Exercise',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Exercise),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        var tr = '<option value=0>--Select--</option>';
                        $('#SelRegion').empty();
                        if (data.length > 0) {
                            for (var i = 0; i < data.length; i++) {
                                tr = tr + '<option value=' + (i + 1) + '>' + data[i].region + '</option>';
                            }
                            $('#SelRegion').append(tr);
                            loadTreatment();
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        });

    }
});
function loadTreatment() {
    debugger;
    var data = {
        Dml_Indicator: "TL"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Type_Exercise',
        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);
                    var tr = '<option value=0>--Select--</option>';
                    $('#Treatment').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<option value=' + data[i].id + '>' + data[i].treatment_name + '</option>';
                        }
                        $('#Treatment').append(tr);
                    }
                    loadExercise();

                }
            }
            else {
                console.log(data);
            }
        }
    });
}
$('#SelRegion').change(function () {
    if ($('#SelRegion').val() == '' || $('#SelRegion').val() == null && $('#SelRegion').val() == 0) {
        return false;
    }
    var where_condition = "";
    var selText = [];
    var i = 0;
    $("#SelRegion option:selected").each(function () {
        var $this = $(this);
        if ($this.length) {
            selText[i] = $this.text();
            i++;
        }
    });
    if ($("#SelRegion").val().length == 1) {
        where_condition = where_condition + "region ='" + selText[0] + "'";
    }
    else if ($("#SelRegion").val().length == 2) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "'";
    }
    else if ($("#SelRegion").val().length == 3) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "'";
    }
    else if ($("#SelRegion").val().length == 4) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "'";
    }
    else if ($("#SelRegion").val().length == 5) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "'";
    }
    else if ($("#SelRegion").val().length == 6) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "'";
    }
    else if ($("#SelRegion").val().length == 7) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "'";
    }
    else if ($("#SelRegion").val().length == 8) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "'";
    }
    else if ($("#SelRegion").val().length == 9) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "' or region='" + selText[8] + "'";
    }


    var Exercise = {
        Dml_Indicator: "OS",
        //region: $('#SelRegion option:selected').text()
        condition: where_condition
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Type_Exercise',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Exercise),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var tr = '<option value=0>--Select--</option>';
                    $('#SelPrePostOP').empty();
                    $('#TypeExercise').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<option value=' + (i + 1) + '>' + data[i].op_type + '</option>';
                        }
                        $('#SelPrePostOP').append(tr);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

});
$('#SelPrePostOP').change(function () {
    var where_condition = "";
    var selText = [];
    var i = 0;
    $("#SelRegion option:selected").each(function () {
        var $this = $(this);
        if ($this.length) {
            selText[i] = $this.text();
            i++;
        }
    });
    //if ($("#SelRegion").val().length == 1) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '"';
    //}
    //else if ($("#SelRegion").val().length == 2) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '"';
    //}
    //else if ($("#SelRegion").val().length == 3) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '"';
    //}
    //else if ($("#SelRegion").val().length == 4) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '"';
    //}
    //else if ($("#SelRegion").val().length == 5) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '"';
    //}
    //else if ($("#SelRegion").val().length == 6) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '"';
    //}
    //else if ($("#SelRegion").val().length == 7) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '"';
    //}
    //else if ($("#SelRegion").val().length == 8) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '" or region="' + selText[7] + '"';
    //}
    //else if ($("#SelRegion").val().length == 9) {
    //    where_condition = where_condition + 'region ="' + selText[0] + '" or region = "' + selText[1] + '" or region ="' + selText[2] + '" or region="' + selText[3] + '" or region="' + selText[4] + '" or region="' + selText[5] + '" or region="' + selText[6] + '" or region="' + selText[7] + '" or region="' + selText[8] + '"';
    //}

    if ($("#SelRegion").val().length == 1) {
        where_condition = where_condition + "region ='" + selText[0] + "'";
    }
    else if ($("#SelRegion").val().length == 2) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "'";
    }
    else if ($("#SelRegion").val().length == 3) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "'";
    }
    else if ($("#SelRegion").val().length == 4) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "'";
    }
    else if ($("#SelRegion").val().length == 5) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "'";
    }
    else if ($("#SelRegion").val().length == 6) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "'";
    }
    else if ($("#SelRegion").val().length == 7) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "'";
    }
    else if ($("#SelRegion").val().length == 8) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "'";
    }
    else if ($("#SelRegion").val().length == 9) {
        where_condition = where_condition + "region ='" + selText[0] + "' or region = '" + selText[1] + "' or region ='" + selText[2] + "' or region='" + selText[3] + "' or region='" + selText[4] + "' or region='" + selText[5] + "' or region='" + selText[6] + "' or region='" + selText[7] + "' or region='" + selText[8] + "'";
    }

    if ($('#SelRegion').val() == '' || $('#SelRegion').val() == null && $('#SelRegion').val() == 0) {
        return false;
    }
    if ($('#SelPrePostOP').val() == '' || $('#SelPrePostOP').val() == null && $('#SelPrePostOP').val() == 0) {
        return false;
    }
    var excercise_intensity_high = '3';
    if ($('#HightIntensity').val() == '2') {
        excercise_intensity_high = '2';
    }

    where_condition = where_condition + " ) and op_type='" + $('#SelPrePostOP option:selected').text() + "'";

    var Exercise = {
        excercise_intensity_high: excercise_intensity_high,
        Dml_Indicator: "ES",
        //region: region,
        condition: where_condition,
        op_type: $('#SelPrePostOP option:selected').text()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Type_Exercise',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Exercise),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var regionRow = '';
                    var tr = '<option value=0>--Select--</option>', ExerciseValue = '';
                    $('#TypeExercise').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {

                            tr = tr + '<option value=' + data[i].type_of_excercise + '>' + data[i].excercise_description + '</option>';


                        }
                        $('#TypeExercise').append(tr);

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


function Instruction(excercise) {
}

$('#TypeExercise').change(function () {
    $('#TypeExerciseBtn').val($('#TypeExercise').val());
    var Exercise = {
        type_of_excercise: $('#TypeExercise').val(),
        Dml_Indicator: "WS"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Type_Exercise',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Exercise),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    //var data = JSON.parse(data);
                    //$('#txtEDInstruction').html(data[0].excercise_instruction);
                    //$('#txtExBenefits').html(data[0].excercise_benefits);
                    var ins = data[0].exercise_instruction;
                    console.log(data[0].duration);
                    if (data[0].excercise_instruction == "NULL") {
                        $('#txtEDInstruction').html("-");
                    }
                    else {
                        $('#txtEDInstruction').html(data[0].excercise_instruction);
                    }
                    $('#txtExBenefits').html(data[0].excercise_benefits);
                    $('#txtDailyDuration').val(data[0].duration);
                    $('#txtSittings').val(data[0].sittings);
                }
            }
            else {
                console.log(data);
            }
        }
    });
});
//load algorithm
function loadAlgorithm() {
    var VisitreportId = {
        visit_report_id: $('#EditVisitReportID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Algorithm_select',
        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 {
                    var algorithm_no = '';
                    var suggestion = '', Prescription = '', Diagnostics = '', Exercise = '', Diet = '';
                    for (var i = 0; i < data.length; i++) {
                        var algorithm_no = data[i].algorithm_no;
                        //suggestion
                        if (algorithm_no == 1 || algorithm_no == 2 || algorithm_no == 5 || algorithm_no == 12 || algorithm_no == 15 || algorithm_no == 16 || algorithm_no == 21) {
                            suggestion = suggestion + '<li><p><strong>' + data[i].algorithm_head + '</strong>: ' + data[i].algorithm_details + '</p></li>';
                        }
                        //Prescription
                        if (algorithm_no == 3 || algorithm_no == 4 || algorithm_no == 24) {
                            Prescription = Prescription + '<li><p><strong>' + data[i].algorithm_head + '</strong>: ' + data[i].algorithm_details + '</p></li>';
                        }
                        //Diagnostics
                        if (algorithm_no == 6 || algorithm_no == 7 || algorithm_no == 8 || algorithm_no == 9 || algorithm_no == 16 || algorithm_no == 18 || algorithm_no == 22 || algorithm_no == 27) {
                            Diagnostics = Diagnostics + '<li><p><strong>' + data[i].algorithm_head + '</strong>: ' + data[i].algorithm_details + '</p></li>'
                        }
                        //Exercise
                        if (algorithm_no == 3 || algorithm_no == 20 || algorithm_no == 26) {
                            Exercise = Exercise + '<li><p><strong>' + data[i].algorithm_head + '</strong>: ' + data[i].algorithm_details + '</p></li>';
                        }
                        //Diet
                        if (algorithm_no == 17 || algorithm_no == 19) {
                            Diet = Diet + '<li><p><strong>' + data[i].algorithm_head + '</strong>: ' + data[i].algorithm_details + '</p></li>';
                        }
                    }
                    $('#ASuggestion').append(suggestion);
                    $('#APrescription').append(Prescription);
                    $('#ADiagonastics').append(Diagnostics);
                    $('#AExercise').append(Exercise);
                    $('#ADiet').append(Diet);
                }
            }
            else {
                console.log(data);
            }
        }
    });
    // loadPatientSummary();
}

$('#tab_Next').click(function () {
    if ($("#csstep14").hasClass("active")) {
        $('#BtnLabSubmit').click();
    }
});

function PatientSummary() {
    if ($('#ASuggestion').find('li').length !== 0) {
        $('#SummarySuggestions-section').removeClass('in');
        $('#SummarySuggestions-section').addClass('in');
    }
    else {
        $('#SummarySuggestions-section').removeClass('in');
    }
    if ($('#APrescription').find('li').length !== 0) {
        $('#SummaryPrescription-section').removeClass('in');
        $('#SummaryPrescription-section').addClass('in');
    }
    else {
        $('#SummaryPrescription-section').removeClass('in');
    }
    if ($('#ADiagonastics').find('li').length !== 0) {
        $('#SummaryDiagnostics-section').removeClass('in');
        $('#SummaryDiagnostics-section').addClass('in');
    }
    else {
        $('#SummaryDiagnostics-section').removeClass('in');
    }
    if ($('#AExercise').find('li').length !== 0) {
        $('#SummaryExercise-section').removeClass('in');
        $('#SummaryExercise-section').addClass('in');
    }
    else {
        $('#SummaryExercise-section').removeClass('in');
    }
    if ($('#ADiet').find('li').length !== 0) {
        $('#SummaryDiet-section').removeClass('in');
        $('#SummaryDiet-section').addClass('in');
    }
    else {
        $('#SummaryDiet-section').removeClass('in');
    }
    loadPatientSummary();
    load_patient_summary_page();
}

function load_patient_summary_page() {
    debugger;
    var MedicinePrescriptiondate = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Summary_details',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(MedicinePrescriptiondate),
        success: function (data) {

            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('.tbl_patient_summary_details').html();
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    //if (data.Table18.length > 0) { // Added by Antony

                    //    $('#Hpatientid').val(data.Table18[0].patientid)
                    //    $('#Hvisit_reportid').val(data.Table18[0].visit_reportid)
                    //}  //

                    if (data.length > 2) {
                        console.log(data);
                        var div = "", divtr = '';
                        var j = 1;
                        if (data.Table.length > 0 && data.Table[0].observation_primary != null) {
                            div = div + '<div class="col-md-12"><h5>OBSERVATION</h5></div>';
                        }
                        else if (data.Table17.length > 0 && data.Table17.length > 0) {
                            div = div + '<div class="col-md-12"><h5>OBSERVATION</h5></div>';
                        }
                        else if (data.Table1.length > 0 && data.Table1[0].patient_bp_record_id != null) {
                            div = div + '<div class="col-md-12"><h5>OBSERVATION</h5></div>';
                        }
                        else {
                        }

                        if (data.Table.length > 0) {
                            if (data.Table[0].current_complaints != null && data.Table[0].current_complaints != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Complaints</label> : <span>' + data.Table[0].current_complaints + '</span></div>';
                            }
                            if (data.Table[0].note != null && data.Table[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Test Requested </label> : <span>' + data.Table[0].note + '</span></div>';
                            }
                            if (data.Table[0].pulse_rate != null && data.Table[0].pulse_rate != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Pulse Rate</label> : <span>' + data.Table[0].pulse_rate + ' / min</span></div>';
                            }
                            if (data.Table[0].spo2 != null && data.Table[0].spo2 != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">SpO2</label> : <span>' + data.Table[0].spo2 + ' %</span></div>';
                            }
                            if (data.Table[0].temperature != null && data.Table[0].temperature != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Temperature</label> : <span>' + data.Table[0].temperature + ' F</span></div>';
                            }
                            if (data.Table[0].hypoglycemia_episodes != null && data.Table[0].hypoglycemia_episodes != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Hypoglycemic Episodes</label> : <span>' + data.Table[0].hypoglycemia_episodes + '</span></div>';
                            }
                            if (data.Table[0].vas != null && data.Table[0].vas != '') {
                                if (data.Table28[0].vas == '0') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Visual Analogue Scale(VAS)</h5></label> : <span> No Pain</span></div>';
                                }
                                else if (data.Table28[0].vas == '1' || data.Table28[0].vas == '2' || data.Table28[0].vas == '3') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Visual Analogue Scale(VAS)</h5></label> : <span> Mild</span></div>';
                                }
                                else if (data.Table28[0].vas == '4' || data.Table28[0].vas == '5' || data.Table28[0].vas == '6') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Visual Analogue Scale(VAS)</h5></label> : <span> Moderate </span></div>';
                                }
                                else if (data.Table28[0].vas == '7' || data.Table28[0].vas == '8' || data.Table28[0].vas == '9') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Visual Analogue Scale(VAS)</h5></label> : <span> Severe</span></div>';
                                }
                                if (data.Table28[0].vas == '10') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Visual Analogue Scale(VAS)</h5></label> : <span> Worst Pain </span></div>';
                                }

                                if (data.Table28[0].vasduration != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Vas Duration</h5></label> : <span>' + data.Table28[0].vasduration + '</span></div>';
                                }

                                if (data.Table28[0].vaslocation != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Vas Location</h5></label> : <span> ' + data.Table28[0].vaslocation + '</span></div>';
                                }

                                if (data.Table28[0].followup != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Follow Up/Admission Plan</h5></label> : <span> ' + data.Table28[0].followup + '</span></div>';
                                }

                                if (data.Table28[0].vaspaincharacter != null) {
                                    var paincharacter = data.Table28[0].vaspaincharacter;

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

                                        var paincharactersplit = paincharacter.split(',');
                                        var paincharacter_disp = [];
                                        for (i = 0; i < paincharactersplit.length; i++) {

                                            if (paincharactersplit[i] == 0) {
                                                var paincharacter_view = "Dull"
                                            }
                                            else if (paincharactersplit[i] == 1) {
                                                var paincharacter_view = "Aching"
                                            }
                                            else if (paincharactersplit[i] == 2) {
                                                var paincharacter_view = "Sharp"
                                            }
                                            else if (paincharactersplit[i] == 3) {
                                                var paincharacter_view = "Stabbing"
                                            }
                                            else if (paincharactersplit[i] == 4) {
                                                var paincharacter_view = "Shooting"
                                            }
                                            else if (paincharactersplit[i] == 5) {
                                                var paincharacter_view = "Burning"
                                            }
                                            else if (paincharactersplit[i] == 6) {
                                                var paincharacter_view = "Referred/Radiant Plain"
                                            }
                                            paincharacter_disp.push(paincharacter_view)
                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Pain Character</h5></label> : <span> ' + paincharacter_disp + ' </span></div>';
                                }
                                if (data.Table28[0].vasfullrisk != null) {
                                    var frsfa = data.Table28[0].vasfullrisk;
                                    var frsfa_disp = [];
                                    if (frsfa != null && frsfa != "") {

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

                                        for (i = 0; i < frsfasplit.length; i++) {
                                            if (frsfasplit[i] == 0) {
                                                var frsfa_view = "No risk"
                                            }
                                            else if (frsfasplit[i] == 1) {
                                                var frsfa_view = "Age More than 65 years"
                                            }
                                            else if (frsfasplit[i] == 2) {
                                                var frsfa_view = "History of fall in last 3 Months"
                                            }
                                            else if (frsfasplit[i] == 3) {
                                                var frsfa_view = "Walks with assistance"
                                            }
                                            else if (frsfasplit[i] == 4) {
                                                var frsfa_view = "Any Neurological Problem"
                                            }

                                            frsfa_disp.push(frsfa_view)


                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5>Full Risk Screening for Adults</h5></label> : <span> ' + frsfa_disp + ' </span></div>';
                                }

                            }
                            if (data.Table[0].glycemic_variability != null && data.Table[0].glycemic_variability != '') {
                                var glycemic_variability = data.Table[0].glycemic_variability;
                                if (glycemic_variability == 1) {
                                    glycemic_variability = "Present";
                                }
                                else {
                                    glycemic_variability = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Glycemic Variability</label> : <span>' + glycemic_variability + '</span></div>';
                            }
                            if (data.Table[0].cvs != null && data.Table[0].cvs != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">CVS</label> : <span>' + data.Table[0].cvs + '</span></div>';
                            }
                            if (data.Table[0].ABS != null && data.Table[0].ABS != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">ABD</label> : <span>' + data.Table[0].ABS + '</span></div>';
                            }
                            if (data.Table[0].rs != null && data.Table[0].rs != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">RS</label> : <span>' + data.Table[0].rs + '</span></div>';
                            }
                            if (data.Table[0].CNS != null && data.Table[0].CNS != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">CNS</label> : <span>' + data.Table[0].CNS + '</span></div>';
                            }

                            if (data.Table[0].heart_sound != null && data.Table[0].heart_sound != '') {
                                var heart_sound = data.Table[0].heart_sound;
                                if (heart_sound == 1) {
                                    heart_sound = "True";
                                }
                                else {
                                    heart_sound = "False";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Abnormal Heart Sound</label> : <span>' + heart_sound + '</span></div>';
                            }

                            if (data.Table[0].murmurs != null && data.Table[0].murmurs != '') {
                                var murmurs = data.Table[0].murmurs;
                                if (murmurs == 1) {
                                    murmurs = "Present";
                                }
                                else {
                                    murmurs = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Murmurs</label> : <span>' + murmurs + '</span></div>';
                            }

                            if (data.Table[0].reduce_air_entry != null && data.Table[0].reduce_air_entry != '') {
                                var reduce_air_entry = data.Table[0].reduce_air_entry;
                                if (reduce_air_entry == 1) {
                                    reduce_air_entry = "Present";
                                }
                                else {
                                    reduce_air_entry = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Reduced Air Entry</label> : <span>' + reduce_air_entry + '</span></div>';
                            }

                            if (data.Table[0].crackles != null && data.Table[0].crackles != '') {
                                var crackles = data.Table[0].crackles;
                                if (crackles == 1) {
                                    crackles = "Present";
                                }
                                else {
                                    crackles = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Crackles</label> : <span>' + crackles + '</span></div>';
                            }
                            if (data.Table[0].bowel_sounds != null && data.Table[0].bowel_sounds != '') {
                                var bowel_sounds = data.Table[0].bowel_sounds;
                                if (bowel_sounds == 1) {
                                    bowel_sounds = "Present";
                                }
                                else {
                                    bowel_sounds = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Abnormal Bowel Sounds</label> : <span>' + bowel_sounds + '</span></div>';
                            }
                            if (data.Table[0].organomeglay != null && data.Table[0].organomeglay != '') {
                                var organomeglay = data.Table[0].organomeglay;
                                if (organomeglay == 1) {
                                    organomeglay = "Present";
                                }
                                else {
                                    organomeglay = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Organomeglay</label> : <span>' + organomeglay + '</span></div>';
                            }
                            if (data.Table[0].tremors_weakness != null && data.Table[0].tremors_weakness != '') {
                                var tremors_weakness = data.Table[0].tremors_weakness;
                                if (tremors_weakness == 1) {
                                    tremors_weakness = "Present";
                                }
                                else {
                                    tremors_weakness = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Tremors Weakness</label> : <span>' + tremors_weakness + '</span></div>';
                            }
                            if (data.Table[0].cognitive_imparement != null && data.Table[0].cognitive_imparement != '') {
                                var cognitive_imparement = data.Table[0].cognitive_imparement;
                                if (cognitive_imparement == 1) {
                                    cognitive_imparement = "Present";
                                }
                                else {
                                    cognitive_imparement = "Absent";
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Cognitive Imparement</label> : <span>' + cognitive_imparement + '</span></div>';
                            }
                        }
                        if (data.Table17.length > 0) {
                            if (data.Table17[0].weight != null && data.Table17[0].weight != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Weight</label> : <span>' + data.Table17[0].weight + ' Kg </span></div>';
                            }
                            if (data.Table17[0].patient_height != null && data.Table17[0].patient_height != '') {

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

                                var hieghtout = (data.Table17[0].patient_height * 30.48) + (data.Table17[0].patient_height_metric * 2.54);
                                hieghtout = hieghtout.toFixed(1);

                                var hieght = hieghtout;

                                div = div + '<div class="col-md-12"><label class="control-label">Height</label> : <span>' + hieght + ' cm </span></div>';
                            }
                        }
                        if (data.Table1.length > 0) {
                            if (data.Table1[0].patient_bp_max != null && data.Table1[0].patient_bp_max != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Sys/Dia</label> : <span>' + data.Table1[0].patient_bp_max + '</span>/<span>' + data.Table1[0].patient_bp_min + '</span></div>';
                            }
                        }
                        //dental
                        if (data.Table28.length > 0 && (data.Table28[0].dental_procedure_done != null || data.Table28[0].dental_procedure_remaining != null || data.Table28[0].dental_type != null || data.Table28[0].dental_hard_tissue != null || data.Table28[0].dental_soft_tissue != null)) {
                            div = div + '<div class="col-md-12"><h5><b>Dental</b></h5></div>';
                        }
                        if (data.Table28.length > 0) {
                            if (data.Table28[0].dental_type != null && data.Table28[0].dental_type != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Type of Dental Appointment</label> : <span>' + (data.Table28[0].dental_type == 1 ? "Cosmetic" : data.Table28[0].dental_type == 2 ? "Dental" : "Surgical") + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_done != null && data.Table28[0].dental_procedure_done != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Done</label> : <span>' + data.Table28[0].dental_procedure_done + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_remaining != null && data.Table28[0].dental_procedure_remaining != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Remaining</label> : <span>' + data.Table28[0].dental_procedure_remaining + '</span></div>';
                            }
                            if (data.Table28[0].dental_hard_tissue != null && data.Table28[0].dental_hard_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Hard Tissue</label> : <span>' + data.Table28[0].dental_hard_tissue + '</span></div>';
                            }
                            if (data.Table28[0].dental_soft_tissue != null && data.Table28[0].dental_soft_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Soft Tissue</label> : <span>' + data.Table28[0].dental_soft_tissue + '</span></div>';
                            }
                        }

                        if (data.Table2.length > 0 && data.Table2[0].glycemic_parameters_basic_id != null) {
                            div = div + '<div class="col-md-12"><h5>Glycemic</h5></div>';
                        }
                        else if (data.Table3.length > 0 && data.Table3[0].patient_hbac_record_id != null) {
                            div = div + '<div class="col-md-12"><h5>Glycemic</h5></div>';
                        }
                        else if (data.Table4.length > 0 && data.Table4[0].patient_blood_sugar_record_id != null) {
                            div = div + '<div class="col-md-12"><h5>Glycemic</h5></div>';
                        }
                        else {

                        }
                        if (data.Table2.length > 0) {
                            if (data.Table2[0].fasting_insulin != null && data.Table2[0].fasting_insulin != '') {
                                var fasting_inslin_unit = 'mlU/L';
                                if (data.Table2[0].fasting_inslin_unit == 2) {
                                    fasting_inslin_unit = 'pmol/L'
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Fasting Insulin</label> : <span>' + data.Table2[0].fasting_insulin + ' ' + fasting_inslin_unit + '</span></div>';
                            }
                            if (data.Table2[0].hemoglobin != null && data.Table2[0].hemoglobin != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">HB</label> : <span>' + data.Table2[0].hemoglobin + ' gms</span></div>';
                            }
                            if (data.Table2[0].note != null && data.Table2[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Glycemic Notes</label> : <span>' + data.Table2[0].note + '</span></div>';
                            }
                            if (data.Table2[0].WBC != null && data.Table2[0].WBC != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">WBC</label> : <span>' + data.Table2[0].WBC + ' cells per cubic millimeter</span></div>';
                            }
                            if (data.Table2[0].platelet != null && data.Table2[0].platelet != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Platelet</label> : <span>' + data.Table2[0].platelet + ' per microliter</span></div>';
                            }
                            if (data.Table2[0].se_ketones != null && data.Table2[0].se_ketones != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Se_ketones</label> : <span>' + data.Table2[0].se_ketones + ' mmol/L</span></div>';
                            }
                        }

                        if (data.Table3.length > 0) {
                            if (data.Table3[0].patient_hbac_record_value != null && data.Table3[0].patient_hbac_record_value != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">HBA1C</label> : <span>' + data.Table3[0].patient_hbac_record_value + ' %</span></div>';
                            }
                        }

                        if (data.Table4.length > 0) {
                            for (var i = 0; i < data.Table4.length; i++) {
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 1) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">Fasting blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 2) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">Postprandial blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 3) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">Random blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 4) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">Before Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 5) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">After Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 6) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">Before Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 7) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">After Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 8) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label">3 Am BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                            }

                        }
                        //want to write code
                        if (data.Table5.length > 0) {
                        }

                        if (data.Table6.length > 0) {
                            if (data.Table6[0].renal_function_test_id != null) {
                                div = div + '<div class="col-md-12"><h5>RENAL</h5></div>';
                            }
                        }
                        else {
                            if (data.Table7.length > 0) {
                                if ((data.Table7[0].ACR != null && data.Table7[0].ACR != '') || (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '')) {
                                    div = div + '<div class="col-md-12"><h5>RENAL</h5></div>';
                                }
                            }
                        }

                        if (data.Table6.length > 0) {
                            if (data.Table6[0].Urea != null && data.Table6[0].Urea != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].urea_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Urea</label> : <span>' + data.Table6[0].Urea + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].creatinine != null && data.Table6[0].creatinine != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].Creatinine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Creatinine</label> : <span>' + data.Table6[0].creatinine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].egfr_value != null && data.Table6[0].egfr_value != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">EGFR ( Calculated )</label> : <span>' + data.Table6[0].egfr_value + ' ml/min/1.73m2</span></div>';
                            }
                            if (data.Table6[0].Sodium != null && data.Table6[0].Sodium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].sodium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Sodium</label> : <span>' + data.Table6[0].Sodium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Potassium != null && data.Table6[0].Potassium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].potassium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Potassium</label> : <span>' + data.Table6[0].Potassium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Chlorine != null && data.Table6[0].Chlorine != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].chlorine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Chlorine</label> : <span>' + data.Table6[0].Chlorine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].BiCarbonate != null && data.Table6[0].BiCarbonate != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Bicarbonate_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">BiCarbonate</label> : <span>' + data.Table6[0].BiCarbonate + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_calcium != null && data.Table6[0].serium_calcium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Calcium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Calcium</label> : <span>' + data.Table6[0].serium_calcium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_phosphorous != null && data.Table6[0].serium_phosphorous != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Phosphorus_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Phosphorous</label> : <span>' + data.Table6[0].serium_phosphorous + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_magnesium != null && data.Table6[0].serium_magnesium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Magnesium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Magnesium</label> : <span>' + data.Table6[0].serium_magnesium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].note != null && data.Table6[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Renal Notes</label> : <span>' + data.Table6[0].note + ' </span></div>';
                            }
                            if (data.Table6[0].ASD != null && data.Table6[0].ASD != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">ASD</label> : <span>' + data.Table6[0].ASD + ' </span></div>';
                            }
                            if (data.Table6[0].VSD != null && data.Table6[0].VSD != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">VSD</label> : <span>' + data.Table6[0].VSD + ' </span></div>';
                            }
                            if (data.Table6[0].C_value != null && data.Table6[0].C_value != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Valve Notes</label> : <span>' + data.Table6[0].C_value + ' </span></div>';
                            }
                            if (data.Table6[0].fraction != null && data.Table6[0].fraction != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Fraction</label> : <span>' + data.Table6[0].fraction + ' </span></div>';
                            }
                            if (data.Table6[0].mitral_value != null && data.Table6[0].mitral_value != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Mitral Value</label> : <span>' + data.Table6[0].mitral_value + ' </span></div>';
                            }
                            if (data.Table6[0].lotic_value != null && data.Table6[0].lotic_value != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Aortic Valve</label> : <span>' + data.Table6[0].lotic_value + ' </span></div>';
                            }
                            if (data.Table6[0].tricuspid != null && data.Table6[0].tricuspid != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Tricuspid</label> : <span>' + data.Table6[0].tricuspid + ' </span></div>';
                            }
                            if (data.Table6[0].pulmonary != null && data.Table6[0].pulmonary != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Pulmonary</label> : <span>' + data.Table6[0].pulmonary + ' </span></div>';
                            }
                        }

                        if (data.Table7.length > 0) {
                            if (data.Table7[0].ACR != null && data.Table7[0].ACR != '') {
                                var ACR = '';
                                if (data.Table7[0].ACR == 1) {
                                    ACR = '< 30 mg/dL - Normal';
                                }
                                if (data.Table7[0].ACR == 2) {
                                    ACR = '30 to 300 mg/dL - Microalbuminuria';
                                }
                                if (data.Table7[0].ACR == 3) {
                                    ACR = '  > 300 mg/dL - Proteinuria';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">ACR</label> : <span>' + ACR + '</span></div>';
                            }
                            if (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '') {
                                var nephropathy = '';
                                if (data.Table7[0].nephropathy == 1) {
                                    nephropathy = 'Yes';
                                }
                                if (data.Table7[0].nephropathy == 2) {
                                    nephropathy = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Nephropathy</label> : <span>' + nephropathy + '</span></div>';
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].cholestrol_id != null) {
                                div = div + '<div class="col-md-12"><h5>CHOLESTEROL</h5></div>';
                            }
                        }
                        else {
                            if (data.Table9.length > 0) {
                                if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                    div = div + '<div class="col-md-12"><h5>CHOLESTEROL</h5></div>';
                                }
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].Total_Cholestrol != null && data.Table8[0].Total_Cholestrol != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Total_cholestrol_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Total Cholesterol</label> : <span>' + data.Table8[0].Total_Cholestrol + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].LDL != null && data.Table8[0].LDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].LDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">LDL</label> : <span>' + data.Table8[0].LDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].HDL != null && data.Table8[0].HDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].HDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">HDL</label> : <span>' + data.Table8[0].HDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].VLDL != null && data.Table8[0].VLDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].VLDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">VLDL</label> : <span>' + data.Table8[0].VLDL + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].Triglycerides != null && data.Table8[0].Triglycerides != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Triglycerides_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Triglycerides</label> : <span>' + data.Table8[0].Triglycerides + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].T_cholestrol_Hdl_ratio != null && data.Table8[0].T_cholestrol_Hdl_ratio != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Total Cholesterol : HDL Ratio</label> : <span>' + data.Table8[0].T_cholestrol_Hdl_ratio + ' </span></div>';
                            }
                            if (data.Table8[0].note != null && data.Table8[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Cholestrol Notes</label> : <span>' + data.Table8[0].note + ' </span></div>';
                            }
                        }
                        if (data.Table9.length > 0) {
                            if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                var unit = '';
                                if (data.Table9[0].dyslipedemia == 1) {
                                    unit = 'yes';
                                }
                                else {
                                    unit = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Dyslipidemia</label> : <span>' + unit + ' </span></div>';
                            }
                        }
                        debugger;
                        if (data.Table10.length > 0 && data.Table10[0].optha_id != null) {
                            div = div + '<div class="col-md-12"><h5>OPTHAL</h5></div>';
                        }
                        else if (data.Table11.length > 0 && data.Table11[0].patient_level_flag_id != null && (data.Table11[0].pdr != null && data.Table11[0].npdr != null && data.Table11[0].viterous_hemorage != null && data.Table11[0].retinal_detachment != null && data.Table11[0].retinopathy != null)) {
                            div = div + '<div class="col-md-12"><h5>OPTHAL</h5></div>';
                        }
                        if (data.Table10.length > 0) {
                            if (data.Table10[0].last_observation_date != null && data.Table10[0].last_observation_date != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Last Observation Date</label> : <span>' + data.Table10[0].last_observation_date + ' </span></div>';
                            }
                            if (data.Table10[0].next_suggested_appointment != null && data.Table10[0].next_suggested_appointment != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Next Suggested Opthal Appointment</label> : <span>' + data.Table10[0].next_suggested_appointment + ' </span></div>';
                            }
                            if (data.Table10[0].note != null && data.Table10[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Opthal Notes</label> : <span>' + data.Table10[0].note + ' </span></div>';
                            }
                        }

                        if (data.Table11.length > 0) {
                            if (data.Table11[0].pdr != null && data.Table11[0].pdr != '') {
                                var val = '';
                                if (data.Table11[0].pdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].pdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].pdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].pdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">PDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].npdr != null && data.Table11[0].npdr != '') {
                                var val = '';
                                if (data.Table11[0].npdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].npdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].npdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].npdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">NPDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].viterous_hemorage != null && data.Table11[0].viterous_hemorage != '') {
                                var val = '';
                                if (data.Table11[0].viterous_hemorage == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].viterous_hemorage == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Vitreous Hemorrhage</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinal_detachment != null && data.Table11[0].retinal_detachment != '') {
                                var val = '';
                                if (data.Table11[0].retinal_detachment == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinal_detachment == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Retinal Detachment</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinopathy != null && data.Table11[0].retinopathy != '') {
                                var val = '';
                                if (data.Table11[0].retinopathy == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinopathy == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Retinopathy</label> : <span>' + val + ' </span></div>';
                            }
                        }
                        if (data.Table19.length > 0 && data.Table19[0].patient_level_cardiac_id != null && (data.Table19[0].L_LAD != null || data.Table19[0].L_LAD_type != null || data.Table19[0].L_LCX != null ||
                            data.Table19[0].L_LCX_type != null || data.Table19[0].L_RCA != null || data.Table19[0].L_RCA_type != null || data.Table19[0].R_LAD != null || data.Table19[0].R_LAD_type != null
                            || data.Table19[0].R_LCX != null || data.Table19[0].R_LCX_type != null || data.Table19[0].R_RCA != null || data.Table19[0].R_RCA_type != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else if (data.Table12.length > 0 && data.Table12[0].cardiac_profile_id != null && (data.Table12[0].ECG != null || data.Table12[0].ECHO != null
                            || (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != 0) || (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != 0) || data.Table12[0].TMT_test != null || data.Table12[0].note != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else { }
                        if (data.Table19.length > 0) {
                            if (data.Table19[0].L_LAD != null && data.Table19[0].L_LAD != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">LCA</label> : <span>' + data.Table19[0].L_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LAD_type != null && data.Table19[0].L_LAD_type != '' && data.Table19[0].L_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LAD_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">LCA Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].L_LCX != null && data.Table19[0].L_LCX != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">LCX</label> : <span>' + data.Table19[0].L_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LCX_type != null && data.Table19[0].L_LCX_type != '' && data.Table19[0].L_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LCX_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">LCX Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].L_RCA != null && data.Table19[0].L_RCA != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">LAD</label> : <span>' + data.Table19[0].L_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].L_RCA_type != null && data.Table19[0].L_RCA_type != '' && data.Table19[0].L_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_RCA_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-12"><label class="control-label">LAD Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].R_LAD != null && data.Table19[0].R_LAD != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">RCA</label> : <span>' + data.Table19[0].R_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LAD_type != null && data.Table19[0].R_LAD_type != '' && data.Table19[0].R_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LAD_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-12"><label class="control-label">RCA Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].R_LCX != null && data.Table19[0].R_LCX != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">R-PLB</label> : <span>' + data.Table19[0].R_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LCX_type != null && data.Table19[0].R_LCX_type != '' && data.Table19[0].R_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LCX_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-12"><label class="control-label">R-PLB Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].R_RCA != null && data.Table19[0].R_RCA != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">R-PDA</label> : <span>' + data.Table19[0].R_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].R_RCA_type != null && data.Table19[0].R_RCA_type != '' && data.Table19[0].R_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_RCA_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">R-PDA Type</label> : <span>' + type + ' </span></div>';
                            }
                        }

                        if (data.Table12.length > 0) {
                            if (data.Table12[0].ECG != null && data.Table12[0].ECG != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">ECG</label> : <span>' + data.Table12[0].ECG + ' </span></div>';
                            }
                            if (data.Table12[0].ECHO != null && data.Table12[0].ECHO != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">ECHO</label> : <span>' + data.Table12[0].ECHO + ' </span></div>';
                            }
                            if (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != '') {
                                if (data.Table12[0].ecg_abnormal == 1) {
                                    div = div + '<div class="col-md-12"><label class="control-label">ECG Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != '') {
                                if (data.Table12[0].echo_abnormal == 1) {
                                    div = div + '<div class="col-md-12"><label class="control-label">ECHO Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].TMT_test != null && data.Table12[0].TMT_test != '') {
                                if (data.Table12[0].TMT_test == 1) {
                                    div = div + '<div class="col-md-12"><label class="control-label">TMT</label> : <span>Positive</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-12"><label class="control-label">TMT</label> : <span>Negative</span></div>';
                                }
                            }
                            if (data.Table12[0].note != null && data.Table12[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Cardiac Notes</label> : <span>' + data.Table12[0].note + '</span></div>';
                            }
                        }

                        if (data.Table13.length > 0 && (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '')) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else if (data.Table14.length > 0 && ((data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') || (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') || (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') || (data.Table14[0].note != null && data.Table14[0].note != ''))) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else {

                        }
                        if (data.Table13.length > 0) {
                            if (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '') {
                                if (data.Table13[0].autonomic_neuropathy == 1) {
                                    div = div + '<div class="col-md-12"><label class="control-label">Autonomic Neuropathy</label> : <span>Yes</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-12"><label class="control-label">Autonomic Neuropathy</label> : <span>No</span></div>';
                                }
                            }
                        }
                        if (data.Table14.length > 0) {
                            if (data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') {
                                var val = '';
                                if (data.Table14[0].peripharal_neuhropathy == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Peripheral Neuhropathy</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') {
                                var val = '';
                                if (data.Table14[0].AB_index == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].AB_index == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].AB_index == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].AB_index == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">AB Index</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Doppler</label> : <span>' + data.Table14[0].doppler_note + ' </span></div>';
                            }
                            if (data.Table14[0].note != null && data.Table14[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Neuropthy Note</label> : <span>' + data.Table14[0].note + ' </span></div>';
                            }
                        }

                        if (data.Table15.length > 0) {
                            if (data.Table15[0].thyroid_id != null) {
                                div = div + '<div class="col-md-12"><h5>THYROID</h5></div>';
                            }
                        }

                        if (data.Table15.length > 0) {
                            if (data.Table15[0].Free_T3 != null && data.Table15[0].Free_T3 != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Free T3</label> : <span>' + data.Table15[0].Free_T3 + ' Pg/dl </span></div>';
                            }
                            if (data.Table15[0].Free_T4 != null && data.Table15[0].Free_T4 != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Free T4</label> : <span>' + data.Table15[0].Free_T4 + ' ng/dl </span></div>';
                            }
                            if (data.Table15[0].TSH != null && data.Table15[0].TSH != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">TSH</label> : <span>' + data.Table15[0].TSH + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T3 != null && data.Table15[0].T3 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T3</label> : <span>' + data.Table15[0].T3 + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T4 != null && data.Table15[0].T4 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T4</label> : <span>' + data.Table15[0].T4 + ' mlU/m </span></div>';
                            }

                            if (data.Table15[0].note != null && data.Table15[0].note != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Thyroid Notes</label> : <span>' + data.Table15[0].note + '</span></div>';
                            }
                        }

                        if (data.Table16.length > 0) {
                            if (data.Table16[0].sheet_chest_xray_id != null) {
                                div = div + '<div class="col-md-12"><h5>ULTRASOUND / X-RAY</h5></div>';
                            }
                        }
                        if (data.Table16.length > 0) {
                            if (data.Table16[0].notes != null && data.Table16[0].notes != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Chest X-Ray Notes</label> : <span>' + data.Table16[0].notes + ' Pg/dl </span></div>';
                            }
                            if (data.Table16[0].USNotes != null && data.Table16[0].USNotes != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Ultrasound Notes</label> : <span>' + data.Table16[0].USNotes + ' ng/dl </span></div>';
                            }
                            if (data.Table16[0].fatty_lives != null && data.Table16[0].fatty_lives != '') {
                                var val = '';
                                if (data.Table16[0].fatty_lives == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].fatty_lives == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">Fatty Liver</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].GS_Calculus != null && data.Table16[0].GS_Calculus != '') {
                                var val = '';
                                if (data.Table16[0].GS_Calculus == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].GS_Calculus == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-12"><label class="control-label">GB Calculas</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].cts_notes != null && data.Table16[0].cts_notes != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">CT scan Notes</label> : <span>' + data.Table16[0].cts_notes + '</span></div>';
                            }
                        }
                        if (data.Table18.length > 0) {

                            $('#Hpatientid').val(data.Table18[0].patientid)
                            $('#Hvisit_reportid').val(data.Table18[0].visit_reportid)
                        }

                        if (data.Table26.length > 0) {
                            if (data.Table26[0].liver_function_test_id != null && (data.Table26[0].serum_bilirubin_total != null || data.Table26[0].serum_bilirubin_direct != null
                                || data.Table26[0].bilirubin_indirect != null || data.Table26[0].serum_protein_total != null || data.Table26[0].serum_protein_albumin != null || data.Table26[0].serumproteinglibulin != null
                                || data.Table26[0].SGOT != null || data.Table26[0].SGPT != null || data.Table26[0].serum_alkaline_phosphatase != null || data.Table26[0].gamma_glutamyl_transpeptidase != null || data.Table26[0].serum_magnesium != null)) {
                                div = div + '<div class="col-md-12"><h5>LIVER FUNCTION TEST</h5></div>';
                            }
                        }
                        if (data.Table26.length > 0) {
                            if (data.Table26[0].serum_bilirubin_total != null && data.Table26[0].serum_bilirubin_total != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Bilirubin Total</label> : <span>' + data.Table26[0].serum_bilirubin_total + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_bilirubin_direct != null && data.Table26[0].serum_bilirubin_direct != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Bilirubin Direct</label> : <span>' + data.Table26[0].serum_bilirubin_direct + ' mg/dl </span></div>';
                            }

                            if (data.Table26[0].bilirubin_indirect != null && data.Table26[0].bilirubin_indirect != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Bilirubin Indirect</label> : <span>' + data.Table26[0].bilirubin_indirect + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_total != null && data.Table26[0].serum_protein_total != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Protein -Total</label> : <span>' + data.Table26[0].serum_protein_total + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_albumin != null && data.Table26[0].serum_protein_albumin != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Protein - Albumin</label> : <span>' + data.Table26[0].serum_protein_albumin + ' g/dl</span></div>';
                            }
                            if (data.Table26[0].serumproteinglibulin != null && data.Table26[0].serumproteinglibulin != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Protein - Glibulin</label> : <span>' + data.Table26[0].serumproteinglibulin + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].SGOT != null && data.Table26[0].SGOT != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">SGOT (AST)</label> : <span>' + data.Table26[0].SGOT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].SGPT != null && data.Table26[0].SGPT != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">SGPT (AST)</label> : <span>' + data.Table26[0].SGPT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_alkaline_phosphatase != null && data.Table26[0].serum_alkaline_phosphatase != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].serum_alkaline_phosphatase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].gamma_glutamyl_transpeptidase != null && data.Table26[0].gamma_glutamyl_transpeptidase != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].gamma_glutamyl_transpeptidase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_magnesium != null && data.Table26[0].serum_magnesium != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Gamma Glutamyl Transpeptidase (GGT)</label> : <span>' + data.Table26[0].serum_magnesium + ' IU/l </span></div>';
                            }
                        }

                        if (data.Table27.length > 0) {
                            if (data.Table27[0].master_labtest_visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5>Master Lab Test</h5></div>';
                            }
                        }

                        if (data.Table27.length > 0) {
                            for (var i = 0; i < data.Table27.length; i++) {
                                if (data.Table27[i].parameter_name != null && data.Table27[i].parameter_name != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">' + data.Table27[i].parameter_name + '</label> : <span>' + data.Table27[i].parameter_value + '  ' + data.Table27[i].reference_value + ' ' + data.Table27[i].unit + '</span></div>';
                                }
                            }
                        }
                        if (data.Table29.length > 0) {
                            if (data.Table29[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5>CBC</h5></div>';
                            }
                        }

                        if (data.Table29.length > 0) {
                            for (var i = 0; i < data.Table29.length; i++) {
                                if (data.Table29[0].hemoglobin != null && data.Table29[0].hemoglobin != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">HEMOGLOBIN</label> : <span>' + data.Table29[0].hemoglobin + " " + ((data.Table29[0].hemoglobin_unit == null || data.Table29[0].hemoglobin_unit == "") ? "" : data.Table29[0].hemoglobin_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].platelet_count != null && data.Table29[0].platelet_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">PLATELET COUNT</label> : <span>' + data.Table29[0].platelet_count + " " + ((data.Table29[0].platelet_count_unit == null || data.Table29[0].platelet_count_unit == "") ? "" : data.Table29[0].platelet_count_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells != null && data.Table29[0].nucleated_red_blood_cells != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">NUCLEATED RED BLOOD CELLS</label> : <span>' + data.Table29[0].nucleated_red_blood_cells + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells_percent != null && data.Table29[0].nucleated_red_blood_cells_percent != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">NUCLEATED RED BLOOD CELLS %</label> : <span>' + data.Table29[0].nucleated_red_blood_cells_percent + ' </span></div>';
                                }
                                if (data.Table29[0].hematocrit != null && data.Table29[0].hematocrit != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">HEMATOCRIT(PCV)</label> : <span>' + data.Table29[0].hematocrit + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocyte_percent != null && data.Table29[0].lymphocyte_percent != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">LYMPHOCYTE PERCENTAGE</label> : <span>' + data.Table29[0].lymphocyte_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_leucocytes_count != null && data.Table29[0].total_leucocytes_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">TOTAL LEUCOCYTES COUNT</label> : <span>' + data.Table29[0].total_leucocytes_count + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_hemoglobin != null && data.Table29[0].mean_corpuscular_hemoglobin != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">MEAN CORPUSCULAR HEMOGLOBIN(MCH)</label> : <span>' + data.Table29[0].mean_corpuscular_hemoglobin + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corp_hemo_conc != null && data.Table29[0].mean_corp_hemo_conc != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">MEAN CORP.HEMO.CONC(MCHC)</label> : <span>' + data.Table29[0].mean_corp_hemo_conc + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_volume != null && data.Table29[0].mean_corpuscular_volume != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">MEAN CORPUSCULAR VOLUME(MCV)</label> : <span>' + data.Table29[0].mean_corpuscular_volume + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes != null && data.Table29[0].monocytes != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">MONOCYTES</label> : <span>' + data.Table29[0].monocytes + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils != null && data.Table29[0].neutrophils != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">NEUTROPHILS</label> : <span>' + data.Table29[0].neutrophils + ' </span></div>';
                                }
                                if (data.Table29[0].eosinophils_absolute_count != null && data.Table29[0].eosinophils_absolute_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">EOSINOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].eosinophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils_absolute_count != null && data.Table29[0].basophils_absolute_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">BASOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].basophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocytes_absolute_count != null && data.Table29[0].lymphocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">LYMPHOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].lymphocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes_absolute_count != null && data.Table29[0].monocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">MONOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].monocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils_absolute_count != null && data.Table29[0].neutrophils_absolute_count != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">NEUTROPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].neutrophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils != null && data.Table29[0].basophils != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">BASOPHILS</label> : <span>' + data.Table29[0].basophils + ' </span></div>';
                                }

                                if (data.Table29[0].eosinophils != null && data.Table29[0].eosinophils != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">EOSINOPHILS</label> : <span>' + data.Table29[0].eosinophils + ' </span></div>';
                                }

                                if (data.Table29[0].immature_granulocytes != null && data.Table29[0].immature_granulocytes != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">IMMATURE GRANULOCYTES(IG)</label> : <span>' + data.Table29[0].immature_granulocytes + ' </span></div>';
                                }
                                if (data.Table29[0].immature_granulocytes_percent != null && data.Table29[0].immature_granulocytes_percent != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">IMMATURE GRANULOCYTE PERCENTAGE(IG%)</label> : <span>' + data.Table29[0].immature_granulocytes_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_rbc != null && data.Table29[0].total_rbc != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">TOTAL RBC</label> : <span>' + data.Table29[0].total_rbc + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width != null && data.Table29[0].redcell_distribution_width != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">RED CELL DISTRIBUTION WIDTH (RDW-CV)</label> : <span>' + data.Table29[0].redcell_distribution_width + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width_sd != null && data.Table29[0].redcell_distribution_width_sd != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">RED CELL DISTRIBUTION WIDTH - SD(RDW-SD)</label> : <span>' + data.Table29[0].redcell_distribution_width_sd + ' </span></div>';
                                }
                            }
                        }

                        if (data.Table30.length > 0) {
                            if (data.Table30[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5>Urine Routine</h5></div>';
                            }
                        }
                        if (data.Table30.length > 0) {
                            for (var i = 0; i < data.Table30.length; i++) {
                                if (data.Table30[0].specific_gravity != null && data.Table30[0].specific_gravity != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">SPECIFIC GRAVITY</label> : <span>' + data.Table30[0].specific_gravity + " " + ((data.Table30[0].specific_gravity_unit == null || data.Table30[0].specific_gravity_unit == "") ? "" : data.Table30[0].specific_gravity_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_bilirubin != null && data.Table30[0].urinary_bilirubin != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINARY BILIRUBIN</label> : <span>' + data.Table30[0].urinary_bilirubin + " " + ((data.Table30[0].urinary_bilirubin_unit == null || data.Table30[0].urinary_bilirubin_unit == "") ? "" : data.Table30[0].urinary_bilirubin_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urine_blood != null && data.Table30[0].urine_blood != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINE BLOOD</label> : <span>' + data.Table30[0].urine_blood + ' </span></div>';
                                }
                                if (data.Table30[0].urobilinogen != null && data.Table30[0].urobilinogen != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">UROBILINOGEN</label> : <span>' + data.Table30[0].urobilinogen + " " + ((data.Table30[0].urobilinogen_unit == null || data.Table30[0].urobilinogen_unit == "") ? "" : data.Table30[0].urobilinogen_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_glucose != null && data.Table30[0].urinary_glucose != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINARY GLUCOSE</label> : <span>' + data.Table30[0].urinary_glucose + ' </span></div>';
                                }
                                if (data.Table30[0].urine_ketone != null && data.Table30[0].urine_ketone != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINE KETONE</label> : <span>' + data.Table30[0].urine_ketone + " " + ((data.Table30[0].urine_ketone_unit == null || data.Table30[0].urine_ketone_unit == "") ? "" : data.Table30[0].urine_ketone_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_leucocytes != null && data.Table30[0].urinary_leucocytes != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINARY LEUCOCYTES</label> : <span>' + data.Table30[0].urinary_leucocytes + ' </span></div>';
                                }
                                if (data.Table30[0].nitrite != null && data.Table30[0].nitrite != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">NITRITE</label> : <span>' + data.Table30[0].nitrite + " " + ((data.Table30[0].nitrite_unit == null || data.Table30[0].nitrite_unit == "") ? "" : data.Table30[0].nitrite_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].ph != null && data.Table30[0].ph != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">PH</label> : <span>' + data.Table30[0].ph + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_protein != null && data.Table30[0].urinary_protein != '') {
                                    div = div + '<div class="col-md-12"><label class="control-label">URINARY PROTEIN</label> : <span>' + data.Table30[0].urinary_protein + ' </span></div>';
                                }
                            }
                        }

                        $('.tbl_patient_summary_details').html('');
                        $('.tbl_patient_summary_details').html(div);
                    }
                    else {
                        $('.tbl_patient_summary_details').html('');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function loadPatientSummary() {
    var PatientSummary = {
        patient_id: patient,
        doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/PatientSummary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSummary),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    tr = tr + '<div class="col-md-12"><table class="table table-bordered table-hover"><thead><tr><th>Test Name</th><th>Last Tested Day</th></tr></thead><tbody style="font-style:italic"><tr><td>Fasting Blood Sugar</td><td >Not Tested</td></tr><tr><td>Post Prandial Blood Sugar</td><td>Not Tested</td></tr><tr><td>HbA1C</td><td>Not Tested</td></tr><tr><td>Urea</td><td>Not Tested</td></tr><tr><td>Creatinine</td><td>Not Tested</td></tr><tr><td>Urine Albumin Creatinine Ratio</td><td>Not Tested</td></tr><tr><td>Lipid  Profile</td><td>Not Tested</td></tr><tr><td>Urine ACR</td><td>Not Tested</td></tr></tbody></table></div>';
                    $('#PatientSuggestion').html(tr);
                }
                else {

                    var list = '', tr = '';
                    for (var i = 0; i < data.length; i++) {
                        var Fasting_Blood_Sugar = data[0].Fasting_Blood_Sugar;
                        var Post_Prandial_Blood_Sugar = data[0].Post_Prandial_Blood_Sugar;
                        var hbac = data[0].hbac;
                        var Urea = data[0].Urea;
                        var Creatinine = data[0].Creatinine;
                        var UrineAlbuminCreatinineRatio = data[0].UrineAlbuminCreatinineRatio;
                        var Lipid_Profile = data[0].Lipid_Profile;
                        var ACR = data[0].ACR;

                        if (Fasting_Blood_Sugar == 0) {
                            Fasting_Blood_Sugar = 'Today';
                        }
                        else if (Fasting_Blood_Sugar == 1) {
                            Fasting_Blood_Sugar = 'Yesterday';
                        }
                        else if (Fasting_Blood_Sugar == '' || Fasting_Blood_Sugar == null) {
                            Fasting_Blood_Sugar = 'Not Tested';
                        }
                        else {
                            Fasting_Blood_Sugar = humanise(Fasting_Blood_Sugar) + ' ago';
                        }

                        if (Post_Prandial_Blood_Sugar == 0) {
                            Post_Prandial_Blood_Sugar = 'Today';
                        }
                        else if (Post_Prandial_Blood_Sugar == 1) {
                            Post_Prandial_Blood_Sugar = 'Yesterday';
                        }
                        else if (Post_Prandial_Blood_Sugar == '' || Post_Prandial_Blood_Sugar == null) {
                            Post_Prandial_Blood_Sugar = 'Not Tested';
                        }
                        else {
                            Post_Prandial_Blood_Sugar = humanise(Post_Prandial_Blood_Sugar) + ' ago';
                        }

                        if (hbac == 0) {
                            hbac = 'Today';
                        }
                        else if (hbac == 1) {
                            hbac = 'Yesterday';
                        }
                        else if (hbac == '' || hbac == null) {
                            hbac = 'Not Tested';
                        }
                        else {
                            hbac = humanise(hbac) + ' ago';
                        }
                        if (Urea == 0) {
                            Urea = 'Today';
                        }
                        else if (Urea == 1) {
                            Urea = 'yesterday';
                        }
                        else if (Urea == '' || Urea == null) {
                            Urea = 'Not Tested';
                        }
                        else {
                            Urea = humanise(Urea) + ' ago';
                        }
                        if (Creatinine == 0) {
                            Creatinine = 'Today';
                        }
                        else if (Creatinine == 1) {
                            Creatinine = 'Yesterday';
                        }
                        else if (Creatinine == '' || Creatinine == null) {
                            Creatinine = 'Not Tested';
                        }
                        else {
                            Creatinine = humanise(Creatinine) + ' ago';
                        }
                        if (UrineAlbuminCreatinineRatio == 0) {
                            UrineAlbuminCreatinineRatio = 'Today';
                        }
                        else if (UrineAlbuminCreatinineRatio == 1) {
                            UrineAlbuminCreatinineRatio = 'Yesterday';
                        }
                        else if (UrineAlbuminCreatinineRatio == '' || UrineAlbuminCreatinineRatio == null) {
                            UrineAlbuminCreatinineRatio = 'Not Tested';
                        }
                        else {
                            UrineAlbuminCreatinineRatio = humanise(UrineAlbuminCreatinineRatio) + ' ago';
                        }
                        if (Lipid_Profile == 0) {
                            Lipid_Profile = 'Today';
                        }
                        else if (Lipid_Profile == 1) {
                            Lipid_Profile = 'Yesterday';
                        }
                        else if (Lipid_Profile == '' || Lipid_Profile == null) {
                            Lipid_Profile = 'Not Tested';
                        }
                        else {
                            Lipid_Profile = humanise(Lipid_Profile) + ' ago';
                        }
                        if (ACR == 0) {
                            ACR = 'Today';
                        }
                        else if (ACR == 1) {
                            ACR = 'Yesterday';
                        }
                        else if (ACR == '' || ACR == null) {
                            ACR = 'Not Tested';
                        }
                        else {
                            ACR = humanise(ACR) + ' ago';
                        }
                        tr = tr + '<div class="col-md-12"><table class="table table-bordered table-hover"><thead><tr><th>Test Name</th><th>Last Tested Day</th></tr></thead><tbody style="font-style:italic"><tr><td>Fasting Blood Sugar</td><td >' + Fasting_Blood_Sugar + '</td></tr><tr><td>Post Prandial Blood Sugar</td><td>' + Post_Prandial_Blood_Sugar + '</td></tr><tr><td>HbA1C</td><td>' + hbac + '</td></tr><tr><td>Urea</td><td>' + Urea + '</td></tr><tr><td>Creatinine</td><td>' + Creatinine + '</td></tr><tr><td>Lipid  Profile</td><td>' + Lipid_Profile + '</td></tr><tr><td>Urine ACR</td><td>' + ACR + '</td></tr></tbody></table></div>';
                    }
                    $('#PatientSuggestion').html(tr);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function humanise(diff) {
    var str = '';
    var values = [[' year', 365], [' month', 30], [' day', 1]];

    // Iterate over the values...
    for (var i = 0; i < values.length; i++) {
        var amount = Math.floor(diff / values[i][1]);

        // ... and find the largest time value that fits into the diff
        if (amount >= 1) {
            // If we match, add to the string ('s' is for pluralization)
            str += amount + values[i][0] + (amount > 1 ? 's' : '') + ' ';

            // and subtract from the diff
            diff -= amount * values[i][1];
        }
    }

    return str;
}

//end load algorithm


//MoreInfomations
$('.dec_time').on('click', function () {

    var time_val = $('#txtdurationweek').val();
    //alert(time_val)
    time_val = parseInt(time_val) - parseInt(10);
    if (time_val < 10 && time_val > -1) {
        time_val = '0' + time_val;
    }
    if (time_val < 0) {
        $('#txtdurationweek').val('800');
    }
    else {
        $('#txtdurationweek').val(time_val);
    }
    var week = $("input[name='Chk_weeks']:checked").length;
    var dur = $('#txtdurationweek').val();
    var tot = (dur / week).toFixed();
    tot = isFinite(tot) && tot || 0;
    $('#txtDailyDuration').val(tot);
});
$('.inc_time').on('click', function () {

    var time_val = $('#txtdurationweek').val();
    time_val = parseInt(time_val) + parseInt(10);

    if (time_val < 10 && time_val > -1) {
        time_val = '0' + time_val;
    }
    if (time_val > 800) {
        $('#txtdurationweek').val('00');
    }
    else {
        $('#txtdurationweek').val(time_val);
    }
    var week = $("input[name='Chk_weeks']:checked").length;
    var dur = $('#txtdurationweek').val();
    var tot = (parseFloat(dur) / parseFloat(week)).toFixed();
    tot = isFinite(tot) && tot || 0;
    $('#txtDailyDuration').val(tot);
});

//end MoreInfomations



//Algorithm 1 to 27
$("#txtDia").change(function () {

    Bp_algorithm4();
    Bp_bmi_algorithm30();
    high_Bp_algorithm5();
});
var itemvalue = 0;
var tr;
var Suggestion, Prescription, Diagonastics, Exercise, Diet;

$("#txtSys").change(function () {
    age_algorithm1();
    if (($('#CoronaryHeart').prop("checked") == true) || ($('#Angina').prop("checked") == true) || ($('#CVA').prop("checked") == true) || ($('#PAD').prop("checked") == true)) {
        var value = '1';
        Angina_algorithm31(value);
    }
});
var view_pop = '<a href="javascript:void(0);" data-toggle="modal" data-target="#algorithm_modal_1" class="view_all_btn_alg col-md-12">View in list</a>';

//we want to work for the algorithm due to slow process (13-08-2020)
function age_algorithm1() {

}
function bmi_algorithm3() {
}

$("#acr1").change(function () {
    Bp_algorithm4();
});

function Bp_algorithm4() {
    if ($('#txtSys').val() != '' && $('#txtDia').val() != '') {
        var PatientData = {
            visit_report_id: $('#VisitReportID').val(),
            patient_id: $('#Hdnpatient_id').val(),
            age: $('#hndage').val(),
            gender: $('#gender').val(),
            patient_bp_max: $('#txtSys').val(),
            patient_bp_min: $('#txtDia').val(),
            ACR: $("#acr1").val(),
            Potassium: $('#txtPotassium').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Algorithm_4',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                var data1 = JSON.parse(data);
                //if (data1.msg == "Success") {
                //    var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                    if ($.trim(data1) != '') {
                        if (data1[0] == 'Normal') {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_4')) {
                                del_algorithm('4');
                            }
                        }
                        else {
                            if ($.trim(data1[0]) != "" || data1[0] != null) {
                                if ($('.carousel-inner > .item').hasClass('rithmitem_4')) {

                                    if ($('.rithmitem_4').hasClass('active')) {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div>';
                                    }
                                    for (var i = 1; i < 15; i++) {
                                        $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_4').html(itemdataicon + itemdatahead + itemdataBody);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</br>' + data1[2] + '</p></div>';
                                    $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_4').html(tr);

                                    Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                    $('#ASuggestion > .rithmitem_4').html(Suggestion);
                                    $('#APrescription > .rithmitem_4').html(Suggestion);
                                }
                                else {
                                    itemvalue++;

                                    if (itemvalue == 1) {
                                        var itemdataicon = '<div class="item active rithmitem_4"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="item rithmitem_4"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                        $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_4"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                    $('#ModalAlgorithms').append(tr);
                                    Suggestion = '<li class="rithmitem_4"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                    $('#ASuggestion').append(Suggestion);
                                    $('#APrescription').append(Suggestion);
                                }
                                setactivealgorithm();
                            }
                        }
                    }
                }
                //output [one heading, 2 output ]
                //}
                //console.log(data1);
            }
        });
    }
}

function high_Bp_algorithm5() {
    if ($('#txtSys').val() != '' && $('#txtDia').val() != '') {
        var PatientData = {
            visit_report_id: $('#VisitReportID').val(),
            patient_id: $('#Hdnpatient_id').val(),
            age: $('#hndage').val(),
            gender: $('#gender').val(),
            patient_bp_max: $('#txtSys').val(),
            patient_bp_min: $('#txtDia').val()
        }

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

                }
                else {
                    if ($.trim(data1) != '') {
                        if (data1[0] == 'Normal') {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_5')) {
                                del_algorithm('5');
                            }
                        }
                        else {
                            if ($.trim(data1[0]) != "" || data1[0] != null) {
                                if ($('.carousel-inner > .item').hasClass('rithmitem_5')) {
                                    if ($('.rithmitem_5').hasClass('active')) {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_5').html(itemdataicon + itemdatahead + itemdataBody);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                    $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_5').html(tr);

                                    Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                    $('#ASuggestion > .rithmitem_5').html(Suggestion);
                                    $('#AExercise > .rithmitem_5').html(Suggestion);
                                    $('#lifeExercise > .rithmitem_5').html(Suggestion);
                                }
                                else {
                                    itemvalue++;
                                    if (itemvalue == 1) {
                                        var itemdataicon = '<div class="item active rithmitem_5"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="item rithmitem_5"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                        $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }

                                    tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_5"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>';
                                    $('#ModalAlgorithms').append(tr);
                                    Suggestion = '<li class="rithmitem_5"><p><strong> ' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                    $('#ASuggestion').append(Suggestion);
                                    $('#AExercise').append(Suggestion);
                                    $('#lifeExercise').append(Suggestion);
                                }
                                setactivealgorithm();
                                if (data1[1] != '') {
                                    $('#HightIntensity').val('2');
                                }
                            }
                        }
                    }
                }
                //}
                //else {
                //    console.log(data1);
                //}
            }
        });
    }
}


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

    if ($('#ChkHeartSound').prop("checked") == true) {
        var value = 'Yes';
        cardiac_algorithm6(value);
    }
    if ($('#ChkHeartSound').prop("checked") == false && $('#ChkMurmurs').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_6')) {
            del_algorithm('6');
        }
    }
});

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

    if ($('#ChkMurmurs').prop("checked") == true) {
        var value = 'Yes';
        cardiac_algorithm6(value);
    }
    if ($('#ChkHeartSound').prop("checked") == false && $('#ChkMurmurs').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_6')) {
            del_algorithm('6');
        }
    }
});


function cardiac_algorithm6(value) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        heart_sound: value,
        murmurs: value,
        history_angina: $("input[name='Angina']:checked").val(),
        CVA: $("input[name='CVA']:checked").val(),
        history_pad: $("input[name='PAD']:checked").val()
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_6')) {
                            del_algorithm('6');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_6')) {
                                if ($('.rithmitem_6').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_6').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_6').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_6').html(Suggestion);
                            }
                            else {
                                itemvalue++;

                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_6"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_6"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_6"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_6"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data);
            //}
        }
    });

}


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

    if ($('#ChkReducedAir').prop("checked") == true) {
        var value = 'Yes';
        rs_algorithm7(value);
    }
    if ($('#ChkReducedAir').prop("checked") == false && $('#ChkCrackles').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_7')) {
            del_algorithm('7');
        }
    }
});

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

    if ($('#ChkCrackles').prop("checked") == true) {
        var value = 'Yes';
        rs_algorithm7(value);
    }
    if ($('#ChkReducedAir').prop("checked") == false && $('#ChkCrackles').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_7')) {
            del_algorithm('7');
        }
    }

});

function rs_algorithm7(value) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        reduce_air_entry: value,
        crackles: value
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_7')) {
                            del_algorithm('7');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_7')) {
                                if ($('.rithmitem_7').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_7').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_7').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_7').html(Suggestion);
                            }
                            else {
                                itemvalue++;

                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_7"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_7"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_7"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_7"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data);
            //}
        }
    });

}

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

    if ($('#ChkBowelSounds').prop("checked") == true) {
        var value = 'Yes';
        abs_algorithm8(value);
    }
    if ($('#ChkBowelSounds').prop("checked") == false && $('#ChkOrganomegaly').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_8')) {
            del_algorithm('8');
        }
    }
});

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

    if ($('#ChkOrganomegaly').prop("checked") == true) {
        var value = 'Yes';
        abs_algorithm8(value);
    }
    if ($('#ChkBowelSounds').prop("checked") == false && $('#ChkOrganomegaly').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_8')) {
            del_algorithm('8');
        }
    }
});

function abs_algorithm8(value) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        bowel_sounds: value,
        organomegaly: value
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_8')) {
                            del_algorithm('8');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_8')) {
                                if ($('.rithmitem_8').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_8').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_8').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_8').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_8"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_8"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_8"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_8"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }

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

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

    if ($('#ChkTremors').prop("checked") == true) {
        var value = 'Yes';
        cns_algorithm9(value);
    }
    if ($('#ChkTremors').prop("checked") == false && $('#ChkCognitive').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_9')) {
            del_algorithm('9');
        }
    }
});

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

    if ($('#ChkCognitive').prop("checked") == true) {
        var value = 'Yes';
        cns_algorithm9(value);
    }
    if ($('#ChkTremors').prop("checked") == false && $('#ChkCognitive').prop("checked") == false) {
        if ($('.carousel-inner > .item').hasClass('rithmitem_9')) {
            del_algorithm('9');
        }
    }
});


function cns_algorithm9(value) {
    var chkANeuropathy = 0;
    if (chkANeuropathy == "1") {
        $("#chkANeuropathy").prop('checked', true).change();
        if ($('#chkANeuropathy').prop('checked')) {
            chkANeuropathy = '1';
        }
    }
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        tremors_weakness: value,
        cognitive_imparement: value,
        peripharal_neuhropathy: $("input[name='per_neu']:checked").val(),
        autonomic_neuropathy: chkANeuropathy
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_9')) {
                            del_algorithm('9');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_9')) {
                                if ($('.rithmitem_9').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_9').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_9').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_9').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_9"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_9"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_9"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_9"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });
}

$("#txtHbA1c").change(function () {
    HbA1c_algorithm12();
});

function HbA1c_algorithm12(aa) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        patient_hbac_record_value: $('#txtHbA1c').val(),
        egfr_value: aa,
        patient_blood_sugar_type: $("txtBloodsugarV_1").val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Algorithm_12',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data1 = JSON.parse(data);
            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_12')) {
                            del_algorithm('12');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_12')) {
                                if ($('.rithmitem_12').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }
                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_12').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_12').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_14').html(Suggestion);
                            }
                            else {
                                itemvalue++;

                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_12"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_12"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_12"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_12"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });
}

$("#txtSimulated").change(function () {
    c_peptide_algorithm14();
});


function c_peptide_algorithm14() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        c_peptite_fasting: $('#txtSimulated').val()
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_14')) {
                            del_algorithm('14');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_14')) {
                                if ($('.rithmitem_14').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_14').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_14').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_14').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                console.log(data1);
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_14"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_14"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_14"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_14"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1)
            //}

        }
    });
}

function c_peptide_algorithm15() {
    var chkGAD = 0;
    if ($('#chkGAD').prop('checked')) {
        chkGAD = '1';
    }
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        c_peptite_fasting: $('#txtSimulated').val(),
        GAD_Antibiotics_test: chkGAD
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_15')) {
                            del_algorithm('15');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_15')) {
                                if ($('.rithmitem_15').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_15').html(itemdatahead + itemdataBody + view_pop);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_15').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_15').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_15"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_15"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_15"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_15"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);

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

}

function egfr_algorithm16(egfrval) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        egfr_value: egfrval
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_16')) {
                            del_algorithm('16');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_16')) {
                                if ($('.rithmitem_16').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_16').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_16').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_16').html(Suggestion);
                                $('#ADiagonastics > .rithmitem_16').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_16"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_16"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_16"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_16"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });

}

function renal_algorithm17(egfrval) {
    var Chknepropathy = 0;
    if ($('#Chknepropathy').prop('checked')) {
        nephropathy = '1';
    }
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        Urea: $('#txtUrea').val(),
        creatinine: $('#txtCreatinine').val(),
        egfr_value: egfrval,
        nephropathy: Chknepropathy
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Algorithm_17',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data1 = JSON.parse(data);
            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_17')) {
                            del_algorithm('17');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_17')) {
                                if ($('.rithmitem_17').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_17').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_17').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiet > .rithmitem_17').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_17"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_17"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_17"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_17"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiet').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });
}

$("input[name='acr1']").click(function () {
    diagnostics_algorithm18();
});


function diagnostics_algorithm18() {
    if ($('#txtSys').val() != '' && $('#txtDia').val() != '') {
        var PatientData = {
            visit_report_id: $('#VisitReportID').val(),
            patient_id: $('#Hdnpatient_id').val(),
            age: $('#hndage').val(),
            gender: $('#gender').val(),
            type_of_diabetes: $('#diabVal').val(),
            diabetes_of_year: $('#diabetes').html(),
            patient_bp_max: $('#txtSys').val(),
            patient_bp_min: $('#txtDia').val()
        }

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

                //if (data1.msg == "Success") {
                //    var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    var data1 = JSON.parse(data);
                    if ($.trim(data1) != '') {
                        if (data1[0] == 'Normal') {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_18')) {
                                del_algorithm('18');
                            }
                        }
                        else {
                            if ($.trim(data1[0]) != "" || data1[0] != null) {
                                if ($('.carousel-inner > .item').hasClass('rithmitem_18')) {
                                    if ($('.rithmitem_18').hasClass('active')) {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[2] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_18').html(itemdataicon + itemdatahead + itemdataBody);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                    $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_18').html(tr);

                                    Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                    $('#ADiagonastics > .rithmitem_18').html(Suggestion);
                                }
                                else {
                                    itemvalue++;

                                    if (itemvalue == 1) {
                                        var itemdataicon = '<div class="item active rithmitem_18"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="item rithmitem_18"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[2] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                        $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_18"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                    $('#ModalAlgorithms').append(tr);

                                    Suggestion = '<li class="rithmitem_18"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                    $('#ADiagonastics').append(Suggestion);
                                }
                                setactivealgorithm();
                            }
                        }
                    }
                }
                //}
                //else {
                //    console.log(data1);
                //}
            }

        });
    }
}



function cholestrol_algorithm19(egrfval) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        egfr_value: egrfval,
        patient_food_preference: '1',                                     //DB_Value
        stage_CKD: $('#txtCKD').val(),
        Triglycerides: $('#txtTriglycerides').val(),
        LDL: $('#txtLDL').val(),
        HDL: $('#txtHDL').val()
    }

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

            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data1 = JSON.parse(data);
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_19')) {
                            del_algorithm('19');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_19')) {
                                if ($('.rithmitem_19').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/ur_assist.png" class="Content/img/algorithm-icons/diet.png" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_19 > .desc_text_content').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_19').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiet > .rithmitem_19').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_19"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_19"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_19"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diet.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_19"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiet').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });

}

$('#txtTriglycerides').change(function () {
    cholestrol_algorithm20();
});

function cholestrol_algorithm20() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        Triglycerides: $('#txtTriglycerides').val(),
        LDL: $('#txtLDL').val(),
        HDL: $('#txtHDL').val(),
        diabetes_of_year: $('#diabetes').html(),
        type_of_diabetes: $('#diabVal').val()
    }

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

            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_20')) {
                            del_algorithm('20');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {

                            if ($('.carousel-inner > .item').hasClass('rithmitem_20')) {
                                if ($('.rithmitem_20').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }
                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_20').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_20').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#AExercise > .rithmitem_20').html(Suggestion);
                                $('#lifeExercise > .rithmitem_20').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_20"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_20"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_20"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_20"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#AExercise').append(Suggestion);
                                $('#lifeExercise').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1)
            //}
        }
    });
}


$('#txtTriglycerides').change(function () {
    high_tgl_algorithm21();
});

function high_tgl_algorithm21() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        Triglycerides: $('#txtTriglycerides').val(),
        LDL: $('#txtLDL').val(),
        HDL: $('#txtxtHDLtHDL').val()
    }

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

            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data1 = JSON.parse(data);
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_21')) {
                            del_algorithm('21');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_21')) {
                                if ($('.rithmitem_21').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_21').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_21').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_21').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_21"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_21"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }

                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_21"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/suggestions.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_21"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1)
            //}
        }
    });
}


$('#txtHbA1c').change(function () {
    lipid_algorithm22();
});

function lipid_algorithm22() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        patient_hbac_record_value: $('#txtHbA1c').val(),
        diabetes_of_year: $('#diabetes').html(),
        type_of_diabetes: $('#diabVal').val()
    }

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

            //if (data1.msg == "Success") {
            //    var data1 = data1.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data1 = JSON.parse(data);
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_22')) {
                            del_algorithm('22');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_22')) {
                                if ($('.rithmitem_22').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_22').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_22').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#APrescription > .rithmitem_22').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_22"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_22"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }

                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_22" ><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_22"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();

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


function ASCVD_Risk_Score_algorithm24(totpercentage) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        ascvd_score: totpercentage,
        Triglycerides: $('#txtTriglycerides').val(),
        LDL: $('#txtCLDL').val(),
        HDL: $('#txtCHDL').val(),
        diabetes_of_year: $('#diabetes').html(),
        type_of_diabetes: $('#diabVal').val(),
        patient_bp_max: $('#txtCSysBP').val(),
        patient_bp_min: $('#txtCDiaBP').val()
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_24')) {
                            del_algorithm('24');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_24')) {
                                if ($('.rithmitem_24').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_24 > .desc_text_content').html(itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_24').html(tr);

                                Suggestion = '<li class="<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#APrescription > .rithmitem_24').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_24"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_24"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_24"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_24"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#APrescription').append(Suggestion);
                            }
                            setactivealgorithm();

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

}


$("#ChkDetachment").change(function () {
    if ($('#ChkDetachment').val() == 1) {
        retinal_algorithm26();
    }
});

$("#ChkHemorrhage").change(function () {
    if ($('#ChkHemorrhage').val() == 1) {
        retinal_algorithm26();
    }
});

$("#PDRradio").change(function () {
    retinal_algorithm26();
});

$("#NPDRradio").change(function () {
    retinal_algorithm26();
});

function retinal_algorithm26() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        retinal_detachment: $("#ChkDetachment").val(),
        viterous_hemorage: $("#ChkHemorrhage").val(),
        pdr: $("#PDRradio").val(),
        npdr: $("#PDRradio").val(),
        diabetes_of_year: $('#diabetes').html(),
        type_of_diabetes: $('#diabVal').val()
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_26')) {
                            del_algorithm('26');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_26')) {
                                if ($('.rithmitem_26').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {
                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_26').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_26').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#AExercise > .rithmitem_26').html(Suggestion);
                                $('#lifeExercise > .rithmitem_26').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_26"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_26"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[2] == '') {
                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                }

                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_26"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_26"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#AExercise').append(Suggestion);
                                $('#lifeExercise').append(Suggestion);
                            }

                            setactivealgorithm();
                            if (data1[1] != '') {
                                $('#HightIntensity').val('2');
                            }

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

}
function setactivealgorithm() {
    for (var i = 1; i < 15; i++) {
        $('#carousel_pg_' + i + ' > .carousel-inner > .item').removeClass('active');
    }
    for (var j = 1; j < 15; j++) {
        $('#carousel_pg_' + j + ' > .carousel-inner > .item:last-child').addClass('active');
    }
    algorithmshowhide();
}

//we want to work for the algorithm due to slow process (13-08-2020)
function neuropathy_algorithm27() {
}



$("#R_tmt").change(function () {
    TMT_algorithm28();
});

function TMT_algorithm28() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        TMT: $('#R_tmt').val()
    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_28')) {
                            del_algorithm('28');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_28')) {
                                if ($('.rithmitem_28').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_28').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_28').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ASuggestion > .rithmitem_28').html(Suggestion);
                                $('#AExercise > .rithmitem_28').html(Suggestion);
                                $('#lifeExercise > .rithmitem_28').html(Suggestion);
                            }
                            else {
                                itemvalue++;
                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_28"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_28"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }

                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_28"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/exercise.jpg" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>';
                                $('#ModalAlgorithms').append(tr);
                                Suggestion = '<li class="rithmitem_28"><p><strong> ' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ASuggestion').append(Suggestion);
                                $('#AExercise').append(Suggestion);
                                $('#lifeExercise').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data);
            //}
        }
    });

}


//we want to work for the algorithm due to slow process (13-08-2020)
function Type1_algorithm29() {
}

function Bp_bmi_algorithm30() {
    if ($('#txtSys').val() != '' && $('#txtDia').val() != '') {
        var PatientData = {
            visit_report_id: $('#VisitReportID').val(),
            patient_id: $('#Hdnpatient_id').val(),
            age: $('#hndage').val(),
            gender: $('#gender').val(),
            patient_bp_max: $('#txtSys').val(),
            patient_bp_min: $('#txtDia').val(),
            patient_bmi: $('#bmi').html(),
            Potassium: $('#txtPotassium').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CaseStudy/Algorithm_30',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientData),
            success: function (data) {
                var data1 = JSON.parse(data);
                //if (data1.msg == "Success") {
                //    var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if ($.trim(data1) != '') {
                        if (data1[0] == 'Normal') {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_30')) {
                                del_algorithm('30');
                            }
                        }
                        else {
                            if ($.trim(data1[0]) != "" || data1[0] != null) {
                                if ($('.carousel-inner > .item').hasClass('rithmitem_30')) {

                                    if ($('.rithmitem_30').hasClass('active')) {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div>';
                                    }
                                    for (var i = 1; i < 15; i++) {
                                        $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_30').html(itemdataicon + itemdatahead + itemdataBody);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</br>' + data1[2] + '</p></div>';
                                    $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_30').html(tr);

                                    Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                    $('#ASuggestion > .rithmitem_30').html(Suggestion);
                                    $('#APrescription > .rithmitem_30').html(Suggestion);
                                }
                                else {
                                    itemvalue++;

                                    if (itemvalue == 1) {
                                        var itemdataicon = '<div class="item active rithmitem_30"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    else {
                                        var itemdataicon = '<div class="item rithmitem_30"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div>';
                                    }
                                    var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                    if (data1[1] == '') {

                                    }
                                    else {
                                        var itemdataBody = '<p>' + data1[2] + '</p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                    }

                                    for (var i = 1; i < 15; i++) {
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                        $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                        $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                    }
                                    if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                    tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_30"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/prescription.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                    $('#ModalAlgorithms').append(tr);
                                    Suggestion = '<li class="rithmitem_30"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                    $('#ASuggestion').append(Suggestion);
                                    $('#APrescription').append(Suggestion);
                                }
                                setactivealgorithm();
                            }
                        }
                    }
                }
                //output [one heading, 2 output ]
                //}
                //else {
                //    console.log(data1);
                //}
            }
        });
    }
}

function Angina_algorithm31(value) {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        history_angina: value,
        CVA: value,
        history_pad: value,
        CHD: value
    }

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

            }
            else {

                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_31')) {
                            del_algorithm('31');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_31')) {
                                if ($('.rithmitem_31').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_31').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_31').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_31').html(Suggestion);
                            }
                            else {
                                itemvalue++;

                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_31"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_31"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_31"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_31"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data1);
            //}
        }
    });
}


$("#txtLDL").change(function () {
    Ascvd_risk_factor_algorithm32();
});

function Ascvd_risk_factor_algorithm32() {
    var PatientData = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        age: $('#hndage').val(),
        gender: $('#gender').val(),
        patient_bp_max: $('#txtSys').val(),
        patient_bp_min: $('#txtDia').val(),
        type_of_diabetes: $('#diabVal').val(),
        LDL: $('#txtLDL').val(),
        egfr_value: $('#txtEGFR').val(),
        ACR: $("#acr1").val()

    }

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

            }
            else {
                if ($.trim(data1) != '') {
                    if (data1[0] == 'Normal') {
                        if ($('.carousel-inner > .item').hasClass('rithmitem_32')) {
                            del_algorithm('32');
                        }
                    }
                    else {
                        if ($.trim(data1[0]) != "" || data1[0] != null) {
                            if ($('.carousel-inner > .item').hasClass('rithmitem_32')) {
                                if ($('.rithmitem_32').hasClass('active')) {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#carousel_pg_' + i + ' > .carousel-inner > .rithmitem_32').html(itemdataicon + itemdatahead + itemdataBody);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div>'
                                $('#ModalAlgorithms > .algorithm_item_box > .rithmitem_32').html(tr);

                                Suggestion = '<p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p>';
                                $('#ADiagonastics > .rithmitem_32').html(Suggestion);
                            }
                            else {
                                itemvalue++;

                                if (itemvalue == 1) {
                                    var itemdataicon = '<div class="item active rithmitem_32"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                else {
                                    var itemdataicon = '<div class="item rithmitem_32"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div>';
                                }
                                var itemdatahead = '<div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p>';
                                if (data1[1] == '') {

                                }
                                else {
                                    var itemdataBody = '<p>' + data1[2] + ' </p></div>' + view_pop + '<div class="clearfix"></div></div>';
                                }

                                for (var i = 1; i < 15; i++) {
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .tot_count').html(itemvalue);
                                    $('#carousel_pg_' + i + ' > .carousel-inner').append(itemdataicon + itemdatahead + itemdataBody);
                                    $('#count_sec_pg_' + i + ' > .pg_no_txt > .current_count').html(itemvalue);
                                }
                                if (itemvalue != 0) { $('.carousel-inner > .item > .view_all_btn_alg').html('View all (' + itemvalue + ') in list'); } else { $('.carousel-inner > .item > .view_all_btn_alg').html('View all in list'); }
                                tr = '<div class="algorithm_item_box"><div class="col-md-12 rithmitem_32"><div class="col-md-1 padding0"><img src="Content/img/algorithm-icons/diagnostics.png" class="img-responsive ur_assist_img" /></div><div class="col-md-11 padding0 desc_text_content"><p class="red_head_clr">' + data1[1] + '</p><p>' + data1[2] + '</p></div></div><div class="clearfix"></div></div>'
                                $('#ModalAlgorithms').append(tr);

                                Suggestion = '<li class="rithmitem_32"><p><strong>' + data1[1] + '</strong>: ' + data1[2] + '</p></li>';
                                $('#ADiagonastics').append(Suggestion);
                            }
                            setactivealgorithm();
                        }
                    }
                }
            }
            //}
            //else {
            //    console.log(data);
            //}
        }
    });
}


// Algorithm end

//next Appointment ending point


//1st screen Python Api starting point


//1st screen python Api end point 

var clickValue = 0;
$(".btn-loadmore").click(function () {

    clickValue++;
    if (clickValue == 1) {
        load_patient_summary_visit_report();
    }

});


function printPrescription(val) {
    debugger;
    window.open('/PatientDashboard/PPDF?visitreportid=' + val + '&lantype=' + $('#sellang').val() + '&btnval=1', "_blank");
}

//video function

//new video call function code

$('#btnvideocall').click(function () {
    NewVideoFunction();
});

$('#btnvideocall_1').click(function () {
    NewVideoFunction();
});

// Add By Akshaya for New Development in Video Call

function NewVideoFunction() {
    debugger;
    var videoUrl = '';
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
        videoUrl = $('#HUrsugarVideoUrl').val();
    }
    else {
        videoUrl = $('#HCurolaVideoUrl').val();
    }
    // var cid = $('#appointment_id').val();
    var uid = $('#Hdnpatient_id').val();
    uid = uid.replace("PCH", "1");
    var pname = $('#PatientName').html();
    // pname = encodeURIComponent(pname);
    var dname = $('#Doc_Name').val();
    //dname = encodeURIComponent(dname);
    var pname_doc = 'Doctor';
    var d_uid = new Date().getTime();
    d_uid = Math.round(d_uid / 1000);
    var invoiceid = $('#VisitReportID').val();
    var vipdata = {
        Patient_id: uid,
        doctor_id: $('#doctorId').val(),
        doctor_Name: dname,
        pname: pname,
        invoice_id: invoiceid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/clicktovideocall',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(vipdata),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
                var cid = data1
                var query_doc = videoUrl + '?cid=' + cid + '||Pname=' + pname_doc + '||uid=' + d_uid;
                if (confirm("Patient doesn't have mobile app.You Want to send invite ?")) {
                    debugger;
                    $('#txtvideoEmail').val($('#PatientName').html());
                    $('#txtvideoPhone').val($('#Patientpno').val());
                    if ($('#txtvideoPhone').val().length = 10) {
                        $('#btnsendmsg').click();
                    }
                    else {
                        $('.addpatientvideo').click();
                    }
                    openSession(query_doc);
                }
                else {
                }
            }
            else {
                var cid = data1
                var query_doc = videoUrl + '?cid=' + cid + '||Pname=' + pname_doc + '||uid=' + d_uid;
                if (data1.success == 1) {
                    openSession(query_doc);
                }
                else {
                    if (confirm("Patient doesn't have mobile app.You Want to send invite ?")) {
                        debugger;
                        $('#txtvideoEmail').val($('#PatientName').html());
                        $('#txtvideoPhone').val($('#Patientpno').val());
                        if ($('#txtvideoPhone').val().length = 10) {
                            console.log('#txtvideoPhone');
                            $('#btnsendmsg').click();
                        }
                        else {
                            $('.addpatientvideo').click();
                        }
                        openSession(query_doc);
                    }
                }
            }

        }
    });
}


// Commented By Akshaya for New Development in Video Call

//function videofunction() {
//    var videoUrl = '';
//    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
//        videoUrl = $('#HUrsugarVideoUrl').val();
//    }
//    else {
//        videoUrl = $('#HCurolaVideoUrl').val();
//    }
//    var cid = $('#appointment_id').val();
//    var a = '=' + cid + '&Pname=' + $('#txtvideoEmail').val() + '&uid=' + $('#Patientpno').html();
//    var uid = $('#Hdnpatient_id').val();
//    uid = uid.replace("PCH", "1");
//    var pname = $('#PatientName').html();
//    pname = encodeURIComponent(pname);    
//    var query = videoUrl + '?cid=' + cid + '||Pname=' + pname + '||uid=' + uid;
//    var pname_doc = 'Doctor';
//    var d_uid = new Date().getTime();
//    d_uid = Math.round(d_uid / 1000);
//    var query_doc = videoUrl + '?cid=' + cid + '||Pname=' + pname_doc + '||uid=' + d_uid;
//    $('#cid').val(cid);
//    $('#channel').val(cid);
//    var vipdata = {
//        Patient_id: $('#Hdnpatient_id').val(),
//        doctor_id: $('#doctorId').val(),
//        Dml_Indicator: '13',
//        pname: pname,
//        uid: uid,
//        product_code: $('#HProductCode').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/caseStudy/videopush_notification?cid=' + query + '&cid_id=' + cid,
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(vipdata),
//        success: function (data) {
//            debugger;
//            var data1 = JSON.parse(data);
//            // if (data1.msg == "Success") {
//            //  var data1 = data1.data;
//            var a = '=' + cid + '&Pname=' + $('#PatientName').html() + '&uid=' + $('#Patientpno').html();
//            var uid = $('#Hdnpatient_id').val();
//            uid = uid.replace("PCH", "1");
//            var pname = $('#Doc_Name').val();
//            pname = encodeURIComponent(pname);
//            if (pname == "" || pname == null) {
//                pname = "Doctor";
//            }
//            channelRef = ref.child("video/channels").child(cid);
//            if (jQuery.isEmptyObject((data))) {
//                if (confirm("Patient doesn't have mobile app.You Want to send invite ?")) {
//                    debugger;
//                    $('#txtvideoEmail').val($('#PatientName').html());
//                    $('#txtvideoPhone').val($('#Patientpno').val());
//                    if ($('#txtvideoPhone').val().length = 10) {
//                        $('#btnsendmsg').click();
//                    }
//                    else {
//                        $('.addpatientvideo').click();
//                    }
//                    openSession(query_doc);
//                }
//                else {
//                }
//            }
//            else {
//                if (data1.success == 1) {
//                    openSession(query_doc);
//                }
//                else {
//                    if (confirm("Patient doesn't have mobile app.You Want to send invite ?")) {
//                        debugger;
//                        $('#txtvideoEmail').val($('#PatientName').html());
//                        $('#txtvideoPhone').val($('#Patientpno').val());
//                        if ($('#txtvideoPhone').val().length = 10) {
//                            console.log('#txtvideoPhone');
//                            $('#btnsendmsg').click();
//                        }
//                        else {
//                            $('.addpatientvideo').click();
//                        }
//                        openSession(query_doc);
//                    }
//                }
//            }
//            //}
//            //else {
//            //    console.log(data1);
//            //}
//        }
//    });
//}


var videoInterval = '';
function openSession(query) {
    debugger;
    $('#videoTimer').val('');
    if (videoInterval != '') {
        clearInterval(videoInterval);
    }
    query = query.replace("||", "&");
    query = query.replace("||", "&");
    //channelRef.update({
    //    status: true,
    //    v_id: $('#VisitReportID').val()
    //})
    $('#iframeurl').html('<iframe src=' + query + ' allow="camera; microphone" title="video call"></iframe>');
    $('#videocallnew').modal('show');
    startTimerDisplay();
}

function startTimerDisplay() {
    const second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24;
    var countDown = 0;
    videoInterval = setInterval(function () {
        countDown += 1000;
        timingHour = Math.floor((countDown % (day)) / (hour));
        timingMin = Math.floor((countDown % (hour)) / (minute));
        timingSec = Math.floor((countDown % (minute)) / second);

        if (timingHour < 10) {
            timingHour = '0' + timingHour;
        }
        if (timingMin < 10) {
            timingMin = '0' + timingMin;
        }
        if (timingSec < 10) {
            timingSec = '0' + timingSec;
        }
        if (countDown > (60 * 60 * 1000)) {
            clearInterval(videoInterval);
        }
        else {
            document.getElementById('videoTimer').innerText = timingHour + ":" + timingMin + ":" + timingSec;
        }
    }, second)
}


$('#videocls').click(function () {
    closeSession();
    if ($('#appointment_type').val() == "2") {
        $('#feedback_type_video').val("2");
        $('#feedback_popup').modal('toggle');
    }
});
function closeSession() {
    channelRef.update({
        status: false
    })
}

//video call feedback

function submit_feedback() {
    var emoji = $('.feedbackvideo li.active').attr('class');
    emoji = emoji.replace("active", "");
    $('#feedback_popup').modal('toggle');
    var feedback_data = {
        no_of_stars: emoji,
        cid: $('#cid').val(),
        feedback: $("input[name='fb']:checked").val(),
        indicator_id: "FI",
        patient_id: $('#Hdnpatient_id').val(),
        patient_name: $('#PatientName').html()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Videocall_feedback',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(feedback_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                $('#closeid').click();
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#btnsendmsg').click(function () {
    var videoUrl = '';
    var pageLink = '';
    var packageName = '';
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
        videoUrl = $('#HUrsugarVideoUrl').val();
        pageLink = $('#HUrsugarDeepLink').val();
        packageName = $('#HUrsugarPackageName').val();
    }
    else {
        videoUrl = $('#HCurolaVideoUrl').val();
        pageLink = $('#HCurolaDeepLink').val();
        packageName = $('#HCurolaPackageName').val();
    }

    var cid = $('#channel').val();
    var a = '=' + cid + '&Pname=' + $('#txtvideoEmail').val() + '&uid=' + $('#Patientpno').html();
    var uid = new Date().getTime();
    uid = Math.round(uid / 1000);
    var pname = $('#txtvideoEmail').val();
    pname = encodeURIComponent(pname);
    debugger;
    var query = videoUrl + '?cid=' + cid + '&Pname=' + pname + '&uid=' + uid;
    var Engages = {
        "dynamicLinkInfo": {
            "domainUriPrefix": pageLink,
            "link": query,
            "androidInfo": {
                "androidPackageName": packageName,
                "androidFallbackLink": query
            },
        }
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=' + $('#Hfirebasekey').val(),
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engages),
        success: function (data) {
            //var data = JSON.parse(data);
            //if (data.msg == "Success") {
            //    var data = data.data;
            console.log(data);
            var a = data.shortLink;
            var Engage = {
                email: $('#txtvideoEmail').val(),
                phonenumber: $('#txtvideoPhone').val(),
                cid: $('#cid').val(),
                Pname: $('#PatientName').html(),
                uid: $('#Patientpno').html(),
                doctor_name: $('#Doc_Name').val()
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/CaseStudy/emailsms?url=' + a,
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(Engage),
                success: function (data) {

                    $(".head-video-wap-popup").removeClass('open');
                    //alert('Invite Sent');
                    toastr.success('Invite Sent',
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })



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

$('.cus-video-close-btn').click(function () {
    $('#iframeurl').html('');
});

function videostarted() {
    var Engage = {
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        check_by: $('#doctorId').val(),
        check_staus: '7',
        Dml_Indicator: 'VCI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engage),
        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) {
                        $('#patient_checkin_videoId').val(data[0].patient_checkin_id);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function videoended() {
    var Dml_Indicator = '', check_staus = '';
    Dml_Indicator = 'VCE';
    check_staus = 8;
    var Engage = {
        patient_id: $('#Hdnpatient_id').val(),
        slot_start_time: $('#VisitReportID').val(),
        check_by: $('#doctorId').val(),
        check_staus: check_staus,
        Dml_Indicator: Dml_Indicator,
        visit_report_id: $('#EditVisitReportID').val(),
        patient_checkin_id: $('#patient_checkin_videoId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Patient_checkin',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Engage),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                $('#videoCall').modal('hide');
            }
            else {
                console.log(data);
            }
        }
    });
}

//inside casesheet collect payment code

//invoice payment
function collectpayment() {
    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: $('#doctorId').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") {
                                    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);
                                        }
                                    }
                                    invoice_quickSelect();
                                    ActiveInvoice();
                                }
                                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: $('#doctorId').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 = $('#doctorId').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 = $('#VisitReportID').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") {
                    collectpayment();
                }
                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: $('#doctorId').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: $('#VisitReportID').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") {
                $('#InvoiceDate').val('');
                $('#InvoiceName').val('');
                $('#InvoiceAmount').val('');
                collectpayment();
            }
            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") {
                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: $('#doctorId').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 data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                $('#cpi_activeInvoice_body').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    debugger;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            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><span class="print btn btn-primary btn-sm mr-15"><i class="fa fa-print" onclick=Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\") ></i></span>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td><a class="payment btn btn-default  btn-sm mr-15" href="javascript:void(0);"  data-backdrop="static" 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 btn-default  btn-sm mr-15" href="javascript:void(0);" data-backdrop="static" 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 btn-default  btn-sm mr-15" href="javascript:void(0);" 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></td><td><a class="delete btn btn-danger  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);
            }
        }
    });
}

function add_payment1(labid) {
    debugger;
    $('#pack_id').val(labid);
    $('#Selpaymenttype').val('1');
    $('#modal_collectpayment_inner').modal('toggle');
}

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;
                        patient_id = $('#Hdnpatient_id').val();
                        if (lab_order_id.length > 3) {
                            doc_id = lab_order_id.split('-')[0];
                            if (doc_id == ($('#doctorId').val())) {
                                get_package_details(lab_order_id, invoice_id, patient_id);
                            }
                        }

                        var InvoiceId = {
                            doctor_id: $('#doctorId').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) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    var data = data.data;
                                    if (jQuery.isEmptyObject((data))) {
                                    }
                                    else {
                                    }
                                    $('#paymentamount').val('');
                                    doc_id = lab_order_id.split('-')[0];
                                    if (doc_id == ($('#doctorId').val())) {
                                        get_package_details(lab_order_id, invoice_id, $('#Hdnpatient_id').val());
                                    }
                                    ActiveInvoice();
                                    HistroyInvoice();
                                    toastr.success("Payment Completed successfully!!!");
                                    $('.paymentclose').click();
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });
                    }
                    else {
                        toastr.warning('You have no right to access page contact administrator');
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });

}


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 {

    }
}

$('#mpinsubmit').click(function () {
    var InvoiceId = {
        doctor_id: $('#doctorId').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))) {
                }
                else {
                    if (data.length > 0) {
                        if (data[0].StringMsg == 'Success') {
                            ActiveInvoice();
                        }
                        else if (data[0].StringMsg == 'Cannot able to delete') {
                            toastr.warning('Payment Received - Unable to delete Invoice');
                        }
                        else {
                            toastr.warning('Wrong MPin !!!');
                        }
                    }
                }

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


function ActiveInvoiceDetails(id, amount) {

    $('#curinvoiceid').val(id);
    $('#curamount').val(amount);
    var invoice = {
        invoice_id: $('#curinvoiceid').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        doctor_id: $('#doctorId').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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#tblinvoiceamtdetails_body').empty();
                var tr = '';
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    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 {
                                paymenttype = 'Payment Gateway';
                            }
                            tr = tr + '<tr><td>' + data[i].payment_id + '</td><td>' + paymenttype + '</td><td>' + data[i].payment_amount + '</td></tr>';
                        }
                    }
                    $('#tblinvoiceamtdetails_body').html(tr);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#add_cpi_invoice').click(function () {
    if ($.trim($('#paymentamount').val()) == '') {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('enter the invoice amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        return false;
    }
    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('');
        return false;
    }
    else if (previousval < parseFloat($('#curamount').val())) {
        invoice_status = 2;
        balance_amount = parseFloat($('#curamount').val()) - parseFloat(previousval);
    }
    else {
        invoice_status = 3;
        balance_amount = 0;
        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 == ($('#doctorId').val())) {
                    get_package_details(package_id, invoice_id, patient_id);
                }
            }
        }
    }
    var InvoiceId = {
        doctor_id: $('#doctorId').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,
        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") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
                $('#paymentamount').val('');
                $("#cpiActiveDetails").hide();
                ActiveInvoice();
                HistroyInvoice();

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

$('#cpHistoryInvoiceId').click(function () {
    HistroyInvoice();
});

function HistroyInvoice() {
    $('.cpi_historyInvoice_table').addClass('us-db-loader-history-inv');
    var InvoiceId = {
        doctor_id: $('#doctorId').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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                $('#cpi_historyInvoice_body').empty();
                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 {
                                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 + '\") ></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-placement="top" data-trigger="click" 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 + '\") ></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-placement="top" data-trigger="click" 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');
    }
});

function historydetails() {
    '<td>col1</td><td>col1</td><td>col1</td></tr><tr><td>col1</td><td>col1</td><td>col1</td></tr>';
}
//invoice payment end 


//new diet template function


function DeitPlan() {
    //$('#tblDietChart > tbody').empty();
    //$('#DietTableRowCount').val(0);
    //clear_diet();
    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: visit_id,
        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;
                                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 Deittemlatelist() {
    var Template = {
        created_by: $('#doctorId').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 data = JSON.parse(data);
            if (data.msg == "Success") {
                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=2"><div class="pull-left">Click To Add Diet 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=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><br>';
                        }
                    }
                }
                $('#deittemplatelist').html(tr);
            }
            else {
                console.log(data);
            }
        }
    });
}


function onDeittemplatelist(val) {
    var Etime = "90";
    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 data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    var tr = '';
                    if (jQuery.isEmptyObject((data))) {
                    }
                    else {
                        // $('#tblDietChart > tbody').empty();
                        $('#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  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);
                            $('#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 sess_data_Deit = Time + "," + food + "," + Quantity + "," + 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>" + 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 insertdiet(val) {
    $('#loaderimg').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',
        }
        $.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);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    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);
                                    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'

                                        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(); }, 2000);
                                            clear_diet();

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



                                //old commented by nandhini on 11/01/2022
                                //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);
                                //                if (data.msg == "Success") {
                                //                    Lcount++;
                                //                    if (Lcount == tot_rowM) {
                                //                        setTimeout(function () { $('.close').click(); }, 2000);
                                //                        clear_diet();
                                //                    }
                                //                }
                                //                else {
                                //                    console.log(data);
                                //                }
                                //            }
                                //        });
                                //    }
                                //}
                                $('#txtTime').val('');
                                $('#txtfood').val('');
                                $('#txtQuantity').val('');
                                $('#txtInstructions').val('');
                                $('#txtdietname').val('');
                            }
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
    SaveGeneralInformation();
}

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='btn addicon-btn btn-sm mr20' title='Edit Diet' onclick='Dietedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' title='Delete Diet' 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 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 code ended

// Personal History start point
function personal_history() {

    var labval = {
        personal_history: $('#PHistory').html(),
        patient_id: $('#Hdnpatient_id').val(),
        personal_history_set_by: $('#doctorId').val(),
        Dml_Indicator: 'PLI',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                if (data.length > 2) {
                }
            }
        }
    });
}

$('#add_family').click(function () {
    if ($.trim($("#FSelrelationship").val()) == 0) {
        $('#PFSelrelationship').show();
        $('#PFSelrelationship').fadeOut(8000);
        $('#PFSelrelationship').html('Select the relationship');
        $('#PFSelrelationship').focus();
        return false;
    }
    if ($.trim($("#FSeldisease").val()) == 0) {
        $('#PFSeldisease').show();
        $('#PFSeldisease').fadeOut(8000);
        $('#PFSeldisease').html('Select the Condition');
        $('#PFSeldisease').focus();
        return false;
    }

    var familydetails = {
        patient_id: $('#Hdnpatient_id').val(),
        name: $('#Ftxtname').val(),
        relationship: $('#FSelrelationship').val(),
        disease: $('#FSeldisease').val(),
        no_of_years: $('#Ftxtyears').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        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 = ''
                    for (var i = 0; i < data.length; i++) {
                        var relationship = '';
                        var disease = '', noofyear, notesfamily;
                        if (data[i].relationship == 1) {
                            relationship = 'Father';
                        }
                        else if (data[i].relationship == 2) {
                            relationship = 'Mother';
                        }
                        else if (data[i].relationship == 3) {
                            relationship = 'Brother';
                        }
                        else if (data[i].relationship == 4) {
                            relationship = 'Sister';
                        }
                        else if (data[i].relationship == 5) {
                            relationship = 'Paternal GrandFather';
                        }
                        else if (data[i].relationship == 6) {
                            relationship = 'Paternal GrandMother';
                        }
                        else if (data[i].relationship == 7) {
                            relationship = 'Maternal GrandFather';
                        }
                        else if (data[i].relationship == 8) {
                            relationship = 'Maternal GrandMother';
                        }
                        else if (data[i].relationship == 9) {
                            relationship = 'Both Parents';
                        }
                        else if (data[i].relationship == 10) {
                            relationship = 'All Family number';
                        }
                        else {
                            relationship = '';
                        }
                        if (data[i].disease == 1) {
                            disease = 'CVA';
                        }
                        else if (data[i].disease == 2) {
                            disease = 'Thyroid';
                        }
                        else if (data[i].disease == 3) {
                            disease = 'Hypertension';
                        }
                        else if (data[i].disease == 4) {
                            disease = 'Diabetes';
                        }
                        else if (data[i].disease == 5) {
                            disease = 'Cardiac Diseases';
                        }
                        else if (data[i].disease == 6) {
                            disease = 'Cancer';
                        }
                        else if (data[i].disease == 7) {
                            disease = 'Renal Diseases';
                        }
                        else {
                            disease = '';
                        }
                        if (data[i].no_of_years == null || data[i].no_of_years == "") noofyear = "-";
                        else noofyear = data[i].no_of_years;
                        if (data[i].name == null || data[i].name == "") notesfamily = '-';
                        else notesfamily = data[i].name;
                        tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn addicon-btn btn-sm mr20" onclick="familyedit(' + data[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" onclick="familydelete(' + data[i].patient_family_history_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                    }
                    $('#tbl_family_body').html(tr);

                    $('#Ftxtname').val('');
                    $('#FSelrelationship').val(0);
                    $('#FSeldisease').val(0);
                    $('#Ftxtyears').val('');
                }
            }
            else {
                console.log(data)
            }
        }
    });
});

function familyedit(val) {
    $('#familyedit').val(val);
    var familydetails = {
        Dml_Indicator: 'SS',
        patient_family_history_id: val,
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        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 {
                    if (data.length > 0) {
                        $('#add_family').hide();
                        $('#Update_family').show();
                        for (var i = 0; i < data.length; i++) {
                            $('#Ftxtname').val(data[i].name);
                            $('#FSelrelationship').val(data[i].relationship);
                            $('#FSeldisease').val(data[i].disease);
                            $('#Ftxtyears').val(data[i].no_of_years);
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function familydelete(val) {
    debugger;
    var familydetails = {
        Dml_Indicator: 'D',
        patient_family_history_id: val,
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data = JSON.parse(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#tbl_family_body').empty();
                }
                else {
                    var tr = '';
                    $('#tbl_family_body').empty();
                    for (var i = 0; i < data.length; i++) {

                        var relationship = '';
                        var disease = '', noofyear, notesfamily;
                        if (data[i].relationship == 1) {
                            relationship = 'Father';
                        }
                        else if (data[i].relationship == 2) {
                            relationship = 'Mother';
                        }
                        else if (data[i].relationship == 3) {
                            relationship = 'Brother';
                        }
                        else if (data[i].relationship == 4) {
                            relationship = 'Sister';
                        }
                        else if (data[i].relationship == 5) {
                            relationship = 'Paternal GrandFather';
                        }
                        else if (data[i].relationship == 6) {
                            relationship = 'Paternal GrandMother';
                        }
                        else if (data[i].relationship == 7) {
                            relationship = 'Maternal GrandFather';
                        }
                        else if (data[i].relationship == 8) {
                            relationship = 'Maternal GrandMother';
                        }
                        else if (data[i].relationship == 9) {
                            relationship = 'Both Parents';
                        }
                        else if (data[i].relationship == 10) {
                            relationship = 'All Family number';
                        }
                        else {
                            relationship = '';
                        }
                        if (data[i].disease == 1) {
                            disease = 'CVA';
                        }
                        else if (data[i].disease == 2) {
                            disease = 'Thyroid';
                        }
                        else if (data[i].disease == 3) {
                            disease = 'Hypertension';
                        }
                        else if (data[i].disease == 4) {
                            disease = 'Diabetes';
                        }
                        else if (data[i].disease == 5) {
                            disease = 'Cardiac Diseases';
                        }
                        else if (data[i].disease == 6) {
                            disease = 'Cancer';
                        }
                        else if (data[i].disease == 7) {
                            disease = 'Renal Diseases';
                        }
                        else {
                            disease = '';
                        }

                        if (data[i].no_of_years == null || data[i].no_of_years == "") noofyear = "-";
                        else noofyear = data[i].no_of_years;
                        if (data[i].name == null || data[i].name == "") notesfamily = '-';
                        else notesfamily = data[i].name;

                        tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn addicon-btn btn-sm mr20" onclick="familyedit(' + data[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" onclick="familydelete(' + data[i].patient_family_history_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                    }

                    $('#tbl_family_body').html(tr);

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

}

$('#Update_family').click(function () {
    debugger;
    var familydetails = {
        patient_id: $('#Hdnpatient_id').val(),
        name: $('#Ftxtname').val(),
        relationship: $('#FSelrelationship').val(),
        disease: $('#FSeldisease').val(),
        no_of_years: $('#Ftxtyears').val(),
        patient_family_history_id: $('#familyedit').val(),
        Dml_Indicator: 'U'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#add_family').show();
                    $('#Update_family').hide();
                    //$('#familyedit').val(data[i].patient_family_history_id);
                    var tr = ''
                    for (var i = 0; i < data.length; i++) {
                        var relationship = '';
                        var disease = '', noofyear, notesfamily;
                        if (data[i].relationship == 1) {
                            relationship = 'Father';
                        }
                        else if (data[i].relationship == 2) {
                            relationship = 'Mother';
                        }
                        else if (data[i].relationship == 3) {
                            relationship = 'Brother';
                        }
                        else if (data[i].relationship == 4) {
                            relationship = 'Sister';
                        }
                        else if (data[i].relationship == 5) {
                            relationship = 'Paternal GrandFather';
                        }
                        else if (data[i].relationship == 6) {
                            relationship = 'Paternal GrandMother';
                        }
                        else if (data[i].relationship == 7) {
                            relationship = 'Maternal GrandFather';
                        }
                        else if (data[i].relationship == 8) {
                            relationship = 'Maternal GrandMother';
                        }
                        else if (data[i].relationship == 9) {
                            relationship = 'Both Parents';
                        }
                        else if (data[i].relationship == 10) {
                            relationship = 'All Family number';
                        }
                        else {
                            relationship = '';
                        }
                        if (data[i].disease == 1) {
                            disease = 'CVA';
                        }
                        else if (data[i].disease == 2) {
                            disease = 'Thyroid';
                        }
                        else if (data[i].disease == 3) {
                            disease = 'Hypertension';
                        }
                        else if (data[i].disease == 4) {
                            disease = 'Diabetes';
                        }
                        else if (data[i].disease == 5) {
                            disease = 'Cardiac Diseases';
                        }
                        else if (data[i].disease == 6) {
                            disease = 'Cancer';
                        }
                        else if (data[i].disease == 7) {
                            disease = 'Renal Diseases';
                        }
                        else {
                            disease = '';
                        }
                        if (data[i].no_of_years == null || data[i].no_of_years == "") noofyear = "-";
                        else noofyear = data[i].no_of_years;
                        if (data[i].name == null || data[i].name == "") notesfamily = '-';
                        else notesfamily = data[i].name;
                        tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn addicon-btn btn-sm mr20" onclick="familyedit(' + data[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" onclick="familydelete(' + data[i].patient_family_history_id + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
                    }
                    $('#tbl_family_body').html(tr);
                    $('#Ftxtname').val('');
                    $('#FSelrelationship').val(0);
                    $('#FSeldisease').val(0);
                    $('#Ftxtyears').val('');
                }
            }
            else {
                console.log(data);
            }
        }
    });
});

//summary patient details visit_report start


function patient_summary_visit_report(visitReportId) {
    debugger;
    var MedicinePrescriptiondate = {
        visit_report_id: visitReportId,
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Summary_details',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(MedicinePrescriptiondate),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 2) {
                        console.log(data);
                        debugger;
                        var div = "", divtr = '';
                        var j = 1;
                        if (data.Table20.length > 0) {
                        }
                        div = div + '<div class="col-md-12"><h5><b>Doctor Name : ' + data.Table24[0].doctor_name + ' </b></h5></div>';

                        // vitals section
                        if (data.Table.length > 0 && ((data.Table[0].pulse_rate != null && data.Table[0].pulse_rate != '') || (data.Table[0].spo2 != null && data.Table[0].spo2 != '') || (data.Table[0].temperature != null && data.Table[0].temperature != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }
                        else if (data.Table17.length > 0 && ((data.Table17[0].weight != null && data.Table17[0].weight != '') || (data.Table17[0].patient_height != null && data.Table17[0].patient_height != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }
                        else if (data.Table1.length > 0 && (data.Table1[0].patient_bp_max != null && data.Table1[0].patient_bp_max != '')) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }

                        if (data.Table17.length > 0) {
                            if (data.Table17[0].weight != null && data.Table17[0].weight != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Weight</label> : <span>' + data.Table17[0].weight + ' Kg </span></div>';
                            }
                            if (data.Table17[0].patient_height != null && data.Table17[0].patient_height != '') {
                                //var hieghtdb = parseInt(data.Table17[0].patient_height * 12) + parseInt(data.Table17[0].patient_height_metric);
                                ////var hieghtout = Math.round(hieghtdb * 2.54);
                                //var hieghtout = hieghtdb * 2.54;
                                var hieghtout = (data.Table17[0].patient_height * 30.48) + (data.Table17[0].patient_height_metric * 2.54);
                                hieghtout = hieghtout.toFixed(1);

                                $('#hieght').html(hieghtout);
                                var hieght = hieghtout;

                                div = div + '<div class="col-md-4"><label class="control-label">Height</label> : <span>' + hieght + ' cm </span></div>';
                            }
                        }

                        if (data.Table1.length > 0) {
                            if (data.Table1[0].patient_bp_max != null && data.Table1[0].patient_bp_max != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Sys/Dia</label> : <span>' + data.Table1[0].patient_bp_max + '</span>/<span>' + data.Table1[0].patient_bp_min + '</span></div>';
                            }
                        }

                        if (data.Table.length > 0) {
                            if (data.Table[0].pulse_rate != null && data.Table[0].pulse_rate != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Pulse Rate</label> : <span>' + data.Table[0].pulse_rate + '</span></div>';
                            }
                            if (data.Table[0].spo2 != null && data.Table[0].spo2 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SpO2</label> : <span>' + data.Table[0].spo2 + '</span></div>';
                            }
                            if (data.Table[0].temperature != null && data.Table[0].temperature != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Temperature</label> : <span>' + data.Table[0].temperature + '</span></div>';
                            }
                        }

                        if (data.Table.length > 0 && data.Table[0].observation_primary != null) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else if (data.Table17.length > 0 && data.Table17.length > 0) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else if (data.Table1.length > 0 && data.Table1[0].patient_bp_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else {
                        }

                        if (data.Table24.length > 0) {
                            if (data.Table24[0].diagnosis != null && data.Table24[0].diagnosis != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Diagnosis</label> : <span>' + data.Table24[0].diagnosis + ' </span></div>';
                            }
                            if (data.Table24[0].notes != null && data.Table24[0].notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Notes</label> : <span>' + data.Table24[0].notes + ' </span></div>';
                            }
                            if (data.Table24[0].investigation != null && data.Table24[0].investigation != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Investigation</label> : <span>' + data.Table24[0].investigation + ' </span></div>';
                            }
                            if (data.Table24[0].observation != null && data.Table24[0].observation != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Examination</label> : <span>' + data.Table24[0].observation + ' </span></div>';
                            }
                            if (data.Table24[0].treatment_procedure != null && data.Table24[0].treatment_procedure != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Treatment Procedure</label> : <span>' + data.Table24[0].treatment_procedure + ' </span></div>';
                            }
                            if (data.Table24[0].instruction != null && data.Table24[0].instruction != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Notes</label> : <span>' + data.Table24[0].instruction + ' </span></div>';
                            }
                            if (data.Table24[0].xray_findings != null && data.Table24[0].xray_findings != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Examination Findings</label> : <span>' + data.Table24[0].xray_findings + ' </span></div>';
                            }
                            if (data.Table24[0].advice != null && data.Table24[0].advice != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Advice</label> : <span>' + data.Table24[0].advice + ' </span></div>';
                            }
                            if (data.Table24[0].counselling != null && data.Table24[0].counselling != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Counselling</label> : <span>' + data.Table24[0].counselling + ' </span></div>';
                            }
                            if (data.Table24[0].xray_findings_new != null && data.Table24[0].xray_findings_new != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Xray Finding</label> : <span>' + data.Table24[0].xray_findings_new + ' </span></div>';
                            }
                            if (data.Table24[0].lab_findings != null && data.Table24[0].lab_findings != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Lab Findings</label> : <span>' + data.Table24[0].lab_findings + ' </span></div>';
                            }
                            if (data.Table24[0].review_notes != null && data.Table24[0].review_notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Review Notes</label> : <span>' + data.Table24[0].review_notes + ' </span></div>';
                            }
                        }

                        if (data.Table.length > 0) {
                            if (data.Table[0].current_complaints != null && data.Table[0].current_complaints != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Complaints</label> : <span>' + data.Table[0].current_complaints + '</span></div>';
                            }
                            if (data.Table[0].note != null && data.Table[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Test Requested </label> : <span>' + ((data.Table[0].note != null && data.Table[0].note != "") ? (data.Table[0].note + " - " + data.Table24[0].test_request) : data.Table[0].note) + '</span></div>';
                            }

                            if (data.Table[0].hypoglycemia_episodes != null && data.Table[0].hypoglycemia_episodes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Hypoglycemic Episodes</label> : <span>' + data.Table[0].hypoglycemia_episodes + '</span></div>';
                            }
                            if (data.Table28[0].vas != null && data.Table28[0].vas != '') {
                                if (data.Table28[0].vas == '0') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> No Pain</span></div>';
                                }
                                else if (data.Table28[0].vas == '1' || data.Table28[0].vas == '2' || data.Table28[0].vas == '3') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Mild</span></div>';
                                }
                                else if (data.Table28[0].vas == '4' || data.Table28[0].vas == '5' || data.Table28[0].vas == '6') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Moderate </span></div>';
                                }
                                else if (data.Table28[0].vas == '7' || data.Table28[0].vas == '8' || data.Table28[0].vas == '9') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Severe</span></div>';
                                }
                                if (data.Table28[0].vas == '10') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Worst Pain </span></div>';
                                }
                                if (data.Table28[0].vasduration != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Vas Duration</b></h5></label> : <span>' + data.Table28[0].vasduration + '</span></div>';
                                }

                                if (data.Table28[0].vaslocation != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Vas Location</b></h5></label> : <span> ' + data.Table28[0].vasduration + ' </span></div>';
                                }

                                if (data.Table28[0].followup != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Follow Up/Admission Plan</b></h5></label> : <span> ' + data.Table28[0].followup + ' </span></div>';
                                }
                                if (data.Table28[0].vaspaincharacter != null) {
                                    var paincharacter = data.Table28[0].vaspaincharacter;

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

                                        var paincharactersplit = paincharacter.split(',');
                                        var paincharacter_disp = [];
                                        for (i = 0; i < paincharactersplit.length; i++) {

                                            if (paincharactersplit[i] == 0) {
                                                var paincharacter_view = "Dull"
                                            }
                                            else if (paincharactersplit[i] == 1) {
                                                var paincharacter_view = "Aching"
                                            }
                                            else if (paincharactersplit[i] == 2) {
                                                var paincharacter_view = "Sharp"
                                            }
                                            else if (paincharactersplit[i] == 3) {
                                                var paincharacter_view = "Stabbing"
                                            }
                                            else if (paincharactersplit[i] == 4) {
                                                var paincharacter_view = "Shooting"
                                            }
                                            else if (paincharactersplit[i] == 5) {
                                                var paincharacter_view = "Burning"
                                            }
                                            else if (paincharactersplit[i] == 6) {
                                                var paincharacter_view = "Referred/Radiant Plain"
                                            }
                                            paincharacter_disp.push(paincharacter_view)
                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Pain Character</b></h5></label> : <span> ' + paincharacter_disp + ' </span></div>';
                                }

                                if (data.Table28[0].vasfullrisk != null) {
                                    var frsfa = data.Table28[0].vasfullrisk;
                                    var frsfa_disp = [];
                                    if (frsfa != null && frsfa != "") {

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

                                        for (i = 0; i < frsfasplit.length; i++) {
                                            if (frsfasplit[i] == 0) {
                                                var frsfa_view = "No risk"
                                            }
                                            else if (frsfasplit[i] == 1) {
                                                var frsfa_view = "Age More than 65 years"
                                            }
                                            else if (frsfasplit[i] == 2) {
                                                var frsfa_view = "History of fall in last 3 Months"
                                            }
                                            else if (frsfasplit[i] == 3) {
                                                var frsfa_view = "Walks with assistance"
                                            }
                                            else if (frsfasplit[i] == 4) {
                                                var frsfa_view = "Any Neurological Problem"
                                            }

                                            frsfa_disp.push(frsfa_view)


                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Full Risk Screening for Adults</b></h5></label> : <span> ' + frsfa_disp + ' </span></div>';
                                }

                            }

                            if (data.Table[0].glycemic_variability != null && data.Table[0].glycemic_variability != '') {
                                var glycemic_variability = data.Table[0].glycemic_variability;
                                if (glycemic_variability == 1) {
                                    glycemic_variability = "Present";
                                }
                                else {
                                    glycemic_variability = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Glycemic Variability</label> : <span>' + glycemic_variability + '</span></div>';
                            }
                            if (data.Table[0].cvs != null && data.Table[0].cvs != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CVS</label> : <span>' + data.Table[0].cvs + '</span></div>';
                            }
                            if (data.Table[0].ABS != null && data.Table[0].ABS != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ABD</label> : <span>' + data.Table[0].ABS + '</span></div>';
                            }
                            if (data.Table[0].rs != null && data.Table[0].rs != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">RS</label> : <span>' + data.Table[0].rs + '</span></div>';
                            }
                            if (data.Table[0].CNS != null && data.Table[0].CNS != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CNS</label> : <span>' + data.Table[0].CNS + '</span></div>';
                            }
                            if (data.Table[0].heart_sound != null && data.Table[0].heart_sound != '') {
                                var heart_sound = data.Table[0].heart_sound;
                                if (heart_sound == 1) {
                                    heart_sound = "True";
                                }
                                else {
                                    heart_sound = "False";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Abnormal Heart Sound</label> : <span>' + heart_sound + '</span></div>';
                            }
                            if (data.Table[0].murmurs != null && data.Table[0].murmurs != '') {
                                var murmurs = data.Table[0].murmurs;
                                if (murmurs == 1) {
                                    murmurs = "Present";
                                }
                                else {
                                    murmurs = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Murmurs</label> : <span>' + murmurs + '</span></div>';
                            }
                            if (data.Table[0].reduce_air_entry != null && data.Table[0].reduce_air_entry != '') {
                                var reduce_air_entry = data.Table[0].reduce_air_entry;
                                if (reduce_air_entry == 1) {
                                    reduce_air_entry = "Present";
                                }
                                else {
                                    reduce_air_entry = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Reduced Air Entry</label> : <span>' + reduce_air_entry + '</span></div>';
                            }
                            if (data.Table[0].crackles != null && data.Table[0].crackles != '') {
                                var crackles = data.Table[0].crackles;
                                if (crackles == 1) {
                                    crackles = "Present";
                                }
                                else {
                                    crackles = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Crackles</label> : <span>' + crackles + '</span></div>';
                            }
                            if (data.Table[0].bowel_sounds != null && data.Table[0].bowel_sounds != '') {
                                var bowel_sounds = data.Table[0].bowel_sounds;
                                if (bowel_sounds == 1) {
                                    bowel_sounds = "Present";
                                }
                                else {
                                    bowel_sounds = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Abnormal Bowel Sounds</label> : <span>' + bowel_sounds + '</span></div>';
                            }
                            if (data.Table[0].organomeglay != null && data.Table[0].organomeglay != '') {
                                var organomeglay = data.Table[0].organomeglay;
                                if (organomeglay == 1) {
                                    organomeglay = "Present";
                                }
                                else {
                                    organomeglay = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Organomeglay</label> : <span>' + organomeglay + '</span></div>';
                            }
                            if (data.Table[0].tremors_weakness != null && data.Table[0].tremors_weakness != '') {
                                var tremors_weakness = data.Table[0].tremors_weakness;
                                if (tremors_weakness == 1) {
                                    tremors_weakness = "Present";
                                }
                                else {
                                    tremors_weakness = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Tremors Weakness</label> : <span>' + tremors_weakness + '</span></div>';
                            }
                            if (data.Table[0].cognitive_imparement != null && data.Table[0].cognitive_imparement != '') {
                                var cognitive_imparement = data.Table[0].cognitive_imparement;
                                if (cognitive_imparement == 1) {
                                    cognitive_imparement = "Present";
                                }
                                else {
                                    cognitive_imparement = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Cognitive Imparement</label> : <span>' + cognitive_imparement + '</span></div>';
                            }
                        }

                        //dental
                        if (data.Table28.length > 0 && (data.Table28[0].dental_procedure_done != null || data.Table28[0].dental_procedure_remaining != null || data.Table28[0].dental_type != null || data.Table28[0].dental_hard_tissue != null || data.Table28[0].dental_soft_tissue != null)) {
                            div = div + '<div class="col-md-12"><h5><b>Dental</h5></b></div>';
                        }
                        if (data.Table28.length > 0) {
                            if (data.Table28[0].dental_type != null && data.Table28[0].dental_type != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Type of Dental Appointment</label> : <span>' + (data.Table28[0].dental_type == 1 ? "Cosmetic" : data.Table28[0].dental_type == 2 ? "Dental" : "Surgical") + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_done != null && data.Table28[0].dental_procedure_done != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Done</label> : <span>' + data.Table28[0].dental_procedure_done + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_remaining != null && data.Table28[0].dental_procedure_remaining != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Remaining</label> : <span>' + data.Table28[0].dental_procedure_remaining + '</span></div>';
                            }
                            if (data.Table28[0].dental_hard_tissue != null && data.Table28[0].dental_hard_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Hard Tissue</label> : <span>' + data.Table28[0].dental_hard_tissue + '</span></div>';
                            }
                            if (data.Table28[0].dental_soft_tissue != null && data.Table28[0].dental_soft_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Soft Tissue</label> : <span>' + data.Table28[0].dental_soft_tissue + '</span></div>';
                            }
                        }
                        if (data.Table2.length > 0 && data.Table2[0].glycemic_parameters_basic_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else if (data.Table3.length > 0 && data.Table3[0].patient_hbac_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else if (data.Table4.length > 0 && data.Table4[0].patient_blood_sugar_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else {

                        }
                        if (data.Table2.length > 0) {
                            if (data.Table2[0].fasting_insulin != null && data.Table2[0].fasting_insulin != '') {
                                var fasting_inslin_unit = 'mlU/L';
                                if (data.Table2[0].fasting_inslin_unit == 2) {
                                    fasting_inslin_unit = 'pmol/L'
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Fasting Insulin</label> : <span>' + data.Table2[0].fasting_insulin + ' ' + fasting_inslin_unit + '</span></div>';
                            }
                            if (data.Table2[0].hemoglobin != null && data.Table2[0].hemoglobin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">HB</label> : <span>' + data.Table2[0].hemoglobin + ' gms</span></div>';
                            }
                            if (data.Table2[0].note != null && data.Table2[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Glycemic Notes</label> : <span>' + data.Table2[0].note + '</span></div>';
                            }
                            if (data.Table2[0].WBC != null && data.Table2[0].WBC != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">WBC</label> : <span>' + data.Table2[0].WBC + ' cells per cubic millimeter</span></div>';
                            }
                            if (data.Table2[0].platelet != null && data.Table2[0].platelet != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Platelet</label> : <span>' + data.Table2[0].platelet + ' per microliter</span></div>';
                            }
                            if (data.Table2[0].se_ketones != null && data.Table2[0].se_ketones != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Se_ketones</label> : <span>' + data.Table2[0].se_ketones + ' mmol/L</span></div>';
                            }
                        }
                        if (data.Table3.length > 0) {
                            if (data.Table3[0].patient_hbac_record_value != null && data.Table3[0].patient_hbac_record_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">HBA1C</label> : <span>' + data.Table3[0].patient_hbac_record_value + ' %</span></div>';
                            }
                        }
                        if (data.Table4.length > 0) {
                            for (var i = 0; i < data.Table4.length; i++) {
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 1) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Fasting blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 2) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Postprandial blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 3) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Random blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 4) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Before Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 5) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">After Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 6) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Before Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 7) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">After Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 8) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">3 Am BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                            }
                        }
                        //want to write code
                        if (data.Table5.length > 0) {

                        }

                        if (data.Table6.length > 0) {
                            if (data.Table6[0].renal_function_test_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>RENAL</b></h5></div>';
                            }
                        }
                        else {
                            if (data.Table7.length > 0) {
                                if ((data.Table7[0].ACR != null && data.Table7[0].ACR != '') || (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '')) {
                                    div = div + '<div class="col-md-12"><h5><b>RENAL</b></h5></div>';
                                }
                            }
                        }
                        if (data.Table6.length > 0) {
                            if (data.Table6[0].Urea != null && data.Table6[0].Urea != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].urea_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Urea</label> : <span>' + data.Table6[0].Urea + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].creatinine != null && data.Table6[0].creatinine != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].Creatinine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Creatinine</label> : <span>' + data.Table6[0].creatinine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].egfr_value != null && data.Table6[0].egfr_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">EGFR ( Calculated )</label> : <span>' + data.Table6[0].egfr_value + ' ml/min/1.73m2</span></div>';
                            }
                            if (data.Table6[0].Sodium != null && data.Table6[0].Sodium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].sodium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Sodium</label> : <span>' + data.Table6[0].Sodium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Potassium != null && data.Table6[0].Potassium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].potassium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Potassium</label> : <span>' + data.Table6[0].Potassium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Chlorine != null && data.Table6[0].Chlorine != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].chlorine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Chlorine</label> : <span>' + data.Table6[0].Chlorine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].BiCarbonate != null && data.Table6[0].BiCarbonate != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Bicarbonate_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">BiCarbonate</label> : <span>' + data.Table6[0].BiCarbonate + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_calcium != null && data.Table6[0].serium_calcium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Calcium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Calcium</label> : <span>' + data.Table6[0].serium_calcium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_phosphorous != null && data.Table6[0].serium_phosphorous != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Phosphorus_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Phosphorous</label> : <span>' + data.Table6[0].serium_phosphorous + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_magnesium != null && data.Table6[0].serium_magnesium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Magnesium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Magnesium</label> : <span>' + data.Table6[0].serium_magnesium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].note != null && data.Table6[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Renal Notes</label> : <span>' + data.Table6[0].note + ' </span></div>';
                            }
                            if (data.Table6[0].ASD != null && data.Table6[0].ASD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ASD</label> : <span>' + data.Table6[0].ASD + ' </span></div>';
                            }
                            if (data.Table6[0].VSD != null && data.Table6[0].VSD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">VSD</label> : <span>' + data.Table6[0].VSD + ' </span></div>';
                            }
                            if (data.Table6[0].C_value != null && data.Table6[0].C_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Valve Notes</label> : <span>' + data.Table6[0].C_value + ' </span></div>';
                            }
                            if (data.Table6[0].fraction != null && data.Table6[0].fraction != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Fraction</label> : <span>' + data.Table6[0].fraction + ' </span></div>';
                            }
                            if (data.Table6[0].mitral_value != null && data.Table6[0].mitral_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Mitral Value</label> : <span>' + data.Table6[0].mitral_value + ' </span></div>';
                            }
                            if (data.Table6[0].lotic_value != null && data.Table6[0].lotic_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Aortic Valve</label> : <span>' + data.Table6[0].lotic_value + ' </span></div>';
                            }
                            if (data.Table6[0].tricuspid != null && data.Table6[0].tricuspid != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Tricuspid</label> : <span>' + data.Table6[0].tricuspid + ' </span></div>';
                            }
                            if (data.Table6[0].pulmonary != null && data.Table6[0].pulmonary != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Pulmonary</label> : <span>' + data.Table6[0].pulmonary + ' </span></div>';
                            }
                        }

                        if (data.Table7.length > 0) {
                            if (data.Table7[0].ACR != null && data.Table7[0].ACR != '') {
                                var ACR = '';
                                if (data.Table7[0].ACR == 1) {
                                    ACR = '< 30 mg/dL - Normal';
                                }
                                if (data.Table7[0].ACR == 2) {
                                    ACR = '30 to 300 mg/dL - Microalbuminuria';
                                }
                                if (data.Table7[0].ACR == 3) {
                                    ACR = '  > 300 mg/dL - Proteinuria';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">ACR</label> : <span>' + ACR + '</span></div>';
                            }
                            if (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '') {
                                var nephropathy = '';
                                if (data.Table7[0].nephropathy == 1) {
                                    nephropathy = 'Yes';
                                }
                                if (data.Table7[0].nephropathy == 2) {
                                    nephropathy = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Nephropathy</label> : <span>' + nephropathy + '</span></div>';
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].cholestrol_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>CHOLESTEROL</b></h5></div>';
                            }
                        }
                        else {
                            if (data.Table9.length > 0) {
                                if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                    div = div + '<div class="col-md-12"><h5><b>CHOLESTEROL</b></h5></div>';
                                }
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].Total_Cholestrol != null && data.Table8[0].Total_Cholestrol != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Total_cholestrol_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Total Cholesterol</label> : <span>' + data.Table8[0].Total_Cholestrol + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].LDL != null && data.Table8[0].LDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].LDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">LDL</label> : <span>' + data.Table8[0].LDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].HDL != null && data.Table8[0].HDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].HDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">HDL</label> : <span>' + data.Table8[0].HDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].VLDL != null && data.Table8[0].VLDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].VLDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">VLDL</label> : <span>' + data.Table8[0].VLDL + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].Triglycerides != null && data.Table8[0].Triglycerides != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Triglycerides_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Triglycerides</label> : <span>' + data.Table8[0].Triglycerides + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].T_cholestrol_Hdl_ratio != null && data.Table8[0].T_cholestrol_Hdl_ratio != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Total Cholesterol : HDL Ratio</label> : <span>' + data.Table8[0].T_cholestrol_Hdl_ratio + ' </span></div>';
                            }
                            if (data.Table8[0].note != null && data.Table8[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Cholestrol Notes</label> : <span>' + data.Table8[0].note + ' </span></div>';
                            }
                        }
                        if (data.Table9.length > 0) {
                            if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                var unit = '';
                                if (data.Table9[0].dyslipedemia == 1) {
                                    unit = 'yes';
                                }
                                else {
                                    unit = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Dyslipidemia</label> : <span>' + unit + ' </span></div>';
                            }
                        }
                        debugger;
                        if (data.Table10.length > 0 && ((data.Table10[0].last_observation_date != null && data.Table10[0].last_observation_date != '') || (data.Table10[0].next_suggested_appointment != null && data.Table10[0].next_suggested_appointment != '') || (data.Table10[0].note != null && data.Table10[0].note != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>OPTHAL</b></h5></div>';
                        }
                        else if (data.Table11.length > 0 && data.Table11[0].patient_level_flag_id != null && ((data.Table11[0].pdr != null && data.Table11[0].pdr != '') || (data.Table11[0].npdr != null && data.Table11[0].npdr != '') || (data.Table11[0].viterous_hemorage != null && data.Table11[0].viterous_hemorage != '') || (data.Table11[0].retinal_detachment != null && data.Table11[0].retinal_detachment != '') || (data.Table11[0].retinopathy != null && data.Table11[0].retinopathy != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>OPTHAL</b></h5></div>';
                        }
                        if (data.Table10.length > 0) {

                            if (data.Table10[0].last_observation_date != null && data.Table10[0].last_observation_date != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Last Observation Date</label> : <span>' + data.Table10[0].last_observation_date + ' </span></div>';
                            }
                            if (data.Table10[0].next_suggested_appointment != null && data.Table10[0].next_suggested_appointment != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Next Suggested Opthal Appointment</label> : <span>' + data.Table10[0].next_suggested_appointment + ' </span></div>';
                            }
                            if (data.Table10[0].note != null && data.Table10[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Opthal Notes</label> : <span>' + data.Table10[0].note + ' </span></div>';
                            }
                        }
                        if (data.Table11.length > 0) {
                            if (data.Table11[0].pdr != null && data.Table11[0].pdr != '') {
                                var val = '';
                                if (data.Table11[0].pdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].pdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].pdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].pdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">PDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].npdr != null && data.Table11[0].npdr != '') {
                                var val = '';
                                if (data.Table11[0].npdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].npdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].npdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].npdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">NPDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].viterous_hemorage != null && data.Table11[0].viterous_hemorage != '') {
                                var val = '';
                                if (data.Table11[0].viterous_hemorage == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].viterous_hemorage == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Vitreous Hemorrhage</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinal_detachment != null && data.Table11[0].retinal_detachment != '') {
                                var val = '';
                                if (data.Table11[0].retinal_detachment == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinal_detachment == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Retinal Detachment</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinopathy != null && data.Table11[0].retinopathy != '') {
                                var val = '';
                                if (data.Table11[0].retinopathy == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinopathy == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Retinopathy</label> : <span>' + val + ' </span></div>';
                            }
                        }
                        if (data.Table19.length > 0 && data.Table19[0].patient_level_cardiac_id != null && (data.Table19[0].L_LAD != null || data.Table19[0].L_LAD_type != null || data.Table19[0].L_LCX != null ||
                            data.Table19[0].L_LCX_type != null || data.Table19[0].L_RCA != null || data.Table19[0].L_RCA_type != null || data.Table19[0].R_LAD != null || data.Table19[0].R_LAD_type != null
                            || data.Table19[0].R_LCX != null || data.Table19[0].R_LCX_type != null || data.Table19[0].R_RCA != null || data.Table19[0].R_RCA_type != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else if (data.Table12.length > 0 && data.Table12[0].cardiac_profile_id != null && (data.Table12[0].ECG != null || data.Table12[0].ECHO != null
                            || (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != 0) || (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != 0) || data.Table12[0].TMT_test != null || data.Table12[0].note != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else { }
                        if (data.Table19.length > 0) {
                            if (data.Table19[0].L_LAD != null && data.Table19[0].L_LAD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LCA</label> : <span>' + data.Table19[0].L_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LAD_type != null && data.Table19[0].L_LAD_type != '' && data.Table19[0].L_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LAD_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">LCA Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].L_LCX != null && data.Table19[0].L_LCX != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LCX</label> : <span>' + data.Table19[0].L_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LCX_type != null && data.Table19[0].L_LCX_type != '' && data.Table19[0].L_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LCX_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">LCX Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].L_RCA != null && data.Table19[0].L_RCA != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LAD</label> : <span>' + data.Table19[0].L_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].L_RCA_type != null && data.Table19[0].L_RCA_type != '' && data.Table19[0].L_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_RCA_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">LAD Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].R_LAD != null && data.Table19[0].R_LAD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">RCA</label> : <span>' + data.Table19[0].R_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LAD_type != null && data.Table19[0].R_LAD_type != '' && data.Table19[0].R_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LAD_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">RCA Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].R_LCX != null && data.Table19[0].R_LCX != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">R-PLB</label> : <span>' + data.Table19[0].R_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LCX_type != null && data.Table19[0].R_LCX_type != '' && data.Table19[0].R_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LCX_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">R-PLB Type</label> : <span>' + type + ' </span></div>';
                            }
                            if (data.Table19[0].R_RCA != null && data.Table19[0].R_RCA != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">R-PDA</label> : <span>' + data.Table19[0].R_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].R_RCA_type != null && data.Table19[0].R_RCA_type != '' && data.Table19[0].R_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_RCA_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">R-PDA Type</label> : <span>' + type + ' </span></div>';
                            }
                        }

                        if (data.Table12.length > 0) {
                            if (data.Table12[0].ECG != null && data.Table12[0].ECG != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ECG</label> : <span>' + data.Table12[0].ECG + ' </span></div>';
                            }
                            if (data.Table12[0].ECHO != null && data.Table12[0].ECHO != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ECHO</label> : <span>' + data.Table12[0].ECHO + ' </span></div>';
                            }
                            if (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != '') {
                                if (data.Table12[0].ecg_abnormal == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">ECG Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != '') {
                                if (data.Table12[0].echo_abnormal == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">ECHO Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].TMT_test != null && data.Table12[0].TMT_test != '') {
                                if (data.Table12[0].TMT_test == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">TMT</label> : <span>Positive</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-4"><label class="control-label">TMT</label> : <span>Negative</span></div>';
                                }
                            }
                            if (data.Table12[0].note != null && data.Table12[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Cardiac Notes</label> : <span>' + data.Table12[0].note + '</span></div>';
                            }
                        }
                        if (data.Table13.length > 0 && (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '')) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else if (data.Table14.length > 0 && ((data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') || (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') || (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') || (data.Table14[0].note != null && data.Table14[0].note != ''))) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else {

                        }
                        if (data.Table13.length > 0) {
                            if (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '') {
                                if (data.Table13[0].autonomic_neuropathy == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">Autonomic Neuropathy</label> : <span>Yes</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-4"><label class="control-label">Autonomic Neuropathy</label> : <span>No</span></div>';
                                }
                            }
                        }
                        if (data.Table14.length > 0) {
                            if (data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') {
                                var val = '';
                                if (data.Table14[0].peripharal_neuhropathy == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Peripheral Neuhropathy</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') {
                                var val = '';
                                if (data.Table14[0].AB_index == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].AB_index == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].AB_index == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].AB_index == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">AB Index</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Doppler</label> : <span>' + data.Table14[0].doppler_note + ' </span></div>';
                            }
                            if (data.Table14[0].note != null && data.Table14[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Neuropthy Note</label> : <span>' + data.Table14[0].note + ' </span></div>';
                            }
                        }
                        if (data.Table15.length > 0) {
                            if (data.Table15[0].thyroid_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>THYROID</b></h5></div>';
                            }
                        }
                        if (data.Table15.length > 0) {
                            if (data.Table15[0].Free_T3 != null && data.Table15[0].Free_T3 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Free T3</label> : <span>' + data.Table15[0].Free_T3 + ' Pg/dl </span></div>';
                            }
                            if (data.Table15[0].Free_T4 != null && data.Table15[0].Free_T4 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Free T4</label> : <span>' + data.Table15[0].Free_T4 + ' ng/dl </span></div>';
                            }
                            if (data.Table15[0].TSH != null && data.Table15[0].TSH != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">TSH</label> : <span>' + data.Table15[0].TSH + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T3 != null && data.Table15[0].T3 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T3</label> : <span>' + data.Table15[0].T3 + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T4 != null && data.Table15[0].T4 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T4</label> : <span>' + data.Table15[0].T4 + ' mlU/m </span></div>';
                            }

                            if (data.Table15[0].note != null && data.Table15[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Thyroid Notes</label> : <span>' + data.Table15[0].note + '</span></div>';
                            }
                        }

                        if (data.Table16.length > 0) {
                            if (data.Table16[0].sheet_chest_xray_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>ULTRASOUND / X-RAY</b></h5></div>';
                            }
                        }
                        if (data.Table16.length > 0) {
                            if (data.Table16[0].notes != null && data.Table16[0].notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Chest X-Ray Notes</label> : <span>' + data.Table16[0].notes + ' Pg/dl </span></div>';
                            }
                            if (data.Table16[0].USNotes != null && data.Table16[0].USNotes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Ultrasound Notes</label> : <span>' + data.Table16[0].USNotes + ' ng/dl </span></div>';
                            }
                            if (data.Table16[0].fatty_lives != null && data.Table16[0].fatty_lives != '') {
                                var val = '';
                                if (data.Table16[0].fatty_lives == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].fatty_lives == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Fatty Liver</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].GS_Calculus != null && data.Table16[0].GS_Calculus != '') {
                                var val = '';
                                if (data.Table16[0].GS_Calculus == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].GS_Calculus == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">GB Calculas</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].cts_notes != null && data.Table16[0].cts_notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CT scan Notes</label> : <span>' + data.Table16[0].cts_notes + ' </span></div>';
                            }
                        }
                        if (data.Table18.length > 0) {
                            //$('#moreinfovisit_date').html(data.Table18[0].c_date);
                            $('#Hpatientid').val(data.Table18[0].patientid)
                            $('#Hvisit_reportid').val(data.Table18[0].visit_reportid)
                        }


                        if (data.Table26.length > 0) {
                            if (data.Table26[0].liver_function_test_id != null && (data.Table26[0].serum_bilirubin_total != null || data.Table26[0].serum_bilirubin_direct != null
                                || data.Table26[0].bilirubin_indirect != null || data.Table26[0].serum_protein_total != null || data.Table26[0].serum_protein_albumin != null || data.Table26[0].serumproteinglibulin != null
                                || data.Table26[0].SGOT != null || data.Table26[0].SGPT != null || data.Table26[0].serum_alkaline_phosphatase != null || data.Table26[0].gamma_glutamyl_transpeptidase != null || data.Table26[0].serum_magnesium != null)) {
                                div = div + '<div class="col-md-12"><h5><b>LIVER FUNCTION TEST</b></h5></div>';
                            }
                        }

                        if (data.Table26.length > 0) {
                            if (data.Table26[0].serum_bilirubin_total != null && data.Table26[0].serum_bilirubin_total != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Bilirubin Total</label> : <span>' + data.Table26[0].serum_bilirubin_total + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_bilirubin_direct != null && data.Table26[0].serum_bilirubin_direct != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Bilirubin Direct</label> : <span>' + data.Table26[0].serum_bilirubin_direct + ' mg/dl </span></div>';
                            }

                            if (data.Table26[0].bilirubin_indirect != null && data.Table26[0].bilirubin_indirect != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Bilirubin Indirect</label> : <span>' + data.Table26[0].bilirubin_indirect + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_total != null && data.Table26[0].serum_protein_total != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein -Total</label> : <span>' + data.Table26[0].serum_protein_total + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_albumin != null && data.Table26[0].serum_protein_albumin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein - Albumin</label> : <span>' + data.Table26[0].serum_protein_albumin + ' g/dl</span></div>';
                            }
                            if (data.Table26[0].serumproteinglibulin != null && data.Table26[0].serumproteinglibulin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein - Glibulin</label> : <span>' + data.Table26[0].serumproteinglibulin + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].SGOT != null && data.Table26[0].SGOT != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SGOT (AST)</label> : <span>' + data.Table26[0].SGOT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].SGPT != null && data.Table26[0].SGPT != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SGPT (AST)</label> : <span>' + data.Table26[0].SGPT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_alkaline_phosphatase != null && data.Table26[0].serum_alkaline_phosphatase != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].serum_alkaline_phosphatase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].gamma_glutamyl_transpeptidase != null && data.Table26[0].gamma_glutamyl_transpeptidase != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].gamma_glutamyl_transpeptidase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_magnesium != null && data.Table26[0].serum_magnesium != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Gamma Glutamyl Transpeptidase (GGT)</label> : <span>' + data.Table26[0].serum_magnesium + ' IU/l </span></div>';
                            }

                        }
                        debugger;
                        if (data.Table31.length > 0) { //Exercise Summary
                            var exercisetable = '<>'
                            var tr = '';
                            for (var i = 0; i < data.Table31.length; i++) {

                                var monday = data.Table31[i].monday_flag;
                                var tuesday = data.Table31[i].tuesday_flag;
                                var wednesday = data.Table31[i].wednesday_flag;
                                var thusday = data.Table31[i].thursday_flag;
                                var friday = data.Table31[i].friday_flag;
                                var saturday = data.Table31[i].saturday_flag;
                                var sunday = data.Table31[i].sunday_flag;

                                var SuggestedDays = ''; var suggestedDaysCount = 0;
                                if (monday == 1) {

                                    SuggestedDays = 'Mon';
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (tuesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Tue';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Tue';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (wednesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Wed';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Wed';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (thusday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Thu';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Thu';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (friday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Fri';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Fri';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (saturday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sat';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Sat';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (sunday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sun';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + '  Sun';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                var treatment_description = [];
                                var t = data.Table31[i].treatment.split(",");
                                var j = 0;
                                for (var k = 0; k < t.length; k++) {
                                    if (t[k] == 1) {
                                        treatment_description[j] = "IFT"
                                    }
                                    else if (t[k] == 2) {
                                        treatment_description[j] = "UST"
                                    }
                                    else if (t[k] == 3) {
                                        treatment_description[j] = "CCT"
                                    }
                                    else if (t[k] == 4) {
                                        treatment_description[j] = "WAX"
                                    }
                                    else if (t[k] == 5) {
                                        treatment_description[j] = "ES"
                                    }
                                    else if (t[k] == 6) {
                                        treatment_description[j] = "LASER"
                                    }
                                    else if (t[k] == 7) {
                                        treatment_description[j] = "ICT"
                                    }
                                    else if (t[k] == 8) {
                                        treatment_description[j] = "IPT"
                                    }
                                    else if (t[k] == 9) {
                                        treatment_description[j] = "CPM"
                                    }
                                    else if (t[k] == 10) {
                                        treatment_description[j] = "CPT"
                                    }
                                    else {

                                    }
                                    j++;
                                }
                                var treatment_description_1 = treatment_description.toString();

                                var choose_region_desc = [];
                                if (data.Table31[i].choose_region != null && data.Table31[i].choose_region != "") {
                                    var r = data.Table31[i].choose_region.split(",");
                                    var p = 0;
                                    for (var k = 0; k < r.length; k++) {
                                        choose_region_desc[p] = $("#SelRegion option[value='" + r[k] + "']").text();
                                        //if (r[k] == 1) {
                                        //    choose_region_desc[p] = "SHOULDER REHAB"
                                        //}
                                        //else if (r[k] == 2) {
                                        //    choose_region_desc[p] = "ELBOW REHAB"
                                        //}
                                        //else if (r[k] == 3) {
                                        //    choose_region_desc[p] = "WRIST & HAND REHAB"
                                        //}
                                        //else if (r[k] == 4) {
                                        //    choose_region_desc[p] = "SPINE REHAB"
                                        //}
                                        //else if (r[k] == 5) {
                                        //    choose_region_desc[p] = "PELVIC & CORE REHAB"
                                        //}
                                        //else if (r[k] == 6) {
                                        //    choose_region_desc[p] = "HIP REHAB"
                                        //}
                                        //else if (r[k] == 7) {
                                        //    choose_region_desc[p] = "KNEE REHAB"
                                        //}
                                        //else if (r[k] == 8) {
                                        //    choose_region_desc[p] = "ANKLE & FOOT REHAB"
                                        //}
                                        //else if (r[k] == 9) {
                                        //    choose_region_desc[p] = "LIBERATORY MANEUVER"
                                        //}
                                        //else {

                                        //}
                                        p++;

                                    }
                                }
                                var choose_region_1 = choose_region_desc.toString();


                                tr = tr + "<tr><td>" + choose_region_1 + "</td><td>" + data.Table31[i].op_type + "</td><td>" + data.Table31[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data.Table31[i].days_to_take + "</td><td>" + data.Table31[i].excercise_duration_per_day + "</td><td>" + data.Table31[i].sitting + "</td><td>" + data.Table31[i].instruction + "</td><td>" + treatment_description_1 + "</td></tr>";
                            }
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Region</th><th>Pre/Post OP</th><th>Type of Exercise</th><th>Suggested Days</th><th>Number of Days</th><th>Duration</th><th>Sitting</th><th>Exercise Instruction</th><th>Treatment</th></tr></thead>';

                            $('#Exercise-table_' + data.Table18[0].visit_report_id).html('');
                            $('#Exercise-table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#exercise_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //diet summary
                        if (data.Table33.length > 0) {
                            var tr = "";
                            for (var i = 0; i < data.Table33.length; i++) {
                                j++;
                                tr = tr + "<tr><td>" + data.Table33[i].time + "</td>";
                                tr = tr + " <td>" + data.Table33[i].type_of_food + "</td>";
                                tr = tr + " <td>" + data.Table33[i].no_of_servings + ' Per day' + "</td>";
                                tr = tr + " <td>" + data.Table33[i].instructions + "</td>";
                                tr = tr + "</tr>";

                            }
                            var dietplan = '<div><p>Plan Duration: <span>' + ((data.Table33[0].diet_goal_duration == null) ? '-' : data.Table33[0].diet_goal_duration + ' days') + '</span></p></div><div><p>Suggested Kcal Intake: <span>' + data.Table33[0].kcal + '</span></p></div>';
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Time</th><th>Food</th><th>Serving</th><th>Instruction</th></tr></thead>';

                            $('#Diet_table_' + data.Table18[0].visit_report_id).html('');
                            $('#Diet_table_' + data.Table18[0].visit_report_id).append(dietplan);
                            $('#Diet_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#diet_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //observed nutrition

                        if (data.Table34.length > 0) {

                            var tr = '';
                            for (var i = 0; i < data.Table34.length; i++) {
                                j++;
                                tr = tr + "<tr><td>" + data.Table34[i].type + "</td><td>" + data.Table34[i].type_name + "</td></tr>";

                            }

                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Type</th><th>Observed Value</th></tr></thead>';

                            $('#observed_nutrition_table_' + data.Table18[0].visit_report_id).html('');
                            $('#observed_nutrition_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#observed_nutrition_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //future services
                        if (data.Table35.length > 0) {

                            var tr = '';
                            for (var i = 0; i < data.Table35.length; i++) {
                                j++;
                                if (data.Table35[i].base_amount_type == 4) {
                                    var date_time = data.Table35[i].service_date + " " + data.Table35[i].service_time + " - " + data.Table35[i].service_end_date + " " + data.Table35[i].service_end_time;
                                    tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data.Table35[i].service_name + '</td><td>' + data.Table35[i].service_code + '</td><td>' + data.Table35[i].quantity + '</td><td>' + date_time + '</td><td>' + ((data.Table35[i].remarks == '') ? '-' : data.Table35[i].remarks) + '</td></tr>'
                                }
                                else {
                                    var date_time = data.Table35[i].service_date + " " + data.Table35[i].service_time;
                                    tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data.Table35[i].service_name + '</td><td>' + data.Table35[i].service_code + '</td><td>' + data.Table35[i].quantity + '</td><td>' + date_time + '</td><td>' + ((data.Table35[i].remarks == '') ? '-' : data.Table35[i].remarks) + '</td></tr>'
                                }

                            }

                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>S.NO</th><th>Service Name</th><th>Service Code</th><th>Quantity</th><th>Date & Time</th><th>Description</th></tr></thead>';

                            $('#future_services_table_' + data.Table18[0].visit_report_id).html('');
                            $('#future_services_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#future_services_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //cbc and urine routine
                        if (data.Table29.length > 0) {
                            if (data.Table29[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>CBC</b></h5></div>';
                            }
                        }

                        if (data.Table29.length > 0) {
                            for (var i = 0; i < data.Table29.length; i++) {
                                if (data.Table29[0].hemoglobin != null && data.Table29[0].hemoglobin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">HEMOGLOBIN</label> : <span>' + data.Table29[0].hemoglobin + " " + ((data.Table29[0].hemoglobin_unit == null || data.Table29[0].hemoglobin_unit == "") ? "" : data.Table29[0].hemoglobin_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].platelet_count != null && data.Table29[0].platelet_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">PLATELET COUNT</label> : <span>' + data.Table29[0].platelet_count + " " + ((data.Table29[0].platelet_count_unit == null || data.Table29[0].platelet_count_unit == "") ? "" : data.Table29[0].platelet_count_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells != null && data.Table29[0].nucleated_red_blood_cells != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NUCLEATED RED BLOOD CELLS</label> : <span>' + data.Table29[0].nucleated_red_blood_cells + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells_percent != null && data.Table29[0].nucleated_red_blood_cells_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NUCLEATED RED BLOOD CELLS %</label> : <span>' + data.Table29[0].nucleated_red_blood_cells_percent + ' </span></div>';
                                }
                                if (data.Table29[0].hematocrit != null && data.Table29[0].hematocrit != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">HEMATOCRIT(PCV)</label> : <span>' + data.Table29[0].hematocrit + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocyte_percent != null && data.Table29[0].lymphocyte_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">LYMPHOCYTE PERCENTAGE</label> : <span>' + data.Table29[0].lymphocyte_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_leucocytes_count != null && data.Table29[0].total_leucocytes_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">TOTAL LEUCOCYTES COUNT</label> : <span>' + data.Table29[0].total_leucocytes_count + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_hemoglobin != null && data.Table29[0].mean_corpuscular_hemoglobin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORPUSCULAR HEMOGLOBIN(MCH)</label> : <span>' + data.Table29[0].mean_corpuscular_hemoglobin + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corp_hemo_conc != null && data.Table29[0].mean_corp_hemo_conc != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORP.HEMO.CONC(MCHC)</label> : <span>' + data.Table29[0].mean_corp_hemo_conc + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_volume != null && data.Table29[0].mean_corpuscular_volume != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORPUSCULAR VOLUME(MCV)</label> : <span>' + data.Table29[0].mean_corpuscular_volume + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes != null && data.Table29[0].monocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MONOCYTES</label> : <span>' + data.Table29[0].monocytes + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils != null && data.Table29[0].neutrophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NEUTROPHILS</label> : <span>' + data.Table29[0].neutrophils + ' </span></div>';
                                }
                                if (data.Table29[0].eosinophils_absolute_count != null && data.Table29[0].eosinophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">EOSINOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].eosinophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils_absolute_count != null && data.Table29[0].basophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">BASOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].basophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocytes_absolute_count != null && data.Table29[0].lymphocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">LYMPHOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].lymphocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes_absolute_count != null && data.Table29[0].monocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MONOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].monocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils_absolute_count != null && data.Table29[0].neutrophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NEUTROPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].neutrophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils != null && data.Table29[0].basophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">BASOPHILS</label> : <span>' + data.Table29[0].basophils + ' </span></div>';
                                }

                                if (data.Table29[0].eosinophils != null && data.Table29[0].eosinophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">EOSINOPHILS</label> : <span>' + data.Table29[0].eosinophils + ' </span></div>';
                                }

                                if (data.Table29[0].immature_granulocytes != null && data.Table29[0].immature_granulocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">IMMATURE GRANULOCYTES(IG)</label> : <span>' + data.Table29[0].immature_granulocytes + ' </span></div>';
                                }
                                if (data.Table29[0].immature_granulocytes_percent != null && data.Table29[0].immature_granulocytes_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">IMMATURE GRANULOCYTE PERCENTAGE(IG%)</label> : <span>' + data.Table29[0].immature_granulocytes_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_rbc != null && data.Table29[0].total_rbc != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">TOTAL RBC</label> : <span>' + data.Table29[0].total_rbc + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width != null && data.Table29[0].redcell_distribution_width != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">RED CELL DISTRIBUTION WIDTH (RDW-CV)</label> : <span>' + data.Table29[0].redcell_distribution_width + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width_sd != null && data.Table29[0].redcell_distribution_width_sd != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">RED CELL DISTRIBUTION WIDTH - SD(RDW-SD)</label> : <span>' + data.Table29[0].redcell_distribution_width_sd + ' </span></div>';
                                }
                            }
                        }

                        if (data.Table30.length > 0) {
                            if (data.Table30[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>Urine Routine</b></h5></div>';
                            }
                        }
                        if (data.Table30.length > 0) {
                            for (var i = 0; i < data.Table30.length; i++) {
                                if (data.Table30[0].specific_gravity != null && data.Table30[0].specific_gravity != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">SPECIFIC GRAVITY</label> : <span>' + data.Table30[0].specific_gravity + " " + ((data.Table30[0].specific_gravity_unit == null || data.Table30[0].specific_gravity_unit == "") ? "" : data.Table30[0].specific_gravity_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_bilirubin != null && data.Table30[0].urinary_bilirubin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY BILIRUBIN</label> : <span>' + data.Table30[0].urinary_bilirubin + " " + ((data.Table30[0].urinary_bilirubin_unit == null || data.Table30[0].urinary_bilirubin_unit == "") ? "" : data.Table30[0].urinary_bilirubin_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urine_blood != null && data.Table30[0].urine_blood != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINE BLOOD</label> : <span>' + data.Table30[0].urine_blood + ' </span></div>';
                                }
                                if (data.Table30[0].urobilinogen != null && data.Table30[0].urobilinogen != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">UROBILINOGEN</label> : <span>' + data.Table30[0].urobilinogen + " " + ((data.Table30[0].urobilinogen_unit == null || data.Table30[0].urobilinogen_unit == "") ? "" : data.Table30[0].urobilinogen_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_glucose != null && data.Table30[0].urinary_glucose != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY GLUCOSE</label> : <span>' + data.Table30[0].urinary_glucose + ' </span></div>';
                                }
                                if (data.Table30[0].urine_ketone != null && data.Table30[0].urine_ketone != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINE KETONE</label> : <span>' + data.Table30[0].urine_ketone + " " + ((data.Table30[0].urine_ketone_unit == null || data.Table30[0].urine_ketone_unit == "") ? "" : data.Table30[0].urine_ketone_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_leucocytes != null && data.Table30[0].urinary_leucocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY LEUCOCYTES</label> : <span>' + data.Table30[0].urinary_leucocytes + ' </span></div>';
                                }
                                if (data.Table30[0].nitrite != null && data.Table30[0].nitrite != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NITRITE</label> : <span>' + data.Table30[0].nitrite + " " + ((data.Table30[0].nitrite_unit == null || data.Table30[0].nitrite_unit == "") ? "" : data.Table30[0].nitrite_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].ph != null && data.Table30[0].ph != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">PH</label> : <span>' + data.Table30[0].ph + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_protein != null && data.Table30[0].urinary_protein != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY PROTEIN</label> : <span>' + data.Table30[0].urinary_protein + ' </span></div>';
                                }
                            }
                        }

                        if (data.Table25.length > 0) {
                            for (var i = 0; i < data.Table25.length; i++) {
                                if (data.Table25[i].parameter_value != null && data.Table25[i].parameter_value != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">' + data.Table25[i].parameter_name + '</label> : <span>' + data.Table25[i].parameter_value + " " + data.Table25[i].unit + '</span></div>';
                                }
                            }
                        }

                        if (data.Table27.length > 0) {
                            if (data.Table27[0].master_labtest_visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>Master Lab Test</b></h5></div>';
                            }
                        }

                        if (data.Table27.length > 0) {
                            for (var i = 0; i < data.Table27.length; i++) {
                                if (data.Table27[0].parameter_name != null && data.Table27[0].parameter_name != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">' + data.Table27[i].parameter_name + '</label> : <span>' + data.Table27[i].parameter_value + '  ' + data.Table27[i].reference_value + ' ' + data.Table27[i].unit + '</span></div>';
                                }
                            }
                        }

                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html('');
                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html(div);

                        if (data.Table21.length > 0) {
                            tr = '';
                            for (var i = 0; i < data.Table21.length; i++) {
                                var session = '';
                                visit_report_id = data.Table21[i].visit_report_id;
                                if (data.Table21[i].evening == 1) {
                                    session = data.Table21[i].morning + ' - ' + data.Table21[i].afternoon + ' - ' + data.Table21[i].evening + ' - ' + data.Table21[i].night;
                                }
                                else {
                                    session = data.Table21[i].morning + ' - ' + data.Table21[i].afternoon + ' - ' + data.Table21[i].night;
                                }
                                var color = '';
                                if (data.Table21[i].priority == 1) {
                                    color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
                                }
                                else if (data.Table21[i].priority == 2) {
                                    color = '<i class=" fa fa-circle" style="color:orange"></i>&nbsp;';
                                }
                                else if (data.Table21[i].priority == 3) {
                                    color = '<i class=" fa fa-circle" style="color:#418bfe"></i>&nbsp;';
                                }
                                else {
                                    color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
                                }
                                var instructions = '';
                                if (data.Table21[i].instructions == '' || data.Table21[i].instructions == null) {
                                    instructions = '';
                                }
                                else {
                                    instructions = data.Table21[i].instructions;
                                }
                                if (data.Table21[i].days_to_take == '' || data.Table21[i].days_to_take == null) {
                                    days_to_take = '';
                                }
                                else if (data.Table21[i].days_to_take == '9999') {
                                    days_to_take = 'Daily';
                                }
                                else {
                                    days_to_take = data.Table21[i].days_to_take;
                                }
                                var generic_name = '';
                                if (data.Table21[i].generic_name == '' || data.Table21[i].generic_name == null) {
                                    generic_name = '';
                                }
                                else {
                                    generic_name = '<span style=font-size:11px;><i>(' + data.Table21[i].generic_name + ')</i></span>';
                                }
                                tr = tr + '<tr><td>' + data.Table21[i].medicine_type + '</td><td style="text-transform:capitalize;">' + color + data.Table21[i].medicine_name + generic_name + '</td><td>' + data.Table21[i].when_to_eat_value + '</td><td>' + data.Table21[i].medicine_frequency + '</td><td>' + days_to_take + '</td><td>' + instructions + '</td><td>' + session + '</td></tr>';
                            }

                            var pdf = '<a href="javascript:void(0);" class="pull-right btn_cpy_prescription" onclick=printPrescription("' + visit_report_id + '")><i class="fa fa-clipboard " aria-hidden="true"></i> Print </a>'
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Type</th><th>Medicine & Generic</th><th>When to take</th><th>Frequency</th><th>Duration(Days)</th><th>Notes</th><th>Dosage</th></tr></thead>';

                            $('#tbl-medicine_' + visit_report_id).html('');
                            $('#tbl-medicine_' + visit_report_id).append(table + headTable + tr + tableend);
                            $('#Prescription_div_' + data.Table18[0].visit_report_id).show();
                        }
                        else {
                            $('#Prescription_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        if (data.Table22.length > 0) {
                            j = 0;
                            var labtr = '';
                            var SuggestedDate = '';
                            var thead = '<table class="table table-condensed table_bordered"><th>S.No</th><th>Service Name</th><th>Service Code</th><th>Quantity</th><th>Date</th><th>Service Added From</th><th>Action</th>';
                            var theadend = '</table>';

                            //for (var i = 0; i < data.Table22.length; i++) {
                            //    //labtr = labtr + '<tr><td>' + data.Table2[i].lab_prescription + '</td><td>' + data.Table2[i].lab_type_name + '</td><td style="text-align:center;">' + data.Table2[i].suggested_date + '</td></tr>'
                            //    if (i == 0) {
                            //        labtr = labtr + '<tr><td><p><span>' + data.Table22[i].suggested_date + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        SuggestedDate = data.Table22[i].suggested_date;
                            //    }
                            //    else {
                            //        if (data.Table22[i].suggested_date == SuggestedDate) {
                            //            SuggestedDate = data.Table22[i].suggested_date;
                            //            labtr = labtr + '<span>,</span><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        }
                            //        else {
                            //            SuggestedDate = data.Table22[i].suggested_date;
                            //            labtr = labtr + '</td></tr><tr><td></p><p><span>' + SuggestedDate + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        }
                            //    }

                            //}

                            for (var i = 0; i < data.Table22.length; i++) {
                                var action = "-";
                                //var action ='<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=job_service_detail_print("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].master_service_id + '","' + data.Table22[i].barcodeid + '","'+ data.Table22[i].work_order_details_id+'")><i class="fa fa fa-print" aria-hidden="true"></i></button>'
                                var payment = '';
                                if (data.Table22[i].is_lab == 1 || data.Table22[i].is_appointment == 1) {
                                    var lab_document = '';
                                    if (data.Table22[i].document_path != null && data.Table22[i].document_path != "") {
                                        var str = data.Table22[i].document_path;
                                        var temp = new Array();
                                        temp = str.split(",");
                                        var strarray = str.split(',');
                                        for (var k = 0; k < strarray.length; k++) {
                                            lab_document = lab_document + '<a href="' + $('#hdngetlabfilepath').val() + $('#HdnHospitalid').val() + "/" + $('#HBranchID').val() + "/Lab_Documents/" + strarray[k] + '" target="_blank" style="margin-right: 10px;">Lab Document ' + (k + 1) + '</a>' + "/";
                                        }
                                    }
                                    action = ((data.Table22[i].flag == 3 || data.Table22[i].flag == 4)) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprint("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].master_service_id + '","' + data.Table22[i].samplbarcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : (data.Table22[i].flag == 2) ? lab_document + " Result Pending" : "Result Pending";
                                    payment = ((data.Table22[i].is_bill == 1 || data.Table22[i].is_bill == "1") && data.Table22[i].due_amount == "0.00") ? '<a><span class="label label-success" style="background-color: green !important;">PAID</span></a>' : '<a><span class="label label-danger">PENDING</span></a>';

                                    if (data.Table22[i].is_appointment == 1 && data.Table22[i].is_lab != 1) {
                                        action = (data.Table22[i].aflag == 4) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprintappointemnt("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].work_order_details_id + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : "Result Pending";
                                    }
                                }

                                labtr = labtr + '<tr><td>' + (i + 1) + '</td><td>' + payment + data.Table22[i].service_name + '</td><td>' + data.Table22[i].service_code + '</td><td>' + data.Table22[i].quantity + '</td><td>' + data.Table22[i].service_date + '</td><td>' + data.Table22[i].added_from + '</td><td>' + action + '</td></tr>';
                            }


                            $('#Lab-table_' + data.Table22[0].visit_report_id).html('');
                            $('#Lab-table_' + data.Table22[0].visit_report_id).append(thead + labtr + theadend);
                            $('#lab_div_' + data.Table18[0].visit_report_id).show();

                        }

                        else {
                            $('#lab_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        if (data.Table23.length > 0) {
                            var imgtr = '';
                            for (var i = 0; i < data.Table23.length; i++) {
                                var img = '';
                                if (data.Table23[i].patient_lab_record_path == '' || data.Table23[i].patient_lab_record_path == null) {
                                    img = '-';
                                }
                                else {
                                    if (data.Table23[i].record_type == 3) {
                                        img = '<img src=' + $("#hdngetlabfilepath").val() + data.Table23[i].doctor_id + "/PrescriptionWritingPad/" + data.Table23[i].patient_lab_record_path + ' class="img-responsive" style="height: 50px;width: 50px;">';
                                        img = '<a href="' + $('#hdngetlabfilepath').val() + data.Table23[i].doctor_id + "/PrescriptionWritingPad/" + data.Table23[i].patient_lab_record_path + '" target="_blank">' + img + '</a>'
                                    }
                                    else {
                                        img = '<img src=' + $("#hdngetlabfilepath").val() + data.Table23[i].patient_lab_record_path + ' class="img-responsive" style="height: 50px;width: 50px;">';
                                        img = '<a href="' + $('#hdngetlabfilepath').val() + data.Table23[i].patient_lab_record_path + '" target="_blank">' + img + '</a>'
                                    }
                                }
                                imgtr = imgtr + '<div class="col-xs-3">' + img + '<br/><span style="text-transform:capitalize;">' + ((data.Table23[i].patient_testname != '' && data.Table23[i].patient_testname != null) ? data.Table23[i].patient_testname : 'No file name') + '</span></div>';
                            }
                            $('#tbl-fileupload_' + data.Table23[0].visit_report_id).html('');
                            $('#tbl-fileupload_' + data.Table23[0].visit_report_id).append(imgtr);
                        }
                        else {
                            $('#file_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        if (data.Table24.length > 0) {
                            if (data.Table24[0].NextAppointment != '' && data.Table24[0].NextAppointment != null) {
                                $('#lblNextApp_' + data.Table24[0].visit_report_id).html(data.Table24[0].NextAppointment);
                            }
                            else {
                                $('#divNextApp_' + data.Table18[0].visit_report_id).hide();
                            }
                            if (data.Table24[0].next_appointment_notes != '' && data.Table24[0].next_appointment_notes != null) {
                                $('#lblNextAppNotes_' + data.Table24[0].visit_report_id).html(data.Table24[0].next_appointment_notes);
                            }
                            else {
                                $('#divNextAppNotes_' + data.Table18[0].visit_report_id).hide();
                            }

                            if ((data.Table24[0].NextAppointment == '' || data.Table24[0].NextAppointment == null) && (data.Table24[0].next_appointment_notes == '' || data.Table24[0].next_appointment_notes == null)) {
                                $('#next_div_' + data.Table18[0].visit_report_id).hide();
                            }
                        }
                        else {
                            $('#next_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        $('#summary_div_' + visitReportId).removeClass('us-db-case-loader');
                    }
                    else {
                        $('.tbl_patient_summary_details').html('');
                        $('#summary_div_' + visitReportId).removeClass('us-db-case-loader');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function load_patient_summary_visit_report() {
    debugger;
    var MedicinePrescriptiondate = {
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        doctor_id: $('#doctorId').val(),
        type: "1"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Summary_details',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(MedicinePrescriptiondate),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('.tbl_patient_summary_details').html();
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 2) {
                        console.log(data);
                        debugger;
                        var div = "", divtr = '';
                        var j = 1;

                        //loadvisit_selection
                        if (data.Table20.length > 0) {
                            for (var i = 0; i < data.Table20.length; i++) {
                                var expanded_status = 'false', expanded_in = '';
                                //if (i < 1) {
                                //    expanded_status = 'True';
                                //    expanded_in = 'in';
                                //}
                                divtr = divtr + '<div class="panel panel-primary" onclick=patient_summary_visit_report("' + data.Table20[i].visit_report_id + '")><div class="panel-heading clearfix" role="button" data-toggle="collapse" data-parent="#accordion" href="#PatientVisitSummary-section' + data.Table20[i].visit_report_id + '" aria-expanded="' + expanded_status + '" aria-controls="PatientVisitSummary-section' + data.Table20[i].visit_report_id + '"><i class="icon-calendar"></i>'
                                divtr = divtr + '<h3 class="panel-title"><span class="pull-left">' + data.Table20[i].visit_date + '</span><span class="pull-right"><a href="javascript:void(0);" onclick=\'printpdf(\"' + data.Table20[i].visit_report_id + '\",\"' + data.Table20[i].visit_reportid + '\",\"' + data.Table20[i].patientid + '\",\"' + data.Table20[i].hospitalid + '\",\"' + data.Table20[i].branch_id + '\",\"' + data.Table20[i].doctorname + '\",\"' + data.Table20[i].hospitalname + '\",\"' + data.Table20[i].phonenumber + '\",\"' + data.Table20[i].patientemailid + '\")\'><i class="fa fa-print "></i> print </a>&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-angle-double-down"></i></span></h3></div><div id="PatientVisitSummary-section' + data.Table20[i].visit_report_id + '" class="panel-collapse collapse in' + expanded_in + '" role="tabpanel" aria-labelledby="headingOne">'
                                divtr = divtr + '<div class="panel-body"><div class="us-db-case-loader" id="summary_div_' + data.Table20[i].visit_report_id + '"><div style="padding:0px;" class="col-md-12" id="summarydiv_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock">Summary</div><div class="col-md-12" id="tbl_patient_summary_details_' + data.Table20[i].visit_report_id + '"></div></div>'
                                divtr = divtr + '<div id="Prescription_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Prescription</b></h5></div><div class="presc_table_block"><div id="tbl-medicine_' + data.Table20[i].visit_report_id + '"></div></div></div>'
                                divtr = divtr + '<div id="lab_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Investigations</b></h5></div><div class=""><div id="Lab-table_' + data.Table20[i].visit_report_id + '" ></div></div></div>'
                                divtr = divtr + '<div id="exercise_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Exercise/Physiotherapy</b></h5></div><div class=""><div id="Exercise-table_' + data.Table20[i].visit_report_id + '" ></div></div></div>'
                                divtr = divtr + '<div id="diet_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Diet</b></h5></div><div class=""><div id="Diet_table_' + data.Table20[i].visit_report_id + '" ></div></div></div>'
                                divtr = divtr + '<div id="observed_nutrition_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Observed Nutrition</b></h5></div><div class=""><div id="observed_nutrition_table_' + data.Table20[i].visit_report_id + '" ></div></div></div>'
                                divtr = divtr + '<div id="file_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Files</b></h5></div><div class="col-xs-12 presc_table_block" id="tbl-fileupload_' + data.Table20[i].visit_report_id + '"></div></div>'
                                divtr = divtr + '<div id="next_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Next Appointment</b></h5></div><div class="col-md-12 padding0 " id="divNextApp_' + data.Table20[i].visit_report_id + '"><div class="col-md-6 disp_table_cell"><div class="form-group label_center"><label class="control-label">Next Appointment Date</label></div></div><div class="col-md-6 disp_table_cell"><div class="form-group label_center"><label class="control-label next_appoinment_date_label_1" id="lblNextApp_' + data.Table20[i].visit_report_id + '"></label></div></div></div><div class="col-md-12 padding0 " id="divNextAppNotes_' + data.Table20[i].visit_report_id + '"><div class="col-md-6 disp_table_cell"><div class="form-group label_center"><label class="control-label">Next Appointment Notes</label> : <span id="lblNextAppNotes_' + data.Table20[i].visit_report_id + '"></span></div></div></div></div>'
                                divtr = divtr + '<div id="future_services_div_' + data.Table20[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Future Investigations</b></h5></div><div class=""><div id="future_services_table_' + data.Table20[i].visit_report_id + '" ></div></div></div></div></div></div></div>';
                            }
                            //$('.loadvisit_selection').html(divtr);
                            $('#cs_op_history_data').html(divtr);

                        }

                        if (data.Table32.length > 0) {
                            divtr = '';
                            for (var i = 0; i < data.Table32.length; i++) {
                                var expanded_status = 'false', expanded_in = '';
                                //if (i < 1) {
                                //    expanded_status = 'True';
                                //    expanded_in = 'in';
                                //}
                                divtr = divtr + '<div class="panel panel-primary" onclick=patient_summary_visit_report("' + data.Table32[i].visit_report_id + '")><div class="panel-heading clearfix" role="button" data-toggle="collapse" data-parent="#accordion" href="#PatientVisitSummary-section' + data.Table32[i].visit_report_id + '" aria-expanded="' + expanded_status + '" aria-controls="PatientVisitSummary-section' + data.Table32[i].visit_report_id + '"><i class="icon-calendar"></i>'
                                divtr = divtr + '<h3 class="panel-title"><span class="pull-left">' + data.Table32[i].visit_date + '</span><span class="pull-right"><a href="javascript:void(0);" onclick=Discharge_report("' + data.Table32[i].branch_id + '","' + data.Table32[i].hospitalid + '","' + data.Table32[i].patientid + '","' + data.Table32[i].visit_reportid + '")><i class="fa fa-print "></i> print </a>&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-angle-double-down"></i></span></h3></div><div id="PatientVisitSummary-section' + data.Table32[i].visit_report_id + '" class="panel-collapse collapse' + expanded_in + '" role="tabpanel" aria-labelledby="headingOne">'
                                divtr = divtr + '<div class="panel-body"><div class="us-db-case-loader" id="summary_div_' + data.Table32[i].visit_report_id + '"><div style="padding:0px;" class="col-md-12" id="summarydiv_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock">Summary</div><div class="col-md-12" id="tbl_patient_summary_details_' + data.Table32[i].visit_report_id + '"></div></div>'
                                divtr = divtr + '<div id="Prescription_div_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Prescription</b></h5></div><div class="presc_table_block"><div id="tbl-medicine_' + data.Table32[i].visit_report_id + '"></div></div></div>'
                                divtr = divtr + '<div id="lab_div_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Investigations</b></h5></div><div class=""><div id="Lab-table_' + data.Table32[i].visit_report_id + '" ></div></div></div>'
                                //divtr = divtr + '<div id="exercise_div_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Exercise/Physiotherapy</b></h5></div><div class=""><div id="Exercise-table_' + data.Table32[i].visit_report_id + '" ></div></div></div>'
                                //divtr = divtr + '<div id="file_div_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Files</b></h5></div><div class="col-xs-12 presc_table_block" id="tbl-fileupload_' + data.Table32[i].visit_report_id + '"></div></div>'
                                //divtr = divtr + '<div id="next_div_' + data.Table32[i].visit_report_id + '"><div class="label_center summaryblock"><h5><b>Next Appointment</b></h5></div><div class="col-md-6 padding0 "><div class="col-md-6 disp_table_cell"><div class="form-group label_center"><label class="control-label">Next Appointment Date</label></div></div><div class="col-md-6 disp_table_cell"><div class="form-group label_center"><label class="control-label next_appoinment_date_label_1" id="lblNextApp_' + data.Table32[i].visit_report_id + '"></label></div></div></div></div>'
                                divtr = divtr + '</div></div></div></div>';
                            }
                            $('#cs_ip_history').html(divtr);
                            //$('.loadvisit_selection').html(divtr);

                        }
                        else {
                            $('#cs_ip_history').html('<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" style="height: 500px;width: 1300px;" ><br><div class="no_data_content">No data found.</div></div>');
                        }

                        div = div + '<div class="col-md-12"><h5><b>Doctor Name :  ' + data.Table24[0].doctor_name + '</b></h5></div>';

                        if (data.Table.length > 0 && ((data.Table[0].pulse_rate != null && data.Table[0].pulse_rate != '') || (data.Table[0].spo2 != null && data.Table[0].spo2 != '') || (data.Table[0].temperature != null && data.Table[0].temperature != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }
                        else if (data.Table17.length > 0 && ((data.Table17[0].weight != null && data.Table17[0].weight != '') || (data.Table17[0].patient_height != null && data.Table17[0].patient_height != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }
                        else if (data.Table1.length > 0 && (data.Table1[0].patient_bp_max != null && data.Table1[0].patient_bp_max != '')) {
                            div = div + '<div class="col-md-12"><h5><b>Vitals</b></h5></div>';
                        }

                        if (data.Table17.length > 0) {
                            if (data.Table17[0].weight != null && data.Table17[0].weight != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Weight</label> : <span>' + data.Table17[0].weight + ' Kg </span></div>';
                            }
                            if (data.Table17[0].patient_height != null && data.Table17[0].patient_height != '') {
                                //var hieghtdb = parseInt(data.Table17[0].patient_height * 12) + parseInt(data.Table17[0].patient_height_metric);
                                ////var hieghtout = Math.round(hieghtdb * 2.54);
                                //var hieghtout = hieghtdb * 2.54;

                                var hieghtout = (data.Table17[0].patient_height * 30.48) + (data.Table17[0].patient_height_metric * 2.54);
                                hieghtout = hieghtout.toFixed(1);

                                $('#hieght').html(hieghtout);
                                var hieght = hieghtout;

                                div = div + '<div class="col-md-4"><label class="control-label">Height</label> : <span>' + hieght + ' cm </span></div>';
                            }
                        }

                        if (data.Table1.length > 0) {
                            if (data.Table1[0].patient_bp_max != null && data.Table1[0].patient_bp_max != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Sys/Dia</label> : <span>' + data.Table1[0].patient_bp_max + '</span>/<span>' + data.Table1[0].patient_bp_min + '</span></div>';
                            }
                        }

                        if (data.Table.length > 0) {
                            if (data.Table[0].pulse_rate != null && data.Table[0].pulse_rate != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Pulse Rate</label> : <span>' + data.Table[0].pulse_rate + '</span></div>';
                            }
                            if (data.Table[0].spo2 != null && data.Table[0].spo2 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SpO2</label> : <span>' + data.Table[0].spo2 + '</span></div>';
                            }
                            if (data.Table[0].temperature != null && data.Table[0].temperature != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Temperature</label> : <span>' + data.Table[0].temperature + '</span></div>';
                            }
                        }

                        if (data.Table.length > 0 && data.Table[0].observation_primary != null) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else if (data.Table17.length > 0 && data.Table17.length > 0) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else if (data.Table1.length > 0 && data.Table1[0].patient_bp_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>OBSERVATION</b></h5></div>';
                        }
                        else {
                        }

                        if (data.Table24.length > 0) {
                            if (data.Table24[0].diagnosis != null && data.Table24[0].diagnosis != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Diagnosis</label> : <span>' + data.Table24[0].diagnosis + ' </span></div>';
                            }
                            if (data.Table24[0].notes != null && data.Table24[0].notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Notes</label> : <span>' + data.Table24[0].notes + ' </span></div>';
                            }
                            if (data.Table24[0].investigation != null && data.Table24[0].investigation != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Investigation</label> : <span>' + data.Table24[0].investigation + ' </span></div>';
                            }
                            if (data.Table24[0].observation != null && data.Table24[0].observation != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Examination</label> : <span>' + data.Table24[0].observation + ' </span></div>';
                            }
                            if (data.Table24[0].treatment_procedure != null && data.Table24[0].treatment_procedure != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Treatment Procedure</label> : <span>' + data.Table24[0].treatment_procedure + ' </span></div>';
                            }
                            if (data.Table24[0].instruction != null && data.Table24[0].instruction != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Notes</label> : <span>' + data.Table24[0].instruction + ' </span></div>';
                            }
                            if (data.Table24[0].xray_findings != null && data.Table24[0].xray_findings != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Examination Findings</label> : <span>' + data.Table24[0].xray_findings + ' </span></div>';
                            }
                            if (data.Table24[0].advice != null && data.Table24[0].advice != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Advice</label> : <span>' + data.Table24[0].advice + ' </span></div>';
                            }
                            if (data.Table24[0].counselling != null && data.Table24[0].counselling != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Counselling</label> : <span>' + data.Table24[0].counselling + ' </span></div>';
                            }
                            if (data.Table24[0].xray_findings_new != null && data.Table24[0].xray_findings_new != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Xray Finding</label> : <span>' + data.Table24[0].xray_findings_new + ' </span></div>';
                            }
                            if (data.Table24[0].lab_findings != null && data.Table24[0].lab_findings != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Lab Findings</label> : <span>' + data.Table24[0].lab_findings + ' </span></div>';
                            }
                            if (data.Table24[0].review_notes != null && data.Table24[0].review_notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Review Notes</label> : <span>' + data.Table24[0].review_notes + ' </span></div>';
                            }
                        }

                        if (data.Table.length > 0) {

                            if (data.Table[0].current_complaints != null && data.Table[0].current_complaints != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Complaints</label> : <span>' + data.Table[0].current_complaints + '</span></div>';
                            }
                            if (data.Table[0].note != null && data.Table[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Test Requested </label> : <span>' + ((data.Table[0].note != null && data.Table[0].note != "") ? (data.Table[0].note + " - " + data.Table24[0].test_request) : data.Table[0].note) + '</span></div>';
                            }

                            if (data.Table[0].hypoglycemia_episodes != null && data.Table[0].hypoglycemia_episodes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Hypoglycemic Episodes</label> : <span>' + data.Table[0].hypoglycemia_episodes + '</span></div>';
                            }
                            if (data.Table28[0].vas != null && data.Table28[0].vas != '') {
                                if (data.Table28[0].vas == '0') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> No Pain</span></div>';
                                }
                                else if (data.Table28[0].vas == '1' || data.Table28[0].vas == '2' || data.Table28[0].vas == '3') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Mild</span></div>';
                                }
                                else if (data.Table28[0].vas == '4' || data.Table28[0].vas == '5' || data.Table28[0].vas == '6') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Moderate </span></div>';
                                }
                                else if (data.Table28[0].vas == '7' || data.Table28[0].vas == '8' || data.Table28[0].vas == '9') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Severe</span></div>';
                                }
                                if (data.Table28[0].vas == '10') {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Visual Analogue Scale(VAS)</b></h5></label> : <span> Worst Pain </span></div>';
                                }

                                if (data.Table28[0].vasduration != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Vas Duration</b></h5></label> : <span> ' + data.Table28[0].vasduration + ' </span></div>';
                                }

                                if (data.Table28[0].vaslocation != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Vas Location</b></h5></label> : <span> ' + data.Table28[0].vaslocation + ' </span></div>';
                                }

                                if (data.Table28[0].followup != null) {
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Follow Up/Admission Plan</b></h5></label> : <span> ' + data.Table28[0].followup + ' </span></div>';
                                }

                                if (data.Table28[0].vaspaincharacter != null) {
                                    var paincharacter = data.Table28[0].vaspaincharacter;

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

                                        var paincharactersplit = paincharacter.split(',');
                                        var paincharacter_disp = [];
                                        for (i = 0; i < paincharactersplit.length; i++) {

                                            if (paincharactersplit[i] == 0) {
                                                var paincharacter_view = "Dull"
                                            }
                                            else if (paincharactersplit[i] == 1) {
                                                var paincharacter_view = "Aching"
                                            }
                                            else if (paincharactersplit[i] == 2) {
                                                var paincharacter_view = "Sharp"
                                            }
                                            else if (paincharactersplit[i] == 3) {
                                                var paincharacter_view = "Stabbing"
                                            }
                                            else if (paincharactersplit[i] == 4) {
                                                var paincharacter_view = "Shooting"
                                            }
                                            else if (paincharactersplit[i] == 5) {
                                                var paincharacter_view = "Burning"
                                            }
                                            else if (paincharactersplit[i] == 6) {
                                                var paincharacter_view = "Referred/Radiant Plain"
                                            }
                                            paincharacter_disp.push(paincharacter_view)

                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Pain Character</b></h5></label> : <span> ' + paincharacter_disp + ' </span></div>';
                                }
                                if (data.Table28[0].vasfullrisk != null) {
                                    var frsfa = data.Table28[0].vasfullrisk;
                                    var frsfa_disp = [];
                                    if (frsfa != null && frsfa != "") {

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

                                        for (i = 0; i < frsfasplit.length; i++) {
                                            if (frsfasplit[i] == 0) {
                                                var frsfa_view = "No risk"
                                            }
                                            else if (frsfasplit[i] == 1) {
                                                var frsfa_view = "Age More than 65 years"
                                            }
                                            else if (frsfasplit[i] == 2) {
                                                var frsfa_view = "History of fall in last 3 Months"
                                            }
                                            else if (frsfasplit[i] == 3) {
                                                var frsfa_view = "Walks with assistance"
                                            }
                                            else if (frsfasplit[i] == 4) {
                                                var frsfa_view = "Any Neurological Problem"
                                            }

                                            frsfa_disp.push(frsfa_view)


                                        }

                                    }
                                    div = div + '<div class="col-md-12"><label class="control-label"><h5><b>Full Risk Screening for Adults</b></h5></label> : <span> ' + frsfa_disp + ' </span></div>';
                                }
                            }

                            if (data.Table[0].glycemic_variability != null && data.Table[0].glycemic_variability != '') {
                                var glycemic_variability = data.Table[0].glycemic_variability;
                                if (glycemic_variability == 1) {
                                    glycemic_variability = "Present";
                                }
                                else {
                                    glycemic_variability = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Glycemic Variability</label> : <span>' + glycemic_variability + '</span></div>';
                            }
                            if (data.Table[0].cvs != null && data.Table[0].cvs != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CVS</label> : <span>' + data.Table[0].cvs + '</span></div>';
                            }
                            if (data.Table[0].ABS != null && data.Table[0].ABS != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ABD</label> : <span>' + data.Table[0].ABS + '</span></div>';
                            }
                            if (data.Table[0].rs != null && data.Table[0].rs != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">RS</label> : <span>' + data.Table[0].rs + '</span></div>';
                            }
                            if (data.Table[0].CNS != null && data.Table[0].CNS != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CNS</label> : <span>' + data.Table[0].CNS + '</span></div>';
                            }

                            if (data.Table[0].heart_sound != null && data.Table[0].heart_sound != '') {
                                var heart_sound = data.Table[0].heart_sound;
                                if (heart_sound == 1) {
                                    heart_sound = "True";
                                }
                                else {
                                    heart_sound = "False";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Abnormal Heart Sound</label> : <span>' + heart_sound + '</span></div>';
                            }

                            if (data.Table[0].murmurs != null && data.Table[0].murmurs != '') {
                                var murmurs = data.Table[0].murmurs;
                                if (murmurs == 1) {
                                    murmurs = "Present";
                                }
                                else {
                                    murmurs = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Murmurs</label> : <span>' + murmurs + '</span></div>';
                            }

                            if (data.Table[0].reduce_air_entry != null && data.Table[0].reduce_air_entry != '') {
                                var reduce_air_entry = data.Table[0].reduce_air_entry;
                                if (reduce_air_entry == 1) {
                                    reduce_air_entry = "Present";
                                }
                                else {
                                    reduce_air_entry = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Reduced Air Entry</label> : <span>' + reduce_air_entry + '</span></div>';
                            }

                            if (data.Table[0].crackles != null && data.Table[0].crackles != '') {
                                var crackles = data.Table[0].crackles;
                                if (crackles == 1) {
                                    crackles = "Present";
                                }
                                else {
                                    crackles = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Crackles</label> : <span>' + crackles + '</span></div>';
                            }
                            if (data.Table[0].bowel_sounds != null && data.Table[0].bowel_sounds != '') {
                                var bowel_sounds = data.Table[0].bowel_sounds;
                                if (bowel_sounds == 1) {
                                    bowel_sounds = "Present";
                                }
                                else {
                                    bowel_sounds = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Abnormal Bowel Sounds</label> : <span>' + bowel_sounds + '</span></div>';
                            }
                            if (data.Table[0].organomeglay != null && data.Table[0].organomeglay != '') {
                                var organomeglay = data.Table[0].organomeglay;
                                if (organomeglay == 1) {
                                    organomeglay = "Present";
                                }
                                else {
                                    organomeglay = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Organomeglay</label> : <span>' + organomeglay + '</span></div>';
                            }
                            if (data.Table[0].tremors_weakness != null && data.Table[0].tremors_weakness != '') {
                                var tremors_weakness = data.Table[0].tremors_weakness;
                                if (tremors_weakness == 1) {
                                    tremors_weakness = "Present";
                                }
                                else {
                                    tremors_weakness = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Tremors Weakness</label> : <span>' + tremors_weakness + '</span></div>';
                            }
                            if (data.Table[0].cognitive_imparement != null && data.Table[0].cognitive_imparement != '') {
                                var cognitive_imparement = data.Table[0].cognitive_imparement;
                                if (cognitive_imparement == 1) {
                                    cognitive_imparement = "Present";
                                }
                                else {
                                    cognitive_imparement = "Absent";
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Cognitive Imparement</label> : <span>' + cognitive_imparement + '</span></div>';
                            }
                        }



                        //dental
                        if (data.Table28.length > 0 && (data.Table28[0].dental_procedure_done != null || data.Table28[0].dental_procedure_remaining != null || data.Table28[0].dental_type != null || data.Table28[0].dental_hard_tissue != null || data.Table28[0].dental_soft_tissue != null)) {
                            div = div + '<div class="col-md-12"><h5><b>Dental</b></h5></div>';
                        }
                        if (data.Table28.length > 0) {
                            if (data.Table28[0].dental_type != null && data.Table28[0].dental_type != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Type of Dental Appointment</label> : <span>' + (data.Table28[0].dental_type == 1 ? "Cosmetic" : data.Table28[0].dental_type == 2 ? "Dental" : "Surgical") + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_done != null && data.Table28[0].dental_procedure_done != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Done</label> : <span>' + data.Table28[0].dental_procedure_done + '</span></div>';
                            }
                            if (data.Table28[0].dental_procedure_remaining != null && data.Table28[0].dental_procedure_remaining != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Procedure Remaining</label> : <span>' + data.Table28[0].dental_procedure_remaining + '</span></div>';
                            }
                            if (data.Table28[0].dental_hard_tissue != null && data.Table28[0].dental_hard_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Hard Tissue</label> : <span>' + data.Table28[0].dental_hard_tissue + '</span></div>';
                            }
                            if (data.Table28[0].dental_soft_tissue != null && data.Table28[0].dental_soft_tissue != '') {
                                div = div + '<div class="col-md-12"><label class="control-label">Soft Tissue</label> : <span>' + data.Table28[0].dental_soft_tissue + '</span></div>';
                            }
                        }

                        if (data.Table2.length > 0 && data.Table2[0].glycemic_parameters_basic_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else if (data.Table3.length > 0 && data.Table3[0].patient_hbac_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else if (data.Table4.length > 0 && data.Table4[0].patient_blood_sugar_record_id != null) {
                            div = div + '<div class="col-md-12"><h5><b>Glycemic</b></h5></div>';
                        }
                        else {
                        }
                        if (data.Table2.length > 0) {
                            if (data.Table2[0].fasting_insulin != null && data.Table2[0].fasting_insulin != '') {
                                var fasting_inslin_unit = 'mlU/L';
                                if (data.Table2[0].fasting_inslin_unit == 2) {
                                    fasting_inslin_unit = 'pmol/L'
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Fasting Insulin</label> : <span>' + data.Table2[0].fasting_insulin + ' ' + fasting_inslin_unit + '</span></div>';
                            }
                            if (data.Table2[0].hemoglobin != null && data.Table2[0].hemoglobin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">HB</label> : <span>' + data.Table2[0].hemoglobin + ' gms</span></div>';
                            }
                            if (data.Table2[0].note != null && data.Table2[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Glycemic Notes</label> : <span>' + data.Table2[0].note + '</span></div>';
                            }
                            if (data.Table2[0].WBC != null && data.Table2[0].WBC != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">WBC</label> : <span>' + data.Table2[0].WBC + ' cells per cubic millimeter</span></div>';
                            }
                            if (data.Table2[0].platelet != null && data.Table2[0].platelet != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Platelet</label> : <span>' + data.Table2[0].platelet + ' per microliter</span></div>';
                            }
                            if (data.Table2[0].se_ketones != null && data.Table2[0].se_ketones != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Se_ketones</label> : <span>' + data.Table2[0].se_ketones + ' mmol/L</span></div>';
                            }

                        }

                        if (data.Table3.length > 0) {
                            if (data.Table3[0].patient_hbac_record_value != null && data.Table3[0].patient_hbac_record_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">HBA1C</label> : <span>' + data.Table3[0].patient_hbac_record_value + ' %</span></div>';
                            }
                        }

                        if (data.Table4.length > 0) {
                            for (var i = 0; i < data.Table4.length; i++) {
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 1) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Fasting blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 2) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Postprandial blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 3) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Random blood sugar</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 4) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Before Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 5) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">After Lunch BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 6) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">Before Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 7) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">After Dinner BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                                if (data.Table4[i].patient_blood_sugar_value != null && data.Table4[i].patient_blood_sugar_value != '' && data.Table4[i].patient_blood_sugar_type == 8) {
                                    var unit = 'mg/dL';
                                    if (data.Table4[i].patient_blood_sugar_unit == 1) {
                                        unit = 'mmol/L';
                                    }
                                    div = div + '<div class="col-md-4"><label class="control-label">3 Am BS</label> : <span>' + data.Table4[i].patient_blood_sugar_value + ' ' + unit + '</span></div>';
                                }
                            }

                        }
                        //want to write code
                        if (data.Table5.length > 0) {
                            //if (data.Table3[0].patient_hbac_record_value != null && data.Table3[0].patient_hbac_record_value != '') {
                            //    div = div + '<div class="col-md-4"><label class="control-label">Platelet</label> : <span>' + data.Table3[0].patient_hbac_record_value + ' %</span></div>';
                            //}
                        }

                        if (data.Table6.length > 0) {
                            if (data.Table6[0].renal_function_test_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>RENAL</b></h5></div>';
                            }
                        }
                        else {
                            if (data.Table7.length > 0) {
                                if ((data.Table7[0].ACR != null && data.Table7[0].ACR != '') || (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '')) {
                                    div = div + '<div class="col-md-12"><h5><b>RENAL</b></h5></div>';
                                }
                            }
                        }

                        if (data.Table6.length > 0) {
                            if (data.Table6[0].Urea != null && data.Table6[0].Urea != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].urea_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Urea</label> : <span>' + data.Table6[0].Urea + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].creatinine != null && data.Table6[0].creatinine != '') {
                                var unit = 'mg/dL';
                                if (data.Table6[0].Creatinine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Creatinine</label> : <span>' + data.Table6[0].creatinine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].egfr_value != null && data.Table6[0].egfr_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">EGFR ( Calculated )</label> : <span>' + data.Table6[0].egfr_value + ' ml/min/1.73m2</span></div>';
                            }
                            if (data.Table6[0].Sodium != null && data.Table6[0].Sodium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].sodium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Sodium</label> : <span>' + data.Table6[0].Sodium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Potassium != null && data.Table6[0].Potassium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].potassium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Potassium</label> : <span>' + data.Table6[0].Potassium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].Chlorine != null && data.Table6[0].Chlorine != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].chlorine_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Chlorine</label> : <span>' + data.Table6[0].Chlorine + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].BiCarbonate != null && data.Table6[0].BiCarbonate != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Bicarbonate_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">BiCarbonate</label> : <span>' + data.Table6[0].BiCarbonate + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_calcium != null && data.Table6[0].serium_calcium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Calcium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Calcium</label> : <span>' + data.Table6[0].serium_calcium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_phosphorous != null && data.Table6[0].serium_phosphorous != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Phosphorus_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Phosphorous</label> : <span>' + data.Table6[0].serium_phosphorous + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].serium_magnesium != null && data.Table6[0].serium_magnesium != '') {
                                var unit = 'mEq/L';
                                if (data.Table6[0].Magnesium_unit == 1) {
                                    unit = 'mmol/L';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Magnesium</label> : <span>' + data.Table6[0].serium_magnesium + '' + unit + ' </span></div>';
                            }
                            if (data.Table6[0].note != null && data.Table6[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Renal Notes</label> : <span>' + data.Table6[0].note + ' </span></div>';
                            }
                            if (data.Table6[0].ASD != null && data.Table6[0].ASD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ASD</label> : <span>' + data.Table6[0].ASD + ' </span></div>';
                            }
                            if (data.Table6[0].VSD != null && data.Table6[0].VSD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">VSD</label> : <span>' + data.Table6[0].VSD + ' </span></div>';
                            }
                            if (data.Table6[0].C_value != null && data.Table6[0].C_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Valve Notes</label> : <span>' + data.Table6[0].C_value + ' </span></div>';
                            }
                            if (data.Table6[0].fraction != null && data.Table6[0].fraction != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Fraction</label> : <span>' + data.Table6[0].fraction + ' </span></div>';
                            }
                            if (data.Table6[0].mitral_value != null && data.Table6[0].mitral_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Mitral Value</label> : <span>' + data.Table6[0].mitral_value + ' </span></div>';
                            }
                            if (data.Table6[0].lotic_value != null && data.Table6[0].lotic_value != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Aortic Valve</label> : <span>' + data.Table6[0].lotic_value + ' </span></div>';
                            }
                            if (data.Table6[0].tricuspid != null && data.Table6[0].tricuspid != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Tricuspid</label> : <span>' + data.Table6[0].tricuspid + ' </span></div>';
                            }
                            if (data.Table6[0].pulmonary != null && data.Table6[0].pulmonary != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Pulmonary</label> : <span>' + data.Table6[0].pulmonary + ' </span></div>';
                            }

                        }

                        if (data.Table7.length > 0) {
                            if (data.Table7[0].ACR != null && data.Table7[0].ACR != '') {
                                var ACR = '';
                                if (data.Table7[0].ACR == 1) {
                                    ACR = '< 30 mg/dL - Normal';
                                }
                                if (data.Table7[0].ACR == 2) {
                                    ACR = '30 to 300 mg/dL - Microalbuminuria';
                                }
                                if (data.Table7[0].ACR == 3) {
                                    ACR = '  > 300 mg/dL - Proteinuria';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">ACR</label> : <span>' + ACR + '</span></div>';
                            }
                            if (data.Table7[0].nephropathy != null && data.Table7[0].nephropathy != '') {
                                var nephropathy = '';
                                if (data.Table7[0].nephropathy == 1) {
                                    nephropathy = 'Yes';
                                }
                                if (data.Table7[0].nephropathy == 2) {
                                    nephropathy = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Nephropathy</label> : <span>' + nephropathy + '</span></div>';
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].cholestrol_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>CHOLESTEROL</b></h5></div>';
                            }
                        }
                        else {
                            if (data.Table9.length > 0) {
                                if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                    div = div + '<div class="col-md-12"><h5><b>CHOLESTEROL</b></h5></div>';
                                }
                            }
                        }

                        if (data.Table8.length > 0) {
                            if (data.Table8[0].Total_Cholestrol != null && data.Table8[0].Total_Cholestrol != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Total_cholestrol_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Total Cholesterol</label> : <span>' + data.Table8[0].Total_Cholestrol + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].LDL != null && data.Table8[0].LDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].LDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">LDL</label> : <span>' + data.Table8[0].LDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].HDL != null && data.Table8[0].HDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].HDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">HDL</label> : <span>' + data.Table8[0].HDL + '' + unit + ' </span></div>';
                            }

                            if (data.Table8[0].VLDL != null && data.Table8[0].VLDL != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].VLDL_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">VLDL</label> : <span>' + data.Table8[0].VLDL + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].Triglycerides != null && data.Table8[0].Triglycerides != '') {
                                var unit = 'mmol/L';
                                if (data.Table8[0].Triglycerides_unit == 1) {
                                    unit = 'mg/dL';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Triglycerides</label> : <span>' + data.Table8[0].Triglycerides + '' + unit + ' </span></div>';
                            }
                            if (data.Table8[0].T_cholestrol_Hdl_ratio != null && data.Table8[0].T_cholestrol_Hdl_ratio != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Total Cholesterol : HDL Ratio</label> : <span>' + data.Table8[0].T_cholestrol_Hdl_ratio + ' </span></div>';
                            }
                            if (data.Table8[0].note != null && data.Table8[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Cholestrol Notes</label> : <span>' + data.Table8[0].note + ' </span></div>';
                            }
                        }
                        if (data.Table9.length > 0) {
                            if (data.Table9[0].dyslipedemia != null && data.Table9[0].dyslipedemia != '') {
                                var unit = '';
                                if (data.Table9[0].dyslipedemia == 1) {
                                    unit = 'yes';
                                }
                                else {
                                    unit = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Dyslipidemia</label> : <span>' + unit + ' </span></div>';
                            }
                        }
                        debugger;
                        if (data.Table10.length > 0 && ((data.Table10[0].last_observation_date != null && data.Table10[0].last_observation_date != '') || (data.Table10[0].next_suggested_appointment != null && data.Table10[0].next_suggested_appointment != '') || (data.Table10[0].note != null && data.Table10[0].note != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>OPTHAL</b></h5></div>';
                        }
                        else if (data.Table11.length > 0 && data.Table11[0].patient_level_flag_id != null && ((data.Table11[0].pdr != null && data.Table11[0].pdr != '') || (data.Table11[0].npdr != null && data.Table11[0].npdr != '') || (data.Table11[0].viterous_hemorage != null && data.Table11[0].viterous_hemorage != '') || (data.Table11[0].retinal_detachment != null && data.Table11[0].retinal_detachment != '') || (data.Table11[0].retinopathy != null && data.Table11[0].retinopathy != ''))) {
                            div = div + '<div class="col-md-12"><h5><b>OPTHAL</b></h5></div>';
                        }
                        if (data.Table10.length > 0) {

                            if (data.Table10[0].last_observation_date != null && data.Table10[0].last_observation_date != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Last Observation Date</label> : <span>' + data.Table10[0].last_observation_date + ' </span></div>';
                            }
                            if (data.Table10[0].next_suggested_appointment != null && data.Table10[0].next_suggested_appointment != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Next Suggested Opthal Appointment</label> : <span>' + data.Table10[0].next_suggested_appointment + ' </span></div>';
                            }
                            if (data.Table10[0].note != null && data.Table10[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Opthal Notes</label> : <span>' + data.Table10[0].note + ' </span></div>';
                            }
                        }

                        if (data.Table11.length > 0) {
                            if (data.Table11[0].pdr != null && data.Table11[0].pdr != '') {
                                var val = '';
                                if (data.Table11[0].pdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].pdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].pdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].pdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">PDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].npdr != null && data.Table11[0].npdr != '') {
                                var val = '';
                                if (data.Table11[0].npdr == 1) {
                                    val = 'None';
                                }
                                else if (data.Table11[0].npdr == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table11[0].npdr == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table11[0].npdr == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">NPDR</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].viterous_hemorage != null && data.Table11[0].viterous_hemorage != '') {
                                var val = '';
                                if (data.Table11[0].viterous_hemorage == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].viterous_hemorage == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Vitreous Hemorrhage</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinal_detachment != null && data.Table11[0].retinal_detachment != '') {
                                var val = '';
                                if (data.Table11[0].retinal_detachment == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinal_detachment == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Retinal Detachment</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table11[0].retinopathy != null && data.Table11[0].retinopathy != '') {
                                var val = '';
                                if (data.Table11[0].retinopathy == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table11[0].retinopathy == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Retinopathy</label> : <span>' + val + ' </span></div>';
                            }
                        }

                        if (data.Table19.length > 0 && data.Table19[0].patient_level_cardiac_id != null && (data.Table19[0].L_LAD != null || data.Table19[0].L_LAD_type != null || data.Table19[0].L_LCX != null ||
                            data.Table19[0].L_LCX_type != null || data.Table19[0].L_RCA != null || data.Table19[0].L_RCA_type != null || data.Table19[0].R_LAD != null || data.Table19[0].R_LAD_type != null
                            || data.Table19[0].R_LCX != null || data.Table19[0].R_LCX_type != null || data.Table19[0].R_RCA != null || data.Table19[0].R_RCA_type != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else if (data.Table12.length > 0 && data.Table12[0].cardiac_profile_id != null && (data.Table12[0].ECG != null || data.Table12[0].ECHO != null
                            || (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != 0) || (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != 0) || data.Table12[0].TMT_test != null || data.Table12[0].note != null)) {
                            div = div + '<div class="col-md-12"><h5>CARDIAC</h5></div>';
                        }
                        else { }
                        if (data.Table19.length > 0) {
                            if (data.Table19[0].L_LAD != null && data.Table19[0].L_LAD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LCA</label> : <span>' + data.Table19[0].L_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LAD_type != null && data.Table19[0].L_LAD_type != '' && data.Table19[0].L_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LAD_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">LCA Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].L_LCX != null && data.Table19[0].L_LCX != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LCX</label> : <span>' + data.Table19[0].L_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].L_LCX_type != null && data.Table19[0].L_LCX_type != '' && data.Table19[0].L_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_LCX_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">LCX Type</label> : <span>' + type + ' </span></div>';
                            }


                            if (data.Table19[0].L_RCA != null && data.Table19[0].L_RCA != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">LAD</label> : <span>' + data.Table19[0].L_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].L_RCA_type != null && data.Table19[0].L_RCA_type != '' && data.Table19[0].L_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].L_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].L_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].L_RCA_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">LAD Type</label> : <span>' + type + ' </span></div>';
                            }


                            if (data.Table19[0].R_LAD != null && data.Table19[0].R_LAD != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">RCA</label> : <span>' + data.Table19[0].R_LAD + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LAD_type != null && data.Table19[0].R_LAD_type != '' && data.Table19[0].R_LAD_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LAD_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LAD_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LAD_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">RCA Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].R_LCX != null && data.Table19[0].R_LCX != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">R-PLB</label> : <span>' + data.Table19[0].R_LCX + ' %</span></div>';
                            }
                            if (data.Table19[0].R_LCX_type != null && data.Table19[0].R_LCX_type != '' && data.Table19[0].R_LCX_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_LCX_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_LCX_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_LCX_type == 3) {
                                    type = 'Distal';
                                }

                                div = div + '<div class="col-md-4"><label class="control-label">R-PLB Type</label> : <span>' + type + ' </span></div>';
                            }

                            if (data.Table19[0].R_RCA != null && data.Table19[0].R_RCA != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">R-PDA</label> : <span>' + data.Table19[0].R_RCA + ' %</span></div>';
                            }
                            if (data.Table19[0].R_RCA_type != null && data.Table19[0].R_RCA_type != '' && data.Table19[0].R_RCA_type != 0) {
                                var type = '';
                                if (data.Table19[0].R_RCA_type == 1) {
                                    type = 'Proximal';
                                }
                                else if (data.Table19[0].R_RCA_type == 2) {
                                    type = 'Mid';
                                }
                                else if (data.Table19[0].R_RCA_type == 3) {
                                    type = 'Distal';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">R-PDA Type</label> : <span>' + type + ' </span></div>';
                            }
                        }

                        if (data.Table12.length > 0) {
                            if (data.Table12[0].ECG != null && data.Table12[0].ECG != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ECG</label> : <span>' + data.Table12[0].ECG + ' </span></div>';
                            }
                            if (data.Table12[0].ECHO != null && data.Table12[0].ECHO != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">ECHO</label> : <span>' + data.Table12[0].ECHO + ' </span></div>';
                            }
                            if (data.Table12[0].ecg_abnormal != null && data.Table12[0].ecg_abnormal != '') {
                                if (data.Table12[0].ecg_abnormal == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">ECG Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].echo_abnormal != null && data.Table12[0].echo_abnormal != '') {
                                if (data.Table12[0].echo_abnormal == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">ECHO Abnormal</label> : <span>True</span></div>';
                                }
                            }
                            if (data.Table12[0].TMT_test != null && data.Table12[0].TMT_test != '') {
                                if (data.Table12[0].TMT_test == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">TMT</label> : <span>Positive</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-4"><label class="control-label">TMT</label> : <span>Negative</span></div>';
                                }
                            }
                            if (data.Table12[0].note != null && data.Table12[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Cardiac Notes</label> : <span>' + data.Table12[0].note + '</span></div>';
                            }
                        }

                        if (data.Table13.length > 0 && (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '')) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else if (data.Table14.length > 0 && ((data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') || (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') || (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') || (data.Table14[0].note != null && data.Table14[0].note != ''))) {
                            div = div + '<div class="col-md-12"><h5>NEUROPATHY</h5></div>';
                        }
                        else {

                        }
                        if (data.Table13.length > 0) {
                            if (data.Table13[0].autonomic_neuropathy != null && data.Table13[0].autonomic_neuropathy != '') {
                                if (data.Table13[0].autonomic_neuropathy == 1) {
                                    div = div + '<div class="col-md-4"><label class="control-label">Autonomic Neuropathy</label> : <span>Yes</span></div>';
                                }
                                else {
                                    div = div + '<div class="col-md-4"><label class="control-label">Autonomic Neuropathy</label> : <span>No</span></div>';
                                }
                            }
                        }
                        if (data.Table14.length > 0) {
                            if (data.Table14[0].peripharal_neuhropathy != null && data.Table14[0].peripharal_neuhropathy != '') {
                                var val = '';
                                if (data.Table14[0].peripharal_neuhropathy == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].peripharal_neuhropathy == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Peripheral Neuhropathy</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].AB_index != null && data.Table14[0].AB_index != '') {
                                var val = '';
                                if (data.Table14[0].AB_index == 1) {
                                    val = 'None';
                                }
                                else if (data.Table14[0].AB_index == 2) {
                                    val = 'Mild';
                                }
                                else if (data.Table14[0].AB_index == 3) {
                                    val = 'Moderate';
                                }
                                else if (data.Table14[0].AB_index == 4) {
                                    val = 'Severe';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">AB Index</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table14[0].doppler_note != null && data.Table14[0].doppler_note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Doppler</label> : <span>' + data.Table14[0].doppler_note + ' </span></div>';
                            }
                            if (data.Table14[0].note != null && data.Table14[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Neuropthy Note</label> : <span>' + data.Table14[0].note + ' </span></div>';
                            }
                        }

                        if (data.Table15.length > 0) {
                            if (data.Table15[0].thyroid_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>THYROID</b></h5></div>';
                            }
                        }

                        if (data.Table15.length > 0) {
                            if (data.Table15[0].Free_T3 != null && data.Table15[0].Free_T3 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Free T3</label> : <span>' + data.Table15[0].Free_T3 + ' Pg/dl </span></div>';
                            }
                            if (data.Table15[0].Free_T4 != null && data.Table15[0].Free_T4 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Free T4</label> : <span>' + data.Table15[0].Free_T4 + ' ng/dl </span></div>';
                            }
                            if (data.Table15[0].TSH != null && data.Table15[0].TSH != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">TSH</label> : <span>' + data.Table15[0].TSH + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T3 != null && data.Table15[0].T3 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T3</label> : <span>' + data.Table15[0].T3 + ' mlU/m </span></div>';
                            }
                            if (data.Table15[0].T4 != null && data.Table15[0].T4 != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">T4</label> : <span>' + data.Table15[0].T4 + ' mlU/m </span></div>';
                            }

                            if (data.Table15[0].note != null && data.Table15[0].note != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Thyroid Notes</label> : <span>' + data.Table15[0].note + '</span></div>';
                            }
                        }

                        if (data.Table16.length > 0) {
                            if (data.Table16[0].sheet_chest_xray_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>ULTRASOUND / X-RAY</b></h5></div>';
                            }
                        }
                        if (data.Table16.length > 0) {
                            if (data.Table16[0].notes != null && data.Table16[0].notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Chest X-Ray Notes</label> : <span>' + data.Table16[0].notes + ' Pg/dl </span></div>';
                            }
                            if (data.Table16[0].USNotes != null && data.Table16[0].USNotes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Ultrasound Notes</label> : <span>' + data.Table16[0].USNotes + ' ng/dl </span></div>';
                            }
                            if (data.Table16[0].fatty_lives != null && data.Table16[0].fatty_lives != '') {
                                var val = '';
                                if (data.Table16[0].fatty_lives == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].fatty_lives == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">Fatty Liver</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].GS_Calculus != null && data.Table16[0].GS_Calculus != '') {
                                var val = '';
                                if (data.Table16[0].GS_Calculus == 1) {
                                    val = 'Yes';
                                }
                                else if (data.Table16[0].GS_Calculus == 2) {
                                    val = 'No';
                                }
                                div = div + '<div class="col-md-4"><label class="control-label">GB Calculas</label> : <span>' + val + ' </span></div>';
                            }
                            if (data.Table16[0].cts_notes != null && data.Table16[0].cts_notes != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">CT scan Notes</label> : <span>' + data.Table16[0].cts_notes + ' ng/dl </span></div>';
                            }
                        }
                        if (data.Table18.length > 0) {
                        }

                        if (data.Table26.length > 0) {
                            if (data.Table26[0].liver_function_test_id != null && (data.Table26[0].serum_bilirubin_total != null || data.Table26[0].serum_bilirubin_direct != null
                                || data.Table26[0].bilirubin_indirect != null || data.Table26[0].serum_protein_total != null || data.Table26[0].serum_protein_albumin != null || data.Table26[0].serumproteinglibulin != null
                                || data.Table26[0].SGOT != null || data.Table26[0].SGPT != null || data.Table26[0].serum_alkaline_phosphatase != null || data.Table26[0].gamma_glutamyl_transpeptidase != null || data.Table26[0].serum_magnesium != null)) {
                                div = div + '<div class="col-md-12"><h5><b>LIVER FUNCTION TEST</b></h5></div>';
                            }
                        }

                        if (data.Table26.length > 0) {
                            if (data.Table26[0].serum_bilirubin_total != null && data.Table26[0].serum_bilirubin_total != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Bilirubin Total</label> : <span>' + data.Table26[0].serum_bilirubin_total + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_bilirubin_direct != null && data.Table26[0].serum_bilirubin_direct != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Bilirubin Direct</label> : <span>' + data.Table26[0].serum_bilirubin_direct + ' mg/dl </span></div>';
                            }

                            if (data.Table26[0].bilirubin_indirect != null && data.Table26[0].bilirubin_indirect != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Bilirubin Indirect</label> : <span>' + data.Table26[0].bilirubin_indirect + ' mg/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_total != null && data.Table26[0].serum_protein_total != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein -Total</label> : <span>' + data.Table26[0].serum_protein_total + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].serum_protein_albumin != null && data.Table26[0].serum_protein_albumin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein - Albumin</label> : <span>' + data.Table26[0].serum_protein_albumin + ' g/dl</span></div>';
                            }
                            if (data.Table26[0].serumproteinglibulin != null && data.Table26[0].serumproteinglibulin != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Protein - Glibulin</label> : <span>' + data.Table26[0].serumproteinglibulin + ' g/dl </span></div>';
                            }
                            if (data.Table26[0].SGOT != null && data.Table26[0].SGOT != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SGOT (AST)</label> : <span>' + data.Table26[0].SGOT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].SGPT != null && data.Table26[0].SGPT != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">SGPT (AST)</label> : <span>' + data.Table26[0].SGPT + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_alkaline_phosphatase != null && data.Table26[0].serum_alkaline_phosphatase != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].serum_alkaline_phosphatase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].gamma_glutamyl_transpeptidase != null && data.Table26[0].gamma_glutamyl_transpeptidase != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Serum Alkaline Phosphatase</label> : <span>' + data.Table26[0].gamma_glutamyl_transpeptidase + ' IU/l </span></div>';
                            }
                            if (data.Table26[0].serum_magnesium != null && data.Table26[0].serum_magnesium != '') {
                                div = div + '<div class="col-md-4"><label class="control-label">Gamma Glutamyl Transpeptidase (GGT)</label> : <span>' + data.Table26[0].serum_magnesium + ' IU/l </span></div>';
                            }
                        }

                        if (data.Table27.length > 0) {
                            if (data.Table27[0].master_labtest_visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>Master Lab Test</b></h5></div>';
                            }
                        }
                        if (data.Table27.length > 0) {
                            for (var i = 0; i < data.Table27.length; i++) {
                                if (data.Table27[i].parameter_name != null && data.Table27[i].parameter_name != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">' + data.Table27[i].parameter_name + '</label> : <span>' + data.Table27[i].parameter_value + '  ' + data.Table27[i].reference_value + ' ' + data.Table27[i].unit + '</span></div>';
                                }
                            }
                        }

                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html('');
                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html(div);

                        if (data.Table21.length > 0) {
                            tr = '';
                            for (var i = 0; i < data.Table21.length; i++) {
                                var session = '';
                                visit_report_id = data.Table21[i].visit_report_id;
                                if (data.Table21[i].evening == 1) {
                                    session = data.Table21[i].morning + ' - ' + data.Table21[i].afternoon + ' - ' + data.Table21[i].evening + ' - ' + data.Table21[i].night;
                                }
                                else {
                                    session = data.Table21[i].morning + ' - ' + data.Table21[i].afternoon + ' - ' + data.Table21[i].night;
                                }
                                var color = '';
                                if (data.Table21[i].priority == 1) {
                                    color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
                                }
                                else if (data.Table21[i].priority == 2) {
                                    color = '<i class=" fa fa-circle" style="color:orange"></i>&nbsp;';
                                }
                                else if (data.Table21[i].priority == 3) {
                                    color = '<i class=" fa fa-circle" style="color:#418bfe"></i>&nbsp;';
                                }
                                else {
                                    color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
                                }
                                var instructions = '';
                                if (data.Table21[i].instructions == '' || data.Table21[i].instructions == null) {
                                    instructions = '';
                                }
                                else {
                                    instructions = data.Table21[i].instructions;
                                }
                                if (data.Table21[i].days_to_take == '' || data.Table21[i].days_to_take == null) {
                                    days_to_take = '';
                                }
                                else if (data.Table21[i].days_to_take == '9999') {
                                    days_to_take = 'Daily';
                                }
                                else {
                                    days_to_take = data.Table21[i].days_to_take;
                                }
                                var generic_name = '';
                                if (data.Table21[i].generic_name == '' || data.Table21[i].generic_name == null) {
                                    generic_name = '';
                                }
                                else {
                                    generic_name = '<span style=font-size:11px;><i>(' + data.Table21[i].generic_name + ')</i></span>';
                                }

                                //tr = tr + '<div class="col-md-12 presc_table_row"><div class="col-md-4"><span style="text-transform:capitalize;">' + data[i].medicine_name + '</div><div class="col-md-2 red">' + data[i].medicine_type + '</div><div class="col-md-2 red">' + data[i].when_to_eat_value + '</div><div class="col-md-3"> &nbsp; ' + data[i].morning + ' &nbsp;&nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp;&nbsp; ' + data[i].afternoon + '&nbsp;&nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp;&nbsp; ' + data[i].evening + ' &nbsp;&nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp;&nbsp; ' + data[i].night + ' &nbsp;&nbsp;&nbsp;&nbsp;</div><div class="col-md-1 red">' + data[i].days_to_take + '</div><div class="clearfix"></div></div>';
                                tr = tr + '<tr><td>' + data.Table21[i].medicine_type + '</td><td style="text-transform:capitalize;">' + color + data.Table21[i].medicine_name + generic_name + '</td><td>' + data.Table21[i].when_to_eat_value + '</td><td>' + data.Table21[i].medicine_frequency + '</td><td>' + days_to_take + '</td><td>' + instructions + '</td><td>' + session + '</td></tr>';
                            }

                            var pdf = '<a href="javascript:void(0);" class="pull-right btn_cpy_prescription" onclick=printPrescription("' + visit_report_id + '")><i class="fa fa-clipboard " aria-hidden="true"></i> Print </a>'
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Type</th><th>Medicine & Generic</th><th>When to take</th><th>Frequency</th><th>Duration(Days)</th><th>Notes</th><th>Dosage</th></tr></thead>';

                            $('#tbl-medicine_' + visit_report_id).html('');
                            $('#tbl-medicine_' + visit_report_id).append(table + headTable + tr + tableend);
                            $('#Prescription_div_' + data.Table18[0].visit_report_id).show();
                            //$('.prescription_print').html(pdf);
                        }
                        else {
                            $('#Prescription_div_' + data.Table18[0].visit_report_id).hide();
                        }


                        if (data.Table22.length > 0) {
                            j = 0;
                            var labtr = '';
                            var SuggestedDate = '';
                            var thead = '<table class="table table-condensed table_bordered"><th>S.No</th><th>Service Name</th><th>Service Code</th><th>Quantity</th><th>Date</th><th>Service Added From</th><th>Action</th>';
                            var theadend = '</table>';

                            //for (var i = 0; i < data.Table22.length; i++) {
                            //    //labtr = labtr + '<tr><td>' + data.Table2[i].lab_prescription + '</td><td>' + data.Table2[i].lab_type_name + '</td><td style="text-align:center;">' + data.Table2[i].suggested_date + '</td></tr>'
                            //    if (i == 0) {
                            //        labtr = labtr + '<tr><td><p><span>' + data.Table22[i].suggested_date + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        SuggestedDate = data.Table22[i].suggested_date;
                            //    }
                            //    else {
                            //        if (data.Table22[i].suggested_date == SuggestedDate) {
                            //            SuggestedDate = data.Table22[i].suggested_date;
                            //            labtr = labtr + '<span>,</span><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        }
                            //        else {
                            //            SuggestedDate = data.Table22[i].suggested_date;
                            //            labtr = labtr + '</td></tr><tr><td></p><p><span>' + SuggestedDate + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></td><td><span>' + data.Table22[i].lab_prescription + '</span>';
                            //        }
                            //    }

                            //}

                            for (var i = 0; i < data.Table22.length; i++) {
                                var action = "-";
                                // var action = '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=job_service_detail_print("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].master_service_id + '","' + data.Table22[i].barcodeid + '","'+data.Table22[i].work_order_details_id+'")><i class="fa fa fa-print" aria-hidden="true"></i></button>' 
                                var payment = '';
                                if (data.Table22[i].is_lab == 1 || data.Table22[i].is_appointment == 1) {
                                    var lab_document = '';
                                    if (data.Table22[i].document_path != null && data.Table22[i].document_path != "") {
                                        var str = data.Table22[i].document_path;
                                        var temp = new Array();
                                        temp = str.split(",");
                                        var strarray = str.split(',');
                                        for (var k = 0; k < strarray.length; k++) {
                                            lab_document = lab_document + '<a href="' + $('#hdngetlabfilepath').val() + $('#HdnHospitalid').val() + "/" + $('#HBranchID').val() + "/Lab_Documents/" + strarray[k] + '" target="_blank" style="margin-right: 10px;">Lab Document ' + (k + 1) + '</a>' + "/";
                                        }
                                    }
                                    action = ((data.Table22[i].flag == 3 || data.Table22[i].flag == 4)) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprint("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].master_service_id + '","' + data.Table22[i].samplbarcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : (data.Table22[i].flag == 2) ? lab_document + " Result Pending" : "Result Pending";
                                    payment = ((data.Table22[i].is_bill == 1 || data.Table22[i].is_bill == "1") && data.Table22[i].due_amount == "0.00") ? '<a><span class="label label-success" style="background-color: green !important;">PAID</span></a>' : '<a><span class="label label-danger">PENDING</span></a>';

                                    if (data.Table22[i].is_appointment == 1 && data.Table22[i].is_lab != 1) {
                                        action = (data.Table22[i].aflag == 4) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprintappointemnt("' + data.Table22[i].work_order_id + '","' + data.Table22[i].hospitalid + '","' + data.Table22[i].patientid + '","' + data.Table22[i].branchid + '","' + data.Table22[i].work_order_details_id + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : "Result Pending";
                                    }

                                }

                                labtr = labtr + '<tr><td>' + (i + 1) + '</td><td>' + payment + data.Table22[i].service_name + '</td><td>' + data.Table22[i].service_code + '</td><td>' + data.Table22[i].quantity + '</td><td>' + data.Table22[i].service_date + '</td><td>' + data.Table22[i].added_from + '</td><td>' + action + '</td></tr>';
                            }


                            $('#Lab-table_' + data.Table22[0].visit_report_id).html('');
                            $('#Lab-table_' + data.Table22[0].visit_report_id).append(thead + labtr + theadend);
                            $('#lab_div_' + data.Table18[0].visit_report_id).show();

                        }

                        else {
                            $('#lab_div_' + data.Table18[0].visit_report_id).hide();
                        }
                        if (data.Table31.length > 0) { //Exercise Summary
                            var exercisetable = '<>'
                            var tr = '';
                            for (var i = 0; i < data.Table31.length; i++) {

                                var monday = data.Table31[i].monday_flag;
                                var tuesday = data.Table31[i].tuesday_flag;
                                var wednesday = data.Table31[i].wednesday_flag;
                                var thusday = data.Table31[i].thursday_flag;
                                var friday = data.Table31[i].friday_flag;
                                var saturday = data.Table31[i].saturday_flag;
                                var sunday = data.Table31[i].sunday_flag;

                                var SuggestedDays = ''; var suggestedDaysCount = 0;
                                if (monday == 1) {

                                    SuggestedDays = 'Mon';
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (tuesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Tue';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Tue';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (wednesday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Wed';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Wed';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (thusday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Thu';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Thu';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (friday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Fri';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Fri';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (saturday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sat';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + ',  Sat';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                if (sunday == 1) {
                                    if (SuggestedDays == '') {
                                        SuggestedDays = '  Sun';
                                    }
                                    else {
                                        SuggestedDays = SuggestedDays + '  Sun';
                                    }
                                    suggestedDaysCount = suggestedDaysCount + 1;
                                }
                                var treatment_description = [];
                                var t = data.Table31[i].treatment.split(",");
                                var j = 0;
                                for (var k = 0; k < t.length; k++) {
                                    if (t[k] == 1) {
                                        treatment_description[j] = "IFT"
                                    }
                                    else if (t[k] == 2) {
                                        treatment_description[j] = "UST"
                                    }
                                    else if (t[k] == 3) {
                                        treatment_description[j] = "CCT"
                                    }
                                    else if (t[k] == 4) {
                                        treatment_description[j] = "WAX"
                                    }
                                    else if (t[k] == 5) {
                                        treatment_description[j] = "ES"
                                    }
                                    else if (t[k] == 6) {
                                        treatment_description[j] = "LASER"
                                    }
                                    else if (t[k] == 7) {
                                        treatment_description[j] = "ICT"
                                    }
                                    else if (t[k] == 8) {
                                        treatment_description[j] = "IPT"
                                    }
                                    else if (t[k] == 9) {
                                        treatment_description[j] = "CPM"
                                    }
                                    else if (t[k] == 10) {
                                        treatment_description[j] = "CPT"
                                    }
                                    else {

                                    }
                                    j++;
                                }
                                var treatment_description_1 = treatment_description.toString();

                                var choose_region_desc = [];
                                if (data.Table31[i].choose_region != null && data.Table31[i].choose_region != "") {
                                    var r = data.Table31[i].choose_region.split(",");
                                    var p = 0;
                                    for (var k = 0; k < r.length; k++) {
                                        choose_region_desc[p] = $("#SelRegion option[value='" + r[k] + "']").text();
                                        //if (r[k] == 1) {
                                        //    choose_region_desc[p] = "SHOULDER REHAB"
                                        //}
                                        //else if (r[k] == 2) {
                                        //    choose_region_desc[p] = "ELBOW REHAB"
                                        //}
                                        //else if (r[k] == 3) {
                                        //    choose_region_desc[p] = "WRIST & HAND REHAB"
                                        //}
                                        //else if (r[k] == 4) {
                                        //    choose_region_desc[p] = "SPINE REHAB"
                                        //}
                                        //else if (r[k] == 5) {
                                        //    choose_region_desc[p] = "PELVIC & CORE REHAB"
                                        //}
                                        //else if (r[k] == 6) {
                                        //    choose_region_desc[p] = "HIP REHAB"
                                        //}
                                        //else if (r[k] == 7) {
                                        //    choose_region_desc[p] = "KNEE REHAB"
                                        //}
                                        //else if (r[k] == 8) {
                                        //    choose_region_desc[p] = "ANKLE & FOOT REHAB"
                                        //}
                                        //else if (r[k] == 9) {
                                        //    choose_region_desc[p] = "LIBERATORY MANEUVER"
                                        //}
                                        //else {

                                        //}
                                        p++;

                                    }
                                }
                                var choose_region_1 = choose_region_desc.toString();


                                tr = tr + "<tr><td>" + choose_region_1 + "</td><td>" + data.Table31[i].op_type + "</td><td>" + data.Table31[i].excercise_description + "</td><td>" + SuggestedDays + "</td><td>" + data.Table31[i].days_to_take + "</td><td>" + data.Table31[i].excercise_duration_per_day + "</td><td>" + data.Table31[i].sitting + "</td><td>" + data.Table31[i].instruction + "</td><td>" + treatment_description_1 + "</td></tr>";
                            }
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Region</th><th>Pre/Post OP</th><th>Type of Exercise</th><th>Suggested Days</th><th>Number of Days</th><th>Duration</th><th>Sitting</th><th>Exercise Instruction</th><th>Treatment</th></tr></thead>';

                            $('#Exercise-table_' + data.Table18[0].visit_report_id).html('');
                            $('#Exercise-table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#exercise_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //diet summary
                        if (data.Table33.length > 0) {
                            var tr = "";
                            for (var i = 0; i < data.Table33.length; i++) {
                                j++;
                                tr = tr + "<tr><td>" + data.Table33[i].time + "</td>";
                                tr = tr + " <td>" + data.Table33[i].type_of_food + "</td>";
                                tr = tr + " <td>" + data.Table33[i].no_of_servings + ' Per day' + "</td>";
                                tr = tr + " <td>" + data.Table33[i].instructions + "</td>";
                                tr = tr + "</tr>";

                            }
                            var dietplan = '<div><p>Plan Duration: <span>' + ((data.Table33[0].diet_goal_duration == null) ? '-' : data.Table33[0].diet_goal_duration + ' days') + '</span></p></div><div><p>Suggested Kcal Intake: <span>' + data.Table33[0].kcal + '</span></p></div>';
                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Time</th><th>Food</th><th>Serving</th><th>Instruction</th></tr></thead>';

                            $('#Diet_table_' + data.Table18[0].visit_report_id).html('');
                            $('#Diet_table_' + data.Table18[0].visit_report_id).append(dietplan);
                            $('#Diet_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#diet_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //observed nutrition

                        if (data.Table34.length > 0) {

                            var tr = '';
                            for (var i = 0; i < data.Table34.length; i++) {
                                j++;
                                tr = tr + "<tr><td>" + data.Table34[i].type + "</td><td>" + data.Table34[i].type_name + "</td></tr>";

                            }

                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>Type</th><th>Observed Value</th></tr></thead>';

                            $('#observed_nutrition_table_' + data.Table18[0].visit_report_id).html('');
                            $('#observed_nutrition_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#observed_nutrition_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //future services
                        if (data.Table35.length > 0) {

                            var tr = '';
                            for (var i = 0; i < data.Table35.length; i++) {
                                j++;
                                if (data.Table35[i].base_amount_type == 4) {
                                    var date_time = data.Table35[i].service_date + " " + data.Table35[i].service_time + " - " + data.Table35[i].service_end_date + " " + data.Table35[i].service_end_time;
                                    tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data.Table35[i].service_name + '</td><td>' + data.Table35[i].service_code + '</td><td>' + data.Table35[i].quantity + '</td><td>' + date_time + '</td><td>' + ((data.Table35[i].remarks == '') ? '-' : data.Table35[i].remarks) + '</td></tr>'
                                }
                                else {
                                    var date_time = data.Table35[i].service_date + " " + data.Table35[i].service_time;
                                    tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data.Table35[i].service_name + '</td><td>' + data.Table35[i].service_code + '</td><td>' + data.Table35[i].quantity + '</td><td>' + date_time + '</td><td>' + ((data.Table35[i].remarks == '') ? '-' : data.Table35[i].remarks) + '</td></tr>'
                                }

                            }

                            var table = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless">';
                            var tableend = '</table></div>';
                            var headTable = '<thead style="background: grey;"><tr><th>S.NO</th><th>Service Name</th><th>Service Code</th><th>Quantity</th><th>Date & Time</th><th>Description</th></tr></thead>';

                            $('#future_services_table_' + data.Table18[0].visit_report_id).html('');
                            $('#future_services_table_' + data.Table18[0].visit_report_id).append(table + headTable + tr + tableend);
                        }
                        else {
                            $('#future_services_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        //cbc and urine routine
                        if (data.Table29.length > 0) {
                            if (data.Table29[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>CBC</b></h5></div>';
                            }
                        }

                        if (data.Table29.length > 0) {
                            for (var i = 0; i < data.Table29.length; i++) {
                                if (data.Table29[0].hemoglobin != null && data.Table29[0].hemoglobin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">HEMOGLOBIN</label> : <span>' + data.Table29[0].hemoglobin + " " + ((data.Table29[0].hemoglobin_unit == null || data.Table29[0].hemoglobin_unit == "") ? "" : data.Table29[0].hemoglobin_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].platelet_count != null && data.Table29[0].platelet_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">PLATELET COUNT</label> : <span>' + data.Table29[0].platelet_count + " " + ((data.Table29[0].platelet_count_unit == null || data.Table29[0].platelet_count_unit == "") ? "" : data.Table29[0].platelet_count_unit) + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells != null && data.Table29[0].nucleated_red_blood_cells != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NUCLEATED RED BLOOD CELLS</label> : <span>' + data.Table29[0].nucleated_red_blood_cells + ' </span></div>';
                                }
                                if (data.Table29[0].nucleated_red_blood_cells_percent != null && data.Table29[0].nucleated_red_blood_cells_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NUCLEATED RED BLOOD CELLS %</label> : <span>' + data.Table29[0].nucleated_red_blood_cells_percent + ' </span></div>';
                                }
                                if (data.Table29[0].hematocrit != null && data.Table29[0].hematocrit != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">HEMATOCRIT(PCV)</label> : <span>' + data.Table29[0].hematocrit + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocyte_percent != null && data.Table29[0].lymphocyte_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">LYMPHOCYTE PERCENTAGE</label> : <span>' + data.Table29[0].lymphocyte_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_leucocytes_count != null && data.Table29[0].total_leucocytes_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">TOTAL LEUCOCYTES COUNT</label> : <span>' + data.Table29[0].total_leucocytes_count + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_hemoglobin != null && data.Table29[0].mean_corpuscular_hemoglobin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORPUSCULAR HEMOGLOBIN(MCH)</label> : <span>' + data.Table29[0].mean_corpuscular_hemoglobin + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corp_hemo_conc != null && data.Table29[0].mean_corp_hemo_conc != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORP.HEMO.CONC(MCHC)</label> : <span>' + data.Table29[0].mean_corp_hemo_conc + ' </span></div>';
                                }
                                if (data.Table29[0].mean_corpuscular_volume != null && data.Table29[0].mean_corpuscular_volume != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MEAN CORPUSCULAR VOLUME(MCV)</label> : <span>' + data.Table29[0].mean_corpuscular_volume + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes != null && data.Table29[0].monocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MONOCYTES</label> : <span>' + data.Table29[0].monocytes + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils != null && data.Table29[0].neutrophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NEUTROPHILS</label> : <span>' + data.Table29[0].neutrophils + ' </span></div>';
                                }
                                if (data.Table29[0].eosinophils_absolute_count != null && data.Table29[0].eosinophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">EOSINOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].eosinophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils_absolute_count != null && data.Table29[0].basophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">BASOPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].basophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].lymphocytes_absolute_count != null && data.Table29[0].lymphocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">LYMPHOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].lymphocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].monocytes_absolute_count != null && data.Table29[0].monocytes_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">MONOCYTES - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].monocytes_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].neutrophils_absolute_count != null && data.Table29[0].neutrophils_absolute_count != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NEUTROPHILS - ABSOLUTE COUNT</label> : <span>' + data.Table29[0].neutrophils_absolute_count + ' </span></div>';
                                }
                                if (data.Table29[0].basophils != null && data.Table29[0].basophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">BASOPHILS</label> : <span>' + data.Table29[0].basophils + ' </span></div>';
                                }

                                if (data.Table29[0].eosinophils != null && data.Table29[0].eosinophils != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">EOSINOPHILS</label> : <span>' + data.Table29[0].eosinophils + ' </span></div>';
                                }

                                if (data.Table29[0].immature_granulocytes != null && data.Table29[0].immature_granulocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">IMMATURE GRANULOCYTES(IG)</label> : <span>' + data.Table29[0].immature_granulocytes + ' </span></div>';
                                }
                                if (data.Table29[0].immature_granulocytes_percent != null && data.Table29[0].immature_granulocytes_percent != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">IMMATURE GRANULOCYTE PERCENTAGE(IG%)</label> : <span>' + data.Table29[0].immature_granulocytes_percent + ' </span></div>';
                                }
                                if (data.Table29[0].total_rbc != null && data.Table29[0].total_rbc != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">TOTAL RBC</label> : <span>' + data.Table29[0].total_rbc + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width != null && data.Table29[0].redcell_distribution_width != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">RED CELL DISTRIBUTION WIDTH (RDW-CV)</label> : <span>' + data.Table29[0].redcell_distribution_width + ' </span></div>';
                                }
                                if (data.Table29[0].redcell_distribution_width_sd != null && data.Table29[0].redcell_distribution_width_sd != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">RED CELL DISTRIBUTION WIDTH - SD(RDW-SD)</label> : <span>' + data.Table29[0].redcell_distribution_width_sd + ' </span></div>';
                                }
                            }
                        }

                        if (data.Table30.length > 0) {
                            if (data.Table30[0].visit_report_id != null) {
                                div = div + '<div class="col-md-12"><h5><b>Urine Routine</b></h5></div>';
                            }
                        }
                        if (data.Table30.length > 0) {
                            for (var i = 0; i < data.Table30.length; i++) {
                                if (data.Table30[0].specific_gravity != null && data.Table30[0].specific_gravity != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">SPECIFIC GRAVITY</label> : <span>' + data.Table30[0].specific_gravity + " " + ((data.Table30[0].specific_gravity_unit == null || data.Table30[0].specific_gravity_unit == "") ? "" : data.Table30[0].specific_gravity_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_bilirubin != null && data.Table30[0].urinary_bilirubin != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY BILIRUBIN</label> : <span>' + data.Table30[0].urinary_bilirubin + " " + ((data.Table30[0].urinary_bilirubin_unit == null || data.Table30[0].urinary_bilirubin_unit == "") ? "" : data.Table30[0].urinary_bilirubin_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urine_blood != null && data.Table30[0].urine_blood != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINE BLOOD</label> : <span>' + data.Table30[0].urine_blood + ' </span></div>';
                                }
                                if (data.Table30[0].urobilinogen != null && data.Table30[0].urobilinogen != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">UROBILINOGEN</label> : <span>' + data.Table30[0].urobilinogen + " " + ((data.Table30[0].urobilinogen_unit == null || data.Table30[0].urobilinogen_unit == "") ? "" : data.Table30[0].urobilinogen_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_glucose != null && data.Table30[0].urinary_glucose != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY GLUCOSE</label> : <span>' + data.Table30[0].urinary_glucose + ' </span></div>';
                                }
                                if (data.Table30[0].urine_ketone != null && data.Table30[0].urine_ketone != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINE KETONE</label> : <span>' + data.Table30[0].urine_ketone + " " + ((data.Table30[0].urine_ketone_unit == null || data.Table30[0].urine_ketone_unit == "") ? "" : data.Table30[0].urine_ketone_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_leucocytes != null && data.Table30[0].urinary_leucocytes != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY LEUCOCYTES</label> : <span>' + data.Table30[0].urinary_leucocytes + ' </span></div>';
                                }
                                if (data.Table30[0].nitrite != null && data.Table30[0].nitrite != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">NITRITE</label> : <span>' + data.Table30[0].nitrite + " " + ((data.Table30[0].nitrite_unit == null || data.Table30[0].nitrite_unit == "") ? "" : data.Table30[0].nitrite_unit) + ' </span></div>';
                                }
                                if (data.Table30[0].ph != null && data.Table30[0].ph != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">PH</label> : <span>' + data.Table30[0].ph + ' </span></div>';
                                }
                                if (data.Table30[0].urinary_protein != null && data.Table30[0].urinary_protein != '') {
                                    div = div + '<div class="col-md-4"><label class="control-label">URINARY PROTEIN</label> : <span>' + data.Table30[0].urinary_protein + ' </span></div>';
                                }
                            }
                        }

                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html('');
                        $('#tbl_patient_summary_details_' + data.Table18[0].visit_report_id).html(div);

                        if (data.Table23.length > 0) {
                            var imgtr = '';
                            for (var i = 0; i < data.Table23.length; i++) {
                                var img = '';
                                if (data.Table23[i].patient_lab_record_path == '' || data.Table23[i].patient_lab_record_path == null) {
                                    img = '-';
                                }
                                else {
                                    if (data.Table23[i].record_type == 3) {
                                        img = '<img src=' + $("#hdngetlabfilepath").val() + data.Table23[i].doctor_id + "/PrescriptionWritingPad/" + data.Table23[i].patient_lab_record_path + ' class="img-responsive" style="height: 50px;width: 50px;">';
                                        img = '<a href="' + $('#hdngetlabfilepath').val() + data.Table23[i].doctor_id + "/PrescriptionWritingPad/" + data.Table23[i].patient_lab_record_path + '" target="_blank">' + img + '</a>'
                                    }
                                    else {
                                        img = '<img src=' + $("#hdngetlabfilepath").val() + data.Table23[i].patient_lab_record_path + ' class="img-responsive" style="height: 50px;width: 50px;">';
                                        img = '<a href="' + $('#hdngetlabfilepath').val() + data.Table23[i].patient_lab_record_path + '" target="_blank">' + img + '</a>'
                                    }
                                }
                                debugger;
                                imgtr = imgtr + '<div class="col-xs-3">' + img + '<br/><span style="text-transform:capitalize;">' + ((data.Table23[i].patient_testname != '' && data.Table23[i].patient_testname != null) ? data.Table23[i].patient_testname : 'No file name') + '</span></div>';
                            }
                            $('#tbl-fileupload_' + data.Table23[0].visit_report_id).html('');
                            $('#tbl-fileupload_' + data.Table23[0].visit_report_id).append(imgtr);
                        }
                        else {
                            $('#file_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        if (data.Table24.length > 0) {
                            if (data.Table24[0].NextAppointment != '' && data.Table24[0].NextAppointment != null) {
                                $('#lblNextApp_' + data.Table24[0].visit_report_id).html(data.Table24[0].NextAppointment);
                            }
                            else {
                                $('#divNextApp_' + data.Table18[0].visit_report_id).hide();
                            }

                            if (data.Table24[0].next_appointment_notes != '' && data.Table24[0].next_appointment_notes != null) {
                                $('#lblNextAppNotes_' + data.Table24[0].visit_report_id).html(data.Table24[0].next_appointment_notes);
                            }
                            else {
                                $('#divNextAppNotes_' + data.Table18[0].visit_report_id).hide();
                            }

                            if ((data.Table24[0].NextAppointment == '' || data.Table24[0].NextAppointment == null) && (data.Table24[0].next_appointment_notes == '' || data.Table24[0].next_appointment_notes == null)) {
                                $('#next_div_' + data.Table18[0].visit_report_id).hide();
                            }
                        }
                        else {
                            $('#next_div_' + data.Table18[0].visit_report_id).hide();
                        }

                        $('#summary_div_' + data.Table20[0].visit_report_id).removeClass('us-db-case-loader');
                    }
                    else {
                        $('.tbl_patient_summary_details').html('');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function printpdf(VisitReportID, visitid, patientid, hospitalid, branchid, doctorname, hospitalname, phone_number, email_id) {
    debugger;
    if ($('#HCasesheetPrintType').val() == 0) {
        window.open('/PatientDashboard/PPDF?visitreportid=' + VisitReportID + '&lantype=' + $('#sellang').val() + '&btnval=1', "_blank");
    }
    else {
        //commeted by nandhin for magna
        //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 printpdf(VisitReportID) {   // Added by Antony
//    debugger;

//    var Hpatientid= $('#Hpatientid').val();
//    var Hvisit_reportid = $('#Hvisit_reportid').val();

//    var load_data = {
//        // hospitalid,branchid,patientid,dmlindicator,fromdate,todate,visit_reportid

//        formid: "80",
//        branchid: $('#HBranchID').val(),
//        patientid: Hpatientid,
//        visit_reportid: Hvisit_reportid,
//    }

//    $.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 graph = 1;
function GraphSectionshow() {
    debugger;
    $('#graphdiv').show();
    $('#Ghide').show();
    $('#Gshow').hide();
    if (graph == 1) {
        observationgraph();
        graph++;
    }

}
function GraphSectionhide() {
    $('#graphdiv').hide();
    $('#Ghide').hide();
    $('#Gshow').show();
}

function observationgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'OB',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                console.log(data);
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    debugger;
                    if (Object.keys(data).length > 0) {
                        var bp_max = '<th>diastolic</th>', bp_min = '<th>systolic</th>', Parameters = '<th>Parameters</th>', Hpulse_rate = '<th>Pulse</th>', Hspo2 = '<th>SPO2</th>', Hhypoglycemia_episodes = '<th>Hypoglycemic Episodes</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var patient_bp_max = '-', patient_bp_min = '-', pulse_rate = '-', spo2 = '-', hypoglycemia_episodes = '-';
                                if (data.Table[i].patient_bp_max != null && data.Table[i].patient_bp_max != '') {
                                    patient_bp_max = data.Table[i].patient_bp_max + ' mmHg';
                                }
                                if (data.Table[i].patient_bp_min != null && data.Table[i].patient_bp_min != '') {
                                    patient_bp_min = data.Table[i].patient_bp_min + ' mmHg';
                                }
                                if (data.Table[i].pulse_rate != null && data.Table[i].pulse_rate != '') {
                                    pulse_rate = data.Table[i].pulse_rate + ' /min';
                                }
                                if (data.Table[i].spo2 != null && data.Table[i].spo2 != '') {
                                    spo2 = data.Table[i].spo2 + ' %';
                                }
                                if (data.Table[i].hypoglycemia_episodes != null && data.Table[i].hypoglycemia_episodes != '') {
                                    hypoglycemia_episodes = data.Table[i].hypoglycemia_episodes + ' /week';
                                }
                                bp_max = bp_max + '<td>' + patient_bp_max + '</td>';
                                bp_min = bp_min + '<td>' + patient_bp_min + '</td>';
                                Hpulse_rate = Hpulse_rate + '<td>' + pulse_rate + '</td>';
                                Hspo2 = Hspo2 + '<td>' + spo2 + '</td>';
                                Hhypoglycemia_episodes = Hhypoglycemia_episodes + '<td>' + hypoglycemia_episodes + '</td>';
                            }
                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + bp_max + trend + trstart + bp_min + trend + trstart + Hpulse_rate + trend + trstart + Hspo2 + trend + trstart + Hhypoglycemia_episodes + trend + tbodyend
                            $('#tbl_observation').html(result);
                        }
                        if (data.Table.length > 0) {
                            var bp_max = [], bp_min = [], pulse_rate = [], spo2 = [], hypoglycemia_episodes = [], maxDate = [], minDate = [], pulseDate = [], spo2Date = [], hypoglycemiaDate = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].patient_bp_max != '' && data.Table[i].patient_bp_max != null && data.Table[i].patient_bp_max != 0) {
                                    bp_max.push(data.Table[i].patient_bp_max);
                                    maxDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_bp_min != '' && data.Table[i].patient_bp_min != null && data.Table[i].patient_bp_min != 0) {
                                    bp_min.push(data.Table[i].patient_bp_min);
                                    minDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].pulse_rate != '' && data.Table[i].pulse_rate != null && data.Table[i].pulse_rate != 0) {
                                    pulse_rate.push(data.Table[i].pulse_rate);
                                    pulseDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].spo2 != '' && data.Table[i].spo2 != null && data.Table[i].spo2 != 0) {
                                    spo2.push(data.Table[i].spo2);
                                    spo2Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].hypoglycemia_episodes != '' && data.Table[i].hypoglycemia_episodes != null && data.Table[i].hypoglycemia_episodes != 0) {
                                    hypoglycemia_episodes.push(data.Table[i].hypoglycemia_episodes);
                                    hypoglycemiaDate.push(data.Table[i].VDate);
                                }
                            }
                            bp_max = bp_max.reverse();
                            console.log(bp_max);
                            bp_min = bp_min.reverse();
                            maxDate = maxDate.reverse();
                            pulse_rate = pulse_rate.reverse();
                            pulseDate = pulseDate.reverse();
                            spo2 = spo2.reverse();
                            spo2Date = spo2Date.reverse();
                            hypoglycemia_episodes = hypoglycemia_episodes.reverse();
                            hypoglycemiaDate = hypoglycemiaDate.reverse();
                            if (bp_max.length > 0 || bp_min > 0) {
                                graph2(bp_max, bp_min, maxDate, 'ghydiastolic', 'Systolic', 'Diastolic');
                            }
                            else {
                                $('#divghydiastolic').hide();
                            }
                            if (pulse_rate.length > 0) {
                                graph1(pulse_rate, pulseDate, 'ghyPulse', 'Pulse');
                            }
                            else {
                                $('#divghyPulse').hide();
                            }
                            if (spo2.length > 0) {
                                graph1(spo2, spo2Date, 'ghySPO2', 'SPO2');
                            }
                            else {
                                $('#divghySPO2').hide();
                            }
                            if (hypoglycemia_episodes.length > 0) {
                                graph1(hypoglycemia_episodes, hypoglycemiaDate, 'ghyhypoglycemicepisodes', 'hypoglycemia Episodes');
                            }
                            else {
                                $('#divghyhypoglycemicepisodes').hide();
                            }
                        }
                    }
                    Glycemicgraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function Glycemicgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'GL',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {
                        var Parameters = '<th>Parameters</th>', HHbA1c = '<th>HbA1c</th>', HFastingInsulin = '<th>Fasting Insulin</th>', HHB = '<th>HB</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var patient_hbac_record_value = '-', fasting_insulin = '-', hemoglobin = '-';
                                if (data.Table[i].patient_hbac_record_value != null && data.Table[i].patient_hbac_record_value != '') {
                                    patient_hbac_record_value = data.Table[i].patient_hbac_record_value + ' %';
                                }
                                if (data.Table[i].fasting_insulin != null && data.Table[i].fasting_insulin != '') {
                                    var unit = ' mlU/L';
                                    if (data.Table[i].fasting_inslin_unit == 2) {
                                        unit = ' pmol/L'
                                    }
                                    fasting_insulin = data.Table[i].fasting_insulin + unit;
                                }
                                if (data.Table[i].hemoglobin != null && data.Table[i].hemoglobin != '') {
                                    hemoglobin = data.Table[i].hemoglobin + ' gms';
                                }
                                HHbA1c = HHbA1c + '<td>' + patient_hbac_record_value + '</td>';
                                HFastingInsulin = HFastingInsulin + '<td>' + fasting_insulin + '</td>';
                                HHB = HHB + '<td>' + hemoglobin + '</td>';
                            }
                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + HHbA1c + trend + trstart + HFastingInsulin + trend + trstart + HHB + trend + tbodyend;
                            $('#tbl_Glycemic').html(result);
                        }
                        if (data.Table.length > 0) {
                            var HbA1c = [], fasting_insulin = [], hemoglobin = [], HbA1cDate = [], fasting_insulinDate = [], hemoglobinDate = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].patient_hbac_record_value != '' && data.Table[i].patient_hbac_record_value != null && data.Table[i].patient_hbac_record_value != 0) {
                                    HbA1c.push(data.Table[i].patient_hbac_record_value);
                                    HbA1cDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].fasting_insulin != '' && data.Table[i].fasting_insulin != null && data.Table[i].fasting_insulin != 0) {
                                    fasting_insulin.push(data.Table[i].fasting_insulin);
                                    fasting_insulinDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].hemoglobin != '' && data.Table[i].hemoglobin != null && data.Table[i].hemoglobin != 0) {
                                    hemoglobin.push(data.Table[i].hemoglobin);
                                    hemoglobinDate.push(data.Table[i].VDate);
                                }
                            }
                            HbA1c = HbA1c.reverse();
                            HbA1cDate = HbA1cDate.reverse();
                            fasting_insulin = fasting_insulin.reverse();
                            fasting_insulinDate = fasting_insulinDate.reverse();
                            hemoglobin = hemoglobin.reverse();
                            hemoglobinDate = hemoglobinDate.reverse();

                            if (HbA1c.length > 0) {
                                graph1(HbA1c, HbA1cDate, 'ghyHbA1c', 'HbA1c');
                            }
                            else {
                                $('#divghyHbA1c').hide();
                            }
                            if (fasting_insulin.length > 0) {
                                graph1(fasting_insulin, fasting_insulinDate, 'ghyfasting_insulinDate', 'Fasting Insulin');
                            }
                            else {
                                $('#divghyfasting_insulinDate').hide();
                            }
                            if (hemoglobin.length > 0) {
                                graph1(hemoglobin, hemoglobinDate, 'ghyHB', 'HB');
                            }
                            else {
                                $('#divghyHB').hide();
                            }
                        }
                    }
                    bloodgraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function bloodgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'SU',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        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 (Object.keys(data).length > 0) {

                        if (data.Table.length > 0) {
                            var su1 = [], su1Date = [], su2 = [], su2Date = [], su3 = [], su3Date = [], su4 = [], su4Date = [], su5 = [], su5Date = [], su6 = [], su6Date = [], su7 = [], su7Date = [], su8 = [], su8Date = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 1) {
                                    su1.push(data.Table[i].patient_blood_sugar_value);
                                    su1Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 2) {
                                    su2.push(data.Table[i].patient_blood_sugar_value);
                                    su2Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 3) {
                                    su3.push(data.Table[i].patient_blood_sugar_value);
                                    su3Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 4) {
                                    su4.push(data.Table[i].patient_blood_sugar_value);
                                    su4Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 5) {
                                    su5.push(data.Table[i].patient_blood_sugar_value);
                                    su5Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 6) {
                                    su6.push(data.Table[i].patient_blood_sugar_value);
                                    su6Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 7) {
                                    su7.push(data.Table[i].patient_blood_sugar_value);
                                    su7Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].patient_blood_sugar_value != '' && data.Table[i].patient_blood_sugar_value != null && data.Table[i].patient_blood_sugar_value != 0 && data.Table[i].patient_blood_sugar_type == 8) {
                                    su8.push(data.Table[i].patient_blood_sugar_value);
                                    su8Date.push(data.Table[i].VDate);
                                }
                            }
                            if (su1.length > 0) {
                                graph1(su1, su1Date, 'ghybs1', 'Fasting blood sugar');
                            }
                            else {
                                $('#divghybs1').hide();
                            }
                            if (su2.length > 0) {
                                graph1(su2, su2Date, 'ghybs2', 'Postprandial blood sugar');
                            }
                            else {
                                $('#divghybs2').hide();
                            }
                            if (su3.length > 0) {
                                graph1(su3, su3Date, 'ghybs3', 'Random blood sugar');
                            }
                            else {
                                $('#divghybs3').hide();
                            }
                            if (su4.length > 0) {
                                graph1(su4, su4Date, 'ghybs4', 'Before Lunch BS');
                            }
                            else {
                                $('#divghybs4').hide();
                            }
                            if (su5.length > 0) {
                                graph1(su5, su5Date, 'ghybs5', 'Before Dinner BS');
                            }
                            else {
                                $('#divghybs5').hide();
                            }
                            if (su6.length > 0) {
                                graph1(su6, su6Date, 'ghybs6', '3 Am BS');
                            }
                            else {
                                $('#divghybs6').hide();
                            }
                            if (su7.length > 0) {
                                graph1(su7, su7Date, 'ghybs7', 'After Lunch BS');
                            }
                            else {
                                $('#divghybs7').hide();
                            }
                            if (su8.length > 0) {
                                graph1(su8, su8Date, 'ghybs8', 'After Dinner BS');
                            }
                            else {
                                $('#divghybs8').hide();
                            }
                        }
                    }
                    renalgraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function renalgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'RE',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {
                        var Parameters = '<th>Parameters</th>', HUrea = '<th>Urea</th>', HCreatinine = '<th>Creatinine</th>', HEGFR = '<th>EGFR</th>', HSodium = '<th>Sodium( Na )</th>',
                            HPotassium = '<th>Potassium( k )</th>', HChlorine = '<th>Chloride( Cl )</th>', HBiCarbonate = '<th>BiCarbonate( HCO3 )</th>', HCalcium = '<th>Calcium( Ca )</th>',
                            HPhosphorus = '<th>Phosphorus( P )</th>', HMagnesium = '<th>Magnesium( Mg )</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var Urea = '-', Creatinine = '-', EGFR = '-', Sodium = '-', Potassium = '-', Chlorine = '-', BiCarbonate = '-', Calcium = '-', Phosphorus = '-', Magnesium = '-';

                                if (data.Table[i].Urea != null && data.Table[i].Urea != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].urea_unit == 2) {
                                        Unit = ' mg/dL';
                                    }
                                    Urea = data.Table[i].Urea + Unit;
                                }
                                if (data.Table[i].creatinine != null && data.Table[i].creatinine != '') {
                                    var unit = ' µmol/L';
                                    if (data.Table[i].Creatinine == 2) {
                                        unit = ' mg/dL'
                                    }
                                    Creatinine = data.Table[i].creatinine + unit;
                                }
                                if (data.Table[i].egfr_value != null && data.Table[i].egfr_value != '') {
                                    EGFR = data.Table[i].egfr_value + ' gms';
                                }
                                if (data.Table[i].Sodium != null && data.Table[i].Sodium != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].sodium_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Sodium = data.Table[i].Sodium + Unit;
                                }
                                if (data.Table[i].Potassium != null && data.Table[i].Potassium != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].potassium_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Potassium = data.Table[i].Potassium + Unit;
                                }

                                if (data.Table[i].Chlorine != null && data.Table[i].Chlorine != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].chlorine_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Chlorine = data.Table[i].Chlorine + Unit;
                                }

                                if (data.Table[i].BiCarbonate != null && data.Table[i].BiCarbonate != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].Bicarbonate_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    BiCarbonate = data.Table[i].BiCarbonate + Unit;
                                }

                                if (data.Table[i].serium_calcium != null && data.Table[i].serium_calcium != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].Calcium_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Calcium = data.Table[i].serium_calcium + Unit;
                                }

                                if (data.Table[i].serium_phosphorous != null && data.Table[i].serium_phosphorous != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].Phosphorus_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Phosphorus = data.Table[i].serium_phosphorous + Unit;
                                }

                                if (data.Table[i].serium_magnesium != null && data.Table[i].serium_magnesium != '') {
                                    var Unit = ' mmol/L';
                                    if (data.Table[i].Magnesium_unit == 2) {
                                        Unit = ' mEq/L';
                                    }
                                    Magnesium = data.Table[i].serium_magnesium + Unit;
                                }

                                HUrea = HUrea + '<td>' + Urea + '</td>';
                                HCreatinine = HCreatinine + '<td>' + Creatinine + '</td>';
                                HEGFR = HEGFR + '<td>' + EGFR + '</td>';
                                HSodium = HSodium + '<td>' + Sodium + '</td>';
                                HPotassium = HPotassium + '<td>' + Potassium + '</td>';
                                HChlorine = HChlorine + '<td>' + Chlorine + '</td>';
                                HBiCarbonate = HBiCarbonate + '<td>' + BiCarbonate + '</td>';
                                HCalcium = HCalcium + '<td>' + Calcium + '</td>';
                                HPhosphorus = HPhosphorus + '<td>' + Phosphorus + '</td>';
                                HMagnesium = HMagnesium + '<td>' + Magnesium + '</td>';
                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + HUrea + trend + trstart + HCreatinine + trend + trstart + HEGFR + trend
                                + trstart + HSodium + trend + trstart + HPotassium + trend + trstart + HChlorine + trend + trstart + HBiCarbonate + trend
                                + trstart + HCalcium + trend + trstart + HPhosphorus + trend + trstart + HMagnesium + trend + tbodyend;
                            $('#tbl_renal').html(result);
                        }
                        if (data.Table.length > 0) {
                            var Urea = [], UreaDate = [], creatinine = [], creatinineDate = [], EGFR = [], EGFRDate = [], Sodium = [], SodiumDate = [],
                                Potassium = [], PotassiumDate = [], Chlorine = [], ChlorineDate = [], BiCarbonate = [], BiCarbonateDate = [], Calcium = [], CalciumDate = []
                            Phosphorus = [], PhosphorusDate = [], Magnesium = [], MagnesiumDate = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].Urea != '' && data.Table[i].Urea != null && data.Table[i].Urea != 0) {
                                    Urea.push(data.Table[i].Urea);
                                    UreaDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].creatinine != '' && data.Table[i].creatinine != null && data.Table[i].creatinine != 0) {
                                    creatinine.push(data.Table[i].creatinine);
                                    creatinineDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].egfr_value != '' && data.Table[i].egfr_value != null && data.Table[i].egfr_value != 0) {
                                    EGFR.push(data.Table[i].egfr_value);
                                    EGFRDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].Sodium != '' && data.Table[i].Sodium != null && data.Table[i].Sodium != 0) {
                                    Sodium.push(data.Table[i].Sodium);
                                    SodiumDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].Potassium != '' && data.Table[i].Potassium != null && data.Table[i].Potassium != 0) {
                                    Potassium.push(data.Table[i].Potassium);
                                    PotassiumDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].Chlorine != '' && data.Table[i].Chlorine != null && data.Table[i].Chlorine != 0) {
                                    Chlorine.push(data.Table[i].Chlorine);
                                    ChlorineDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].BiCarbonate != '' && data.Table[i].BiCarbonate != null && data.Table[i].BiCarbonate != 0) {
                                    BiCarbonate.push(data.Table[i].BiCarbonate);
                                    BiCarbonateDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].serium_calcium != '' && data.Table[i].serium_calcium != null && data.Table[i].serium_calcium != 0) {
                                    Calcium.push(data.Table[i].serium_calcium);
                                    CalciumDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].serium_phosphorous != '' && data.Table[i].serium_phosphorous != null && data.Table[i].serium_phosphorous != 0) {
                                    Phosphorus.push(data.Table[i].serium_phosphorous);
                                    PhosphorusDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].serium_magnesium != '' && data.Table[i].serium_magnesium != null && data.Table[i].serium_magnesium != 0) {
                                    Magnesium.push(data.Table[i].serium_magnesium);
                                    MagnesiumDate.push(data.Table[i].VDate);
                                }
                            }
                            Urea = Urea.reverse();
                            UreaDate = UreaDate.reverse();
                            creatinine = creatinine.reverse();
                            creatinineDate = creatinineDate.reverse();
                            EGFR = EGFR.reverse();
                            EGFRDate = EGFRDate.reverse();
                            Sodium = Sodium.reverse();
                            SodiumDate = SodiumDate.reverse();
                            Potassium = Potassium.reverse();
                            PotassiumDate = PotassiumDate.reverse();
                            Chlorine = Chlorine.reverse();
                            ChlorineDate = ChlorineDate.reverse();
                            BiCarbonate = BiCarbonate.reverse();
                            BiCarbonateDate = BiCarbonateDate.reverse();
                            Calcium = Calcium.reverse();
                            CalciumDate = CalciumDate.reverse();
                            Phosphorus = Phosphorus.reverse();
                            PhosphorusDate = PhosphorusDate.reverse();
                            Magnesium = Magnesium.reverse();
                            MagnesiumDate = MagnesiumDate.reverse();

                            if (Urea.length > 0) {
                                graph1(Urea, UreaDate, 'ghyUrea', 'Urea');
                            }
                            else {
                                $('#divghyUrea').hide();
                            }
                            if (creatinine.length > 0) {
                                graph1(creatinine, creatinineDate, 'ghyCreatinine', 'Creatinine');
                            }
                            else {
                                $('#divghyCreatinine').hide();
                            }
                            if (EGFR.length > 0) {
                                graph1(EGFR, EGFRDate, 'ghyEGFR', 'EGFR ( Calculated )');
                            }
                            else {
                                $('#divghyEGFR').hide();
                            }
                            if (Sodium.length > 0) {
                                graph1(Sodium, SodiumDate, 'ghySodium', 'Sodium( Na )');
                            }
                            else {
                                $('#divghySodium').hide();
                            }
                            if (Potassium.length > 0) {
                                graph1(Potassium, PotassiumDate, 'ghyPotassium', 'Potassium( k )');
                            }
                            else {
                                $('#divghyPotassium').hide();
                            }
                            if (Chlorine.length > 0) {
                                graph1(Chlorine, ChlorineDate, 'ghyChloride', 'Chloride( Cl )');
                            }
                            else {
                                $('#divghyChloride').hide();
                            }
                            if (BiCarbonate.length > 0) {
                                graph1(BiCarbonate, BiCarbonateDate, 'ghyBiCarbonate', 'BiCarbonate( HCO3 )');
                            }
                            else {
                                $('#divghyBiCarbonate').hide();
                            }
                            if (Calcium.length > 0) {
                                graph1(Calcium, CalciumDate, 'ghyCalcium', 'Calcium( Ca )');
                            }
                            else {
                                $('#divghyCalcium').hide();
                            }
                            if (Phosphorus.length > 0) {
                                graph1(Phosphorus, PhosphorusDate, 'ghyPhosphorus', 'Phosphorus( P )');
                            }
                            else {
                                $('#divghyPhosphorus').hide();
                            }
                            if (Magnesium.length > 0) {
                                graph1(Magnesium, MagnesiumDate, 'ghyMagnesium', 'Magnesium( Mg )');
                            }
                            else {
                                $('#divghyMagnesium').hide();
                            }
                        }
                    }
                    cholesterolgraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


function cholesterolgraph() {

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

                }
                else {
                    if (Object.keys(data).length > 0) {
                        var Parameters = '<th>Parameters</th>', HTotalCholesterol = '<th>Total Cholesterol</th>', HLDL = '<th>LDL (Low Density Lipoproteins)</th>', HHDL = '<th>HDL (High Density Lipoproteins)</th>',
                            HVLDL = '<th>VLDL</th>', HTriglycerides = '<th>Triglycerides</th>', HHDLRatio = '<th>Total Cholesterol : HDL Ratio</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var TotalCholesterol = '-', LDL = '-', HDL = '-', VLDL = '-', Triglycerides = '-', HDLRatio = '-';
                                if (data.Table[i].Total_Cholestrol != null && data.Table[i].Total_Cholestrol != '') {
                                    var unit = ' mg/dL';
                                    if (data.Table[i].Total_cholestrol_unit == 2) {
                                        unit = ' mmol/L'
                                    }
                                    TotalCholesterol = data.Table[i].Total_Cholestrol + unit;
                                }

                                if (data.Table[i].LDL != null && data.Table[i].LDL != '') {
                                    var unit = ' mg/dL';
                                    if (data.Table[i].LDL_unit == 2) {
                                        unit = ' mmol/L'
                                    }
                                    LDL = data.Table[i].LDL + unit;
                                }

                                if (data.Table[i].HDL != null && data.Table[i].HDL != '') {
                                    var unit = ' mg/dL';
                                    if (data.Table[i].HDL_unit == 2) {
                                        unit = ' mmol/L'
                                    }
                                    HDL = data.Table[i].HDL + unit;
                                }

                                if (data.Table[i].VLDL != null && data.Table[i].VLDL != '') {
                                    var unit = ' mg/dL';
                                    if (data.Table[i].VLDL_unit == 2) {
                                        unit = ' mmol/L'
                                    }
                                    VLDL = data.Table[i].VLDL + unit;
                                }

                                if (data.Table[i].Triglycerides != null && data.Table[i].Triglycerides != '') {
                                    var unit = ' mg/dL';
                                    if (data.Table[i].Triglycerides_unit == 2) {
                                        unit = ' mmol/L'
                                    }
                                    Triglycerides = data.Table[i].Triglycerides + unit;
                                }

                                if (data.Table[i].T_cholestrol_Hdl_ratio != null && data.Table[i].T_cholestrol_Hdl_ratio != '') {

                                    HDLRatio = data.Table[i].T_cholestrol_Hdl_ratio;
                                }

                                HTotalCholesterol = HTotalCholesterol + '<td>' + TotalCholesterol + '</td>';
                                HLDL = HLDL + '<td>' + LDL + '</td>';
                                HHDL = HHDL + '<td>' + HDL + '</td>';
                                HVLDL = HVLDL + '<td>' + VLDL + '</td>';
                                HTriglycerides = HTriglycerides + '<td>' + Triglycerides + '</td>';
                                HHDLRatio = HHDLRatio + '<td>' + HDLRatio + '</td>';
                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + HTotalCholesterol + trend + trstart + HLDL + trend + trstart + HHDL + trend +
                                trstart + HVLDL + trend + trstart + HTriglycerides + trend + trstart + HHDLRatio + trend + tbodyend;
                            $('#tbl_cholestrol').html(result);
                        }
                        if (data.Table.length > 0) {
                            var TotalCholesterol = [], TotalCholesterolDate = [], LDL = [], LDLDate = [], HDL = [], HDLDate = []
                            VLDL = [], VLDLDate = [], Triglycerides = [], TriglyceridesDate = [], HDLRatio = [], HDLRatioDate = [];

                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].patient_hbac_record_value != '' && data.Table[i].patient_hbac_record_value != null && data.Table[i].patient_hbac_record_value != 0) {
                                    TotalCholesterol.push(data.Table[i].Total_Cholestrol);
                                    TotalCholesterolDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].LDL != '' && data.Table[i].LDL != null && data.Table[i].LDL != 0) {
                                    LDL.push(data.Table[i].LDL);
                                    LDLDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].HDL != '' && data.Table[i].HDL != null && data.Table[i].HDL != 0) {
                                    HDL.push(data.Table[i].HDL);
                                    HDLDate.push(data.Table[i].VDate);
                                }

                                if (data.Table[i].VLDL != '' && data.Table[i].VLDL != null && data.Table[i].VLDL != 0) {
                                    VLDL.push(data.Table[i].VLDL);
                                    VLDLDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].Triglycerides != '' && data.Table[i].Triglycerides != null && data.Table[i].Triglycerides != 0) {
                                    Triglycerides.push(data.Table[i].Triglycerides);
                                    TriglyceridesDate.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].T_cholestrol_Hdl_ratio != '' && data.Table[i].T_cholestrol_Hdl_ratio != null && data.Table[i].T_cholestrol_Hdl_ratio != 0) {
                                    HDLRatio.push(data.Table[i].T_cholestrol_Hdl_ratio);
                                    HDLRatioDate.push(data.Table[i].VDate);
                                }
                            }
                            TotalCholesterol = TotalCholesterol.reverse();
                            TotalCholesterolDate = TotalCholesterolDate.reverse();
                            LDL = LDL.reverse();
                            LDLDate = LDLDate.reverse();
                            HDL = HDL.reverse();
                            HDLDate = HDLDate.reverse();
                            VLDL = VLDL.reverse();
                            VLDLDate = VLDLDate.reverse();
                            Triglycerides = Triglycerides.reverse();
                            TriglyceridesDate = TriglyceridesDate.reverse();
                            HDLRatio = HDLRatio.reverse();
                            HDLRatioDate = HDLRatioDate.reverse();

                            if (TotalCholesterol.length > 0) {
                                graph1(TotalCholesterol, TotalCholesterolDate, 'ghyTotalCholesterol', 'Total Cholesterol');
                            }
                            else {
                                $('#divghyTotalCholesterol').hide();
                            }
                            if (LDL.length > 0) {
                                graph1(LDL, LDLDate, 'ghyLDL', 'LDL (Low Density Lipoproteins)');
                            }
                            else {
                                $('#divghyLDL').hide();
                            }
                            if (HDL.length > 0) {
                                graph1(HDL, HDLDate, 'ghyHDL', 'HDL (High Density Lipoproteins)');
                            }
                            else {
                                $('#divghyHDL').hide();
                            }
                            if (VLDL.length > 0) {
                                graph1(VLDL, VLDLDate, 'ghyVLDL', 'VLDL');
                            }
                            else {
                                $('#divghyVLDL').hide();
                            }
                            if (Triglycerides.length > 0) {
                                graph1(Triglycerides, TriglyceridesDate, 'ghyTriglycerides', 'Triglycerides');
                            }
                            else {
                                $('#divghyTriglycerides').hide();
                            }
                            if (HDLRatio.length > 0) {
                                graph1(HDLRatio, HDLRatioDate, 'ghyHDLRatio', 'Total Cholesterol : HDL Ratio');
                            }
                            else {
                                $('#divghyHDLRatio').hide();
                            }
                        }
                    }
                    Cardiacgraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

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

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

function Cardiacgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'CA',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {
                        var Parameters = '<th>Parameters</th>', HEjectionFraction = '<th>Ejection Fraction</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var EjectionFraction = '-';
                                if (data.Table[i].fraction != null && data.Table[i].fraction != '') {
                                    EjectionFraction = data.Table[i].fraction;
                                }
                                HEjectionFraction = HEjectionFraction + '<td>' + EjectionFraction + '</td>';
                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + HEjectionFraction + trend + tbodyend;
                            $('#tbl_cardiac').html(result);
                        }
                        if (data.Table.length > 0) {
                            var EjectionFraction = [], EjectionFractionDate = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].fraction != '' && data.Table[i].fraction != null && data.Table[i].fraction != 0) {
                                    EjectionFraction.push(data.Table[i].fraction);
                                    EjectionFractionDate.push(data.Table[i].VDate);
                                }
                            }
                            EjectionFraction = EjectionFraction.reverse();
                            EjectionFractionDate = EjectionFractionDate.reverse();
                            if (EjectionFraction.length > 0) {
                                graph1(EjectionFraction, EjectionFractionDate, 'ghyEjectionFraction', 'Ejection Fraction');
                            }
                            else {
                                $('#divghyEjectionFraction').hide();
                            }
                        }
                    }
                    Thyroidgraph();

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




function Thyroidgraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'TH',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {
                        var Parameters = '<th>Parameters</th>', HT3 = '<th>Free T3</th>', HT4 = '<th>Free T4</th>', HTSH = '<th>TSH</th>', HN_T3 = '<th>T3</th>', HN_T4 = '<th>T4</th>';
                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>'
                                var T3 = '-', T4 = '-', TSH = '-', N_T3 = '-', N_T4 = '-';
                                if (data.Table[i].Free_T3 != null && data.Table[i].Free_T3 != '') {
                                    T3 = data.Table[i].Free_T3 + ' Pg/dL';
                                }
                                if (data.Table[i].Free_T4 != null && data.Table[i].Free_T4 != '') {
                                    T4 = data.Table[i].Free_T4 + ' ng/dL';
                                }
                                if (data.Table[i].TSH != null && data.Table[i].TSH != '') {
                                    TSH = data.Table[i].TSH + ' mIU/mL';
                                }
                                if (data.Table[i].T3 != null && data.Table[i].T3 != '') {
                                    N_T3 = data.Table[i].T3 + ' Pg/dL';
                                }
                                if (data.Table[i].T4 != null && data.Table[i].T4 != '') {
                                    N_T4 = data.Table[i].T4 + ' ng/dL';
                                }

                                HT3 = HT3 + '<td>' + T3 + '</td>';
                                HT4 = HT4 + '<td>' + T4 + '</td>';
                                HN_T3 = HN_T3 + '<td>' + N_T3 + '</td>';
                                HN_T4 = HN_T4 + '<td>' + N_T4 + '</td>';
                                HTSH = HTSH + '<td>' + TSH + '</td>';
                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + HT3 + trend + trstart + HT4 + trend + trstart + HN_T3 + trend + trstart + HN_T4 + trend + trstart + HTSH + trend + tbodyend;
                            $('#tbl_thyroid').html(result);
                        }
                        if (data.Table.length > 0) {
                            var T3 = [], T3Date = [], T4 = [], T4Date = [], TSH = [], TSHDate = [], N_T3 = [], N_T3Date = [], N_T4 = [], N_T4Date = [];
                            for (var i = 0; i < data.Table.length; i++) {
                                if (data.Table[i].Free_T3 != '' && data.Table[i].Free_T3 != null && data.Table[i].Free_T3 != 0) {
                                    T3.push(data.Table[i].Free_T3);
                                    T3Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].Free_T4 != '' && data.Table[i].Free_T4 != null && data.Table[i].Free_T4 != 0) {
                                    T4.push(data.Table[i].Free_T4);
                                    T4Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].T3 != '' && data.Table[i].T3 != null && data.Table[i].T3 != 0) {
                                    N_T3.push(data.Table[i].T3);
                                    N_T3Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].T4 != '' && data.Table[i].T4 != null && data.Table[i].T4 != 0) {
                                    N_T4.push(data.Table[i].T4);
                                    N_T4Date.push(data.Table[i].VDate);
                                }
                                if (data.Table[i].TSH != '' && data.Table[i].TSH != null && data.Table[i].TSH != 0) {
                                    TSH.push(data.Table[i].TSH);
                                    TSHDate.push(data.Table[i].VDate);
                                }
                            }
                            T3 = T3.reverse();
                            T3Date = T3Date.reverse();
                            T4 = T4.reverse();
                            T4Date = T4Date.reverse();
                            N_T3 = N_T3.reverse();
                            N_T3Date = N_T3Date.reverse();
                            N_T4 = N_T4.reverse();
                            N_T4Date = N_T4Date.reverse();
                            TSH = TSH.reverse();
                            TSHDate = TSHDate.reverse();

                            if (T3.length > 0) {
                                graph1(T3, T3Date, 'ghyT3', 'Free T3');
                            }
                            else {
                                $('#divghyT3').hide();
                            }
                            if (T4.length > 0) {
                                graph1(T4, T4Date, 'ghyT4', 'Free T4');
                            }
                            else {
                                $('#divghyT4').hide();
                            }
                            if (N_T3.length > 0) {
                                graph1(N_T3, T3Date, 'ghyNT3', 'T3');
                            }
                            else {
                                $('#divghyNT3').hide();
                            }
                            if (N_T4.length > 0) {
                                graph1(N_T4, T4Date, 'ghyNT4', 'T4');
                            }
                            else {
                                $('#divghyNT4').hide();
                            }
                            if (TSH.length > 0) {
                                graph1(TSH, TSHDate, 'ghyTSH', 'TSH');
                            }
                            else {
                                $('#divghyTSH').hide();
                            }
                        }
                    }
                    //observed_nutrition_graph();
                    CBCGraph();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}



//load cbc graph
function CBCGraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'CS',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {

                        var Parameters = '<th>Parameters</th>', hemoglobin = '<th>HEMOGLOBIN</th>', plateletCount = '<th>PLATELET COUNT</th>',
                            nucleatedRedBlood = '<th>NUCLEATED RED BLOOD CELLS</th>', nucleatedBloodCellPercent = '<th>NUCLEATED RED BLOOD CELLS (%)</th>', hematocrit = '<th>HEMATOCRIT(PCV)</th>',
                            lympocytePercent = '<th>LYMPHOCYTE PERCENTAGE</th>', totalLeucocytes = '<th>TOTAL LEUCOCYTES COUNT</th>', meanCorpuscular = '<th>MEAN CORPUSCULAR HEMOGLOBIN(MCH)</th>', meanCorpHemo = '<th>MEAN CORP.HEMO.CONC(MCHC)</th>', meanCorpuscularVolume = '<th>MEAN CORPUSCULAR VOLUME(MCV)</th>',
                            monocytes = '<th>MONOCYTES</th>', neutrophils = '<th>NEUTROPHILS</th>', eosinophilsCount = '<th>EOSINOPHILS - ABSOLUTE COUNT</th>',
                            basophilsCount = '<th>BASOPHILS - ABSOLUTE COUNT</th>', lymphocytesCount = '<th>LYMPHOCYTES - ABSOLUTE COUNT</th>', monocytesCount = '<th>MONOCYTES - ABSOLUTE COUNT</th>',
                            neutrophilsCount = '<th>NEUTROPHILS - ABSOLUTE COUNT</th>', basophils = '<th>BASOPHILS</th>', eosinophils = '<th>EOSINOPHILS</th>', immaturegranulo = '<th>IMMATURE GRANULOCYTES(IG)</th>',
                            immatureGranuloPercent = '<th>IMMATURE GRANULOCYTE PERCENTAGE(IG%)</th>', totalRBC = '<th>TOTAL RBC</th>', redCell = '<th>RED CELL DISTRIBUTION WIDTH (RDW-CV)</th>', redCellDistribution = '<th>RED CELL DISTRIBUTION WIDTH - SD(RDW-SD)</th>';

                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>';

                                var hemoglobinValue = '-', plateletCountValue = '-', nucleatedRedBloodValue = '-', nucleatedBloodCellPercentValue = '-',
                                    hematocritValue = '-', lympocytePercentValue = '-', totalLeucocytesValue = '-', meanCorpuscularValue = '-', meanCorpHemoValue = '-', meanCorpuscularVolumeValue = '-',
                                    monocytesValue = '-', neutrophilsValue = '-', eosinophilsCountValue = '-', basophilsCountValue = '-', lymphocytesCountValue = '-',
                                    monocytesCountValue = '-', neutrophilsCountValue = '-', basophilsValue = '-', eosinophilsValue = '-', immaturegranuloValue = '-',
                                    immatureGranuloPercentValue = '-', totalRBCValue = '-', redCellValue = '-', redCellDistributionValue = '-';


                                if (data.Table[i].hemoglobin != null && data.Table[i].hemoglobin != '') {
                                    hemoglobinValue = data.Table[i].hemoglobin + ' ' + (data.Table[i].hemoglobin_unit == null || data.Table[i].hemoglobin_unit == "" ? "" : data.Table[i].hemoglobin_unit);
                                }
                                if (data.Table[i].platelet_count != null && data.Table[i].platelet_count != '') {
                                    plateletCountValue = data.Table[i].platelet_count + ' ' + (data.Table[i].platelet_count_unit == null || data.Table[i].platelet_count_unit == "" ? "" : data.Table[i].platelet_count_unit);
                                }
                                if (data.Table[i].nucleated_red_blood_cells != null && data.Table[i].nucleated_red_blood_cells != '') {
                                    nucleatedRedBloodValue = data.Table[i].nucleated_red_blood_cells;
                                }
                                if (data.Table[i].nucleated_red_blood_cells_percent != null && data.Table[i].nucleated_red_blood_cells_percent != '') {
                                    nucleatedBloodCellPercentValue = data.Table[i].nucleated_red_blood_cells_percent;
                                }
                                if (data.Table[i].hematocrit != null && data.Table[i].hematocrit != '') {
                                    hematocritValue = data.Table[i].hematocrit;
                                }
                                if (data.Table[i].lymphocyte_percent != null && data.Table[i].lymphocyte_percent != '') {
                                    lympocytePercentValue = data.Table[i].lymphocyte_percent;
                                }

                                if (data.Table[i].total_leucocytes_count != null && data.Table[i].total_leucocytes_count != '') {
                                    totalLeucocytesValue = data.Table[i].total_leucocytes_count;
                                }
                                if (data.Table[i].mean_corpuscular_hemoglobin != null && data.Table[i].mean_corpuscular_hemoglobin != '') {
                                    meanCorpuscularValue = data.Table[i].mean_corpuscular_hemoglobin;
                                }
                                if (data.Table[i].mean_corp_hemo_conc != null && data.Table[i].mean_corp_hemo_conc != '') {
                                    meanCorpHemoValue = data.Table[i].mean_corp_hemo_conc;
                                }
                                if (data.Table[i].mean_corpuscular_volume != null && data.Table[i].mean_corpuscular_volume != '') {
                                    meanCorpuscularVolumeValue = data.Table[i].mean_corpuscular_volume;
                                }
                                if (data.Table[i].monocytes != null && data.Table[i].monocytes != '') {
                                    monocytesValue = data.Table[i].monocytes;
                                }
                                if (data.Table[i].neutrophils != null && data.Table[i].neutrophils != '') {
                                    neutrophilsValue = data.Table[i].neutrophils;
                                }
                                if (data.Table[i].eosinophils_absolute_count != null && data.Table[i].eosinophils_absolute_count != '') {
                                    eosinophilsCountValue = data.Table[i].eosinophils_absolute_count;
                                }
                                if (data.Table[i].basophils_absolute_count != null && data.Table[i].basophils_absolute_count != '') {
                                    basophilsCountValue = data.Table[i].basophils_absolute_count;
                                }
                                if (data.Table[i].lymphocytes_absolute_count != null && data.Table[i].lymphocytes_absolute_count != '') {
                                    lymphocytesCountValue = data.Table[i].lymphocytes_absolute_count;
                                }
                                if (data.Table[i].monocytes_absolute_count != null && data.Table[i].monocytes_absolute_count != '') {
                                    monocytesCountValue = data.Table[i].monocytes_absolute_count;
                                }
                                if (data.Table[i].neutrophils_absolute_count != null && data.Table[i].neutrophils_absolute_count != '') {
                                    neutrophilsCountValue = data.Table[i].neutrophils_absolute_count;
                                }
                                if (data.Table[i].basophils != null && data.Table[i].basophils != '') {
                                    basophilsValue = data.Table[i].basophils;
                                }
                                if (data.Table[i].eosinophils != null && data.Table[i].eosinophils != '') {
                                    eosinophilsValue = data.Table[i].eosinophils;
                                }
                                if (data.Table[i].immature_granulocytes != null && data.Table[i].immature_granulocytes != '') {
                                    immaturegranuloValue = data.Table[i].immature_granulocytes;
                                }
                                if (data.Table[i].immature_granulocytes_percent != null && data.Table[i].immature_granulocytes_percent != '') {
                                    immatureGranuloPercentValue = data.Table[i].immature_granulocytes_percent;
                                }
                                if (data.Table[i].total_rbc != null && data.Table[i].total_rbc != '') {
                                    totalRBCValue = data.Table[i].total_rbc;
                                }
                                if (data.Table[i].redcell_distribution_width != null && data.Table[i].redcell_distribution_width != '') {
                                    redCellValue = data.Table[i].redcell_distribution_width;
                                }
                                if (data.Table[i].redcell_distribution_width_sd != null && data.Table[i].redcell_distribution_width_sd != '') {
                                    redCellDistributionValue = data.Table[i].redcell_distribution_width_sd;
                                }


                                hemoglobin = hemoglobin + '<td>' + hemoglobinValue + '</td>';
                                plateletCount = plateletCount + '<td>' + plateletCountValue + '</td>';
                                nucleatedRedBlood = nucleatedRedBlood + '<td>' + nucleatedRedBloodValue + '</td>';
                                nucleatedBloodCellPercent = nucleatedBloodCellPercent + '<td>' + nucleatedBloodCellPercentValue + '</td>';
                                hematocrit = hematocrit + '<td>' + hematocritValue + '</td>';
                                lympocytePercent = lympocytePercent + '<td>' + lympocytePercentValue + '</td>';
                                totalLeucocytes = totalLeucocytes + '<td>' + totalLeucocytesValue + '</td>';
                                meanCorpuscular = meanCorpuscular + '<td>' + meanCorpuscularValue + '</td>';
                                meanCorpHemo = meanCorpHemo + '<td>' + meanCorpHemoValue + '</td>';
                                meanCorpuscularVolume = meanCorpuscularVolume + '<td>' + meanCorpuscularVolumeValue + '</td>';
                                monocytes = monocytes + '<td>' + monocytesValue + '</td>';
                                neutrophils = neutrophils + '<td>' + neutrophilsValue + '</td>';
                                eosinophilsCount = eosinophilsCount + '<td>' + eosinophilsCountValue + '</td>';
                                basophilsCount = basophilsCount + '<td>' + basophilsCountValue + '</td>';
                                lymphocytesCount = lymphocytesCount + '<td>' + lymphocytesCountValue + '</td>';
                                monocytesCount = monocytesCount + '<td>' + monocytesCountValue + '</td>';
                                neutrophilsCount = neutrophilsCount + '<td>' + neutrophilsCountValue + '</td>';
                                basophils = basophils + '<td>' + basophilsValue + '</td>';
                                eosinophils = eosinophils + '<td>' + eosinophilsValue + '</td>';
                                immaturegranulo = immaturegranulo + '<td>' + immaturegranuloValue + '</td>';
                                immatureGranuloPercent = immatureGranuloPercent + '<td>' + immatureGranuloPercentValue + '</td>';
                                totalRBC = totalRBC + '<td>' + totalRBCValue + '</td>';
                                redCell = redCell + '<td>' + redCellValue + '</td>';
                                redCellDistribution = redCellDistribution + '<td>' + redCellDistributionValue + '</td>';

                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + hemoglobin + trend + trstart + plateletCount + trend + trstart + nucleatedRedBlood +
                                trend + trstart + nucleatedBloodCellPercent + trend + trstart + hematocrit + trend + trstart + lympocytePercent + trend + trstart + totalLeucocytes + trend + trstart + meanCorpuscular + trend + trstart + meanCorpHemo + trend +
                                trstart + meanCorpuscularVolume + trend + trstart + monocytes + trend + trstart + neutrophils + trend + trstart + eosinophilsCount + trend +
                                trstart + basophilsCount + trend + trstart + lymphocytesCount + trend + trstart + monocytesCount + trend +
                                trstart + neutrophilsCount + trend + trstart + basophils + trend + trstart + eosinophils + trend + trstart + immaturegranulo + trend +
                                trstart + immatureGranuloPercent + trend + trstart + totalRBC + trend + trstart + redCell + trend + trstart + redCellDistribution + trend + tbodyend;

                            $('#tbl_cbc').html(result);
                        }
                    }
                }

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

//urine routine graph
function UrineRoutineGraph() {
    var PaitentsTrend = {
        Dml_Indicator: 'US',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Graph_Section',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    if (Object.keys(data).length > 0) {

                        var Parameters = '<th>Parameters</th>', specificgravity = '<th>SPECIFIC GRAVITY</th>', urinarybilirubin = '<th>URINARY BILIRUBIN</th>',
                            urineblood = '<th>URINE BLOOD</th>', urobiligen = '<th>UROBILINOGEN</th>', urinaryglucose = '<th>URINARY GLUCOSE</th>',
                            urinaryketone = '<th>URINE KETONE</th>', leucocytes = '<th>URINARY LEUCOCYTES</th>', nitrite = '<th>NITRITE</th>', ph = '<th>PH</th>', urinaryprotein = '<th>URINARY PROTEIN</th>';

                        if (data.Table.length > 0) {
                            var datalength = 10;
                            if (data.Table.length < 10) {
                                datalength = data.Table.length;
                            }
                            for (var i = 0; i < datalength; i++) {
                                Parameters = Parameters + '<th>' + data.Table[i].VDate + '</th>';

                                var specificgravityValue = '-', urinarybilirubinValue = '-', urinebloodValues = '-', urobiligenValue = '-',
                                    urinaryglucoseValue = '-'; urinaryketoneValue = '-'; leucocytesValue = '-'; nitriteValue = '-'; phValue = '-'; urinaryproteinValue = '-';

                                if (data.Table[i].specific_gravity != null && data.Table[i].specific_gravity != '') {
                                    specificgravityValue = data.Table[i].specific_gravity + ' ' + (data.Table[i].specific_gravity_unit == null || data.Table[i].specific_gravity_unit == "" ? "" : data.Table[i].specific_gravity_unit);
                                }
                                if (data.Table[i].urinary_bilirubin != null && data.Table[i].urinary_bilirubin != '') {
                                    urinarybilirubinValue = data.Table[i].urinary_bilirubin + ' ' + (data.Table[i].urinary_bilirubin_unit == null || data.Table[i].urinary_bilirubin_unit == "" ? "" : data.Table[i].urinary_bilirubin_unit);
                                }
                                if (data.Table[i].urine_blood != null && data.Table[i].urine_blood != '') {
                                    urinebloodValues = data.Table[i].urine_blood;
                                }
                                if (data.Table[i].urobilinogen != null && data.Table[i].urobilinogen != '') {
                                    urobiligenValue = data.Table[i].urobilinogen + ' ' + (data.Table[i].urobilinogen_unit == null || data.Table[i].urobilinogen_unit == "" ? "" : data.Table[i].urobilinogen_unit);
                                }
                                if (data.Table[i].urinary_glucose != null && data.Table[i].urinary_glucose != '') {
                                    urinaryglucoseValue = data.Table[i].urinary_glucose;
                                }
                                if (data.Table[i].urine_ketone != null && data.Table[i].urine_ketone != '') {
                                    urinaryketoneValue = data.Table[i].urine_ketone + ' ' + (data.Table[i].urine_ketone_unit == null || data.Table[i].urine_ketone_unit == "" ? "" : data.Table[i].urine_ketone_unit);
                                }

                                if (data.Table[i].urinary_leucocytes != null && data.Table[i].urinary_leucocytes != '') {
                                    leucocytesValue = data.Table[i].urinary_leucocytes;
                                }
                                if (data.Table[i].nitrite != null && data.Table[i].nitrite != '') {
                                    nitriteValue = data.Table[i].nitrite + ' ' + (data.Table[i].nitrite_unit == null || data.Table[i].nitrite_unit == "" ? "" : data.Table[i].nitrite_unit);
                                }
                                if (data.Table[i].ph != null && data.Table[i].ph != '') {
                                    phValue = data.Table[i].ph;
                                }
                                if (data.Table[i].urinary_protein != null && data.Table[i].urinary_protein != '') {
                                    urinaryproteinValue = data.Table[i].urinary_protein;
                                }


                                specificgravity = specificgravity + '<td>' + specificgravityValue + '</td>';
                                urinarybilirubin = urinarybilirubin + '<td>' + urinarybilirubinValue + '</td>';
                                urineblood = urineblood + '<td>' + urinebloodValues + '</td>';
                                urobiligen = urobiligen + '<td>' + urobiligenValue + '</td>';
                                urinaryglucose = urinaryglucose + '<td>' + urinaryglucoseValue + '</td>';
                                urinaryketone = urinaryketone + '<td>' + urinaryketoneValue + '</td>';
                                leucocytes = leucocytes + '<td>' + leucocytesValue + '</td>';
                                nitrite = nitrite + '<td>' + nitriteValue + '</td>';
                                ph = ph + '<td>' + phValue + '</td>';
                                urinaryprotein = urinaryprotein + '<td>' + urinaryproteinValue + '</td>';

                            }

                            var theadstart = '<thead><tr>'
                            var theadend = '</tr></thead>'
                            var tbodystart = '<tbody>'
                            var tbodyend = '</tbody>'
                            var trstart = '<tr>';
                            var trend = '</tr>';
                            var result = theadstart + Parameters + theadend + tbodystart + trstart + specificgravity + trend + trstart + urinarybilirubin + trend + trstart + urineblood +
                                trend + trstart + urobiligen + trend + trstart + urinaryglucose + trend + trstart + urinaryketone + trend + trstart + leucocytes + trend + trstart + nitrite + trend + trstart + ph + trend +
                                trstart + urinaryprotein + trend + tbodyend;
                            $('#tbl_urineroutine').html(result);
                        }
                    }
                }
                observed_nutrition_graph();
            }
            else {
                console.log(data);
            }
        }
    });
}

function observed_nutrition_graph() {
    var doctorData = {
        Dml_Indicator: 'GS',
        Patient_id: $('#Hdnpatient_id').val()
    }
    $.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 theadStart = '<thead><tr><th>Type</th>';
                    var theadEnd = '</tr></thead>';
                    var tbodyStart = '<tbody>';
                    var tbodyEnd = '</tbody>';
                    var thead = '';
                    var trow = '';
                    var j = 0;

                    $('#tbl_observed_nutrition').empty();
                    if (data1.Table.length > 0) {
                        for (var i = 0; i < data1.Table.length; i++) {
                            j++;
                            thead = thead + '<th>' + data1.Table[i].date + '</th>';
                        }
                        if (data1.Table1.length > 0) {

                            while (j > 0) {
                                trow = trow + '<td></td>';
                                j--;
                            }

                            for (var i = 0; i < data1.Table1.length; i++) {
                                row = row + '<tr><td>' + data1.Table1[i].Type + '</td>' + trow + '</tr>';
                            }
                        }


                        $('#tbl_observed_nutrition').append(theadStart + thead + theadEnd + tbodyStart + row + tbodyEnd);

                        if (data1.Table2.length > 0) {

                            var refTab = document.getElementById("tbl_observed_nutrition");
                            // Loop through all rows and columns of the table and popup alert with the value
                            // /content of each cell.
                            for (var k = 0; k < data1.Table2.length; k++) {
                                for (var i = 1; row = refTab.rows[i]; i++) {
                                    row = refTab.rows[0];
                                    for (var j = 0; col = row.cells[j]; j++) {
                                        if (refTab.rows[0].cells[j].innerHTML == data1.Table2[k].date && refTab.rows[i].cells[0].innerHTML == data1.Table2[k].Type) {
                                            refTab.rows[i].cells[j].innerHTML = data1.Table2[k].TypeValue;
                                        }
                                        console.log(col.firstChild.nodeValue);
                                    }
                                }
                            }
                        }
                    }

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

function graph1(dataValue, lablevalue, id, labletext) {
    var chartColors = {
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        greenfade: 'rgba(75, 192, 192,0.8)',
        bluefade: 'rgba(54, 162, 235,0.4)',
        white: 'rgb(255, 255, 255)',
        whitefade: 'rgba(255, 255, 255,0.7)',
        newgreen: '#94fc13',
        neworange: '#ff502f',
        darkblue: '#36a2eb',
        darkpink: '#ff6b8b',
        lightwhite: '#fff'
    };

    var config = {
        type: 'line',
        data: {
            labels: lablevalue,
            datasets: [{
                label: labletext,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkblue,
                data: dataValue,

            }]
        },
        options: {
            responsive: true,
            tooltips: {
                mode: 'label',
            },
            legend: {
                display: false,
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: labletext,
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                    },
                    gridLines: {
                        display: false,
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: false,
                        labelString: 'Value',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: false,
                    }
                }]
            }
        }
    };

    var ctx = document.getElementById(id).getContext("2d");
    window.myLine = new Chart(ctx, config);
}


function graph2(dataValue1, dataValue2, lablevalue, id, label1, label2) {
    debugger;
    var chartColors = {
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        greenfade: 'rgba(75, 192, 192,0.8)',
        bluefade: 'rgba(54, 162, 235,0.4)',
        white: 'rgb(255, 255, 255)',
        whitefade: 'rgba(255, 255, 255,0.7)',
        darkblue: '#36a2eb',
        darkpink: '#ff6b8b',
        lightwhite: '#fff'
    };
    var config = {
        type: 'line',
        data: {
            labels: lablevalue,
            datasets: [{
                label: label1,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkblue,
                data: dataValue1,

            }, {
                label: label2,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkpink,
                data: dataValue2,
            }]
        },
        options: {
            responsive: true,
            tooltips: {
                mode: 'label',
            },
            legend: {
                display: false,
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Date',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                    },
                    gridLines: {
                        display: false,
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: false,
                        labelString: 'Value',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: false,
                    }
                }]
            }
        }
    };

    var ctx = document.getElementById(id).getContext("2d");
    window.myLine = new Chart(ctx, config);
}

function graph3(dataValue1, lablevalue, id) {
    var chartColors = {
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        greenfade: 'rgba(75, 192, 192,0.8)',
        bluefade: 'rgba(54, 162, 235,0.4)',
        white: 'rgb(255, 255, 255)',
        whitefade: 'rgba(255, 255, 255,0.7)',
        newgreen: '#94fc13',
        neworange: '#ff502f',
        darkblue: '#36a2eb',
        darkpink: '#ff6b8b',
        lightwhite: '#fff'
    };
    var config = {
        type: 'line',
        data: {
            labels: lablevalue,
            datasets: [{
                label: "score",
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkblue,
                data: dataValue1,
            }]
        },
        options: {
            responsive: true,
            tooltips: {
                mode: 'label',
            },
            legend: {
                display: false,
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Date',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                    },
                    gridLines: {
                        display: false,
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: false,
                        labelString: 'Value',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: false,
                    }
                }]
            }
        }
    };

    var ctx = document.getElementById(id).getContext("2d");
    window.myLine = new Chart(ctx, config);
}

//summary patient details visit_report_end

function Invoiceprint() {
    window.open('/PatientDashboard/doctorfees?visitreportid=' + $('#VisitReportID').val() + '&doctorId=' + $('#doctorId').val() + '&btnval=1', "_blank");
}

function Invoice_lab_print(order_id, visit_report_id) {
    if (order_id != '' && order_id != "null") {
        window.open('/PatientDashboard/labinvoice?orderid=' + order_id + '&doctorId=' + $('#doctorId').val());
    }
    else {
        window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&doctorId=' + $('#doctorId').val() + '&btnval=1', "_blank");
    }
}

//invoice payment amount textbox value start

$('#InvoiceName').change(function () {
    var familydetails = {
        consultation_name: $('#InvoiceName').val(),
        doctor_id: $('#doctorId').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);
            }
        }
    });

});
//invoice payment amount textbox value end


//Medicine Interaction started
$('#prclose,#closeid').click(function () {
    $('#tblDoctorUser12 tbody').empty();
});

function med_inter() {
    $('.da-load-casestudy').toggle();
    var visit = {
        visit_report_id: $('#VisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/MedicineInteraction/Med_Int',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(visit),
        success: function (data) {
            $('.da-load-casestudy').toggle();
            $('.list1').empty();
            $('.list2').empty();
            $('.list3').empty();
            $('.list4').empty();

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    var task = "No Interaction found";
                    var html = '<h2 style="padding-left: 20%;">' + task + '</h2>';
                    $('.list1').html(html);
                    $('.list2').html(html);
                    $('.list3').html(html);
                    $('.list4').html(html);
                }
                else {
                    var severe = data1[2].severe.length;
                    var met = data1[1].met.length;
                    var moderate = data1[3].moderate.length;
                    var mild = data1[4].mild.length;
                    if (severe == 0) {
                        var task = "No Severe Interaction found";
                        var html = '<h2 style="padding-left: 10%;">' + task + '</h2>';
                        $('.list1').html(html);
                    }
                    else {
                        for (var i = 0; i < severe; i++) {
                            var task = data1[2].severe[i];
                            var html = '<li><span>' + task + '</span></li>';
                            $('.list1').append(html);
                        }
                    }
                    if (met == 0) {
                        var task = "No Metabolism Interaction found";
                        var html = '<h2 style="padding-left: 6%;">' + task + '</h2>';
                        $('.list2').html(html);
                    }
                    else {
                        for (var i = 0; i < met; i++) {
                            var task = data1[1].met[i];
                            var html = '<li><span>' + task + '</span></li>';
                            $('.list2').append(html);
                        }
                    }
                    if (moderate == 0) {
                        var task = "No Moderate Interaction found";
                        var html = '<h2 style="padding-left: 8%;">' + task + '</h2>';
                        $('.list3').html(html);
                    }
                    else {
                        for (var i = 0; i < moderate; i++) {
                            var task = data1[3].moderate[i];
                            var html = '<li><span>' + task + '</span></li>';
                            $('.list3').append(html);
                        }
                    }
                    if (mild == 0) {
                        var task = "No Mild Interaction found";
                        var html = '<h2 style="padding-left: 10%;">' + task + '</h2>';
                        $('.list4').html(html);
                    }
                    else {
                        for (var i = 0; i < mild; i++) {
                            var task = data1[4].mild[i];
                            var html = '<li><span>' + task + '</span></li>';
                            $('.list4').append(html);
                        }
                    }
                }
                var overlay = document.getElementById('tblDoctorUser12');
                $('#tblDoctorUser12').modal('toggle');
            }
            else {
                console.log(data1);
            }
        }
    });
}

//Medicine Interaction end


//Complaints master started
$('#txtnotes').change(function () {
    $('#txtnotes_1').val($('#txtnotes').val());
});

$('#txtnotes_1').change(function () {
    $('#txtnotes').val($('#txtnotes_1').val());
});

function copy_complaints(val) {
    var tr = [];
    tr = val;
    console.log(tr);

    $('#txtComplaints_1').tagEditor('addTag', tr);

}

//Complaints master ended
//function complaints_master_insert(val) {
//    var complaints_master_list = {
//        doctor_id: $('#doctorId').val(),
//        complaints:val,
//        Dml_Indicator: 'I'
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/caseStudy/complaints_master',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(complaints_master_list),
//        success: function (data) {
//            if (jQuery.isEmptyObject((data))) {

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

function complaints_master_insert(val, Type) {
    var complaints_master_list = {
        doctor_id: $('#doctorId').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) {
            if (jQuery.isEmptyObject((data))) {

            }
        }
    });
}


//diagnosis master started

function diagnosis_insert(val) {
    var complaints_master_list = {
        diagnosis: val,
        doctor_id: $('#doctorId').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) {
        }
    });
}

function diagonsislist() {
    var complaints_master_list = {
        doctor_id: $('#doctorId').val(),
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'list'
    }
    $.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 {
                    var dia = '', pro = ''; var complaints = ''; var advice = ''; var notes = '';;
                    $('#Diagonsislist').html('');
                    $('#Procedurelist').html('');
                    $('#Complaintslist').html('');
                    $('#Advicelist').html('');
                    $('#Noteslist').html('');
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var diagnosis = '', treatment_procedure = '';
                            if (data[i].diagnosis != '' && data[i].diagnosis != null) {
                                diagnosis = data[i].diagnosis;
                                dia = dia + '<a href="JavaScript:Void(0);" onclick=\'diagonsisliston(\"' + diagnosis + '\")\'><div class="pull-left">' + diagnosis + ' (' + data[i].created_on + ')</div><div class="clearfix"></div></a>';
                            }
                            if (data[i].treatment_procedure != '' && data[i].treatment_procedure != null) {
                                treatment_procedure = data[i].treatment_procedure;
                                pro = pro + '<a href="JavaScript:Void(0);" onclick=\'treatment_procedureon(\"' + treatment_procedure + '\")\'><div class="pull-left">' + treatment_procedure + ' (' + data[i].created_on + ')</div><div class="clearfix"></div></a>';
                            }
                            if (data[i].complaints != '' && data[i].complaints != null) {
                                complaints = complaints + '<a href="JavaScript:Void(0);" onclick=\'complaintsliston(\"' + data[i].complaints + '\")\'><div class="pull-left">' + data[i].complaints + ' (' + data[i].created_on + ')</div><div class="clearfix"></div></a>';
                            }
                            if (data[i].advice != '' && data[i].advice != null) {
                                advice = advice + '<a href="JavaScript:Void(0);" onclick=\'adviceliston(\"' + data[i].advice + '\")\'><div class="pull-left">' + data[i].advice + ' (' + data[i].created_on + ')</div><div class="clearfix"></div></a>';
                            }
                            if (data[i].notes != '' && data[i].notes != null) {
                                notes = notes + '<a href="JavaScript:Void(0);" onclick=\'notesliston(\"' + data[i].notes + '\")\'><div class="pull-left">' + data[i].notes + ' (' + data[i].created_on + ')</div><div class="clearfix"></div></a>';
                            }

                        }
                        $('#Diagonsislist').html(dia);
                        $('#Procedurelist').html(pro);
                        $('#Complaintslist').html(complaints);
                        $('#Advicelist').html(advice);
                        $('#Noteslist').html(notes);
                    }
                }
            }
            else {
                console.log(data)
            }
        }
    });

    dental_procedures_list();
}

function diagonsisliston(values) {

    var tr = [];
    tr = values
    $('#txtdiagnosis').tagEditor('addTag', tr);
}

function complaintsliston(values) {

    var tr = [];
    tr = values
    $('#txtComplaints_1').tagEditor('addTag', tr);
    //$('#txtComplaints_1').val(values);

}

function adviceliston(values) {
    var tr = [];
    tr = values
    $('#txtAdvice').tagEditor('addTag', tr);
    //$('#txtAdvice').val(values);
}

function notesliston(values) {
    var tr = [];
    tr = values
    $('#txtnotes_1').tagEditor('addTag', tr);
    // $('#txtnotes_1').val(values);
}

function treatment_procedureon(values) {
    $('#txtprodcedure').val(values);
}
//diagnosis master ended

//medicine comparision started

$('#med_comp').click(function () {
    var PaitentsTrend = {
        Dml_Indicator: "PMP",
        doctor_id: $('#doctorId').val(),
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/PrescriptionYear',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#Selchdate1,#Selchdate2').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1[i].visit_report_id + '">' + data1[i].c_date + '</option>';
                        }
                        $('#Selchdate1,#Selchdate2').append(default_opt + SelRole);
                    }
                    $('#Selchdate1,#Selchdate2').val($('#visit_report_id').val());
                }
                $('#moreinfoCompare_1').modal();
                $('#tbl-med_comp,#scrollmed').hide();
            }
            else {
                console.log(data1);
            }
        }
    });
});


$('#btndatesum').click(function () {
    if ($.trim($('#Selchdate1,#Selchdate2').val()).length > 0) {
        current_visit_report_1 = $('#Selchdate1').val();
        visit_report_2_date = $('#Selchdate2').val();
        if (current_visit_report_1 == visit_report_2_date) {
            toastr.warning("Two visit dates cannot be the same, Please select the different date")
        }
        else {
            compare_pres();

        }
    }
    else {
        toastr.warning("Visit date cannot be empty, Please select the date");
    }
});


function compare_pres() {
    var PaitentsTrend = {
        indicator_id: "MC",
        current_visit_report_1: $('#Selchdate1').val(),
        visit_report_2_date: $('#Selchdate2').val(),
        patient_id: $('#Hdnpatient_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Medicine_Comparision/Compare',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaitentsTrend),
        success: function (data) {
            $('#tbl-med_comp,#scrollmed').show();
            $('#tbl-med_comp tbody').empty();
            if (data["visit"].length == 0 && data["new_med"].length == 0 && data["del_med"].length == 0) {
                toastr.warning("No Medicine Comparision Found");
            }
            else {
                var data1 = JSON.parse(data);

                $.each(data1["visit"], function (i, emp) {

                    if (emp.instructions == null) {
                        var notes = "-";
                    }
                    else {
                        var notes = emp.instructions;
                    }

                    if (emp.morning == null) {
                        var morning = "0";
                    }
                    else {
                        var morning = emp.morning;
                    }
                    if (emp.afternoon == null) {
                        var afternoon = "0";
                    }
                    else {
                        var afternoon = emp.afternoon;
                    }
                    if (emp.evening == null) {
                        var evening = "0";
                    }
                    else {
                        var evening = emp.evening;
                    }
                    if (emp.night == null) {
                        var night = "0";
                    }
                    else {
                        var night = emp.night;
                    }

                    row_data = "<tr " + color + "><td>" + emp.medicine_type + "</td><td>" + emp.medicine_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + morning + "-" + afternoon + "-" + evening + "-" + night + "</td><td>" + notes + "</td><td>" + emp.days_to_take + " -days" + "</td></tr>";
                    $('#tbl-med_comp').append(row_data);

                })

                $.each(data1["new_med"], function (i, emp) {
                    if (emp.instructions == null) {
                        var notes = "-";
                    }
                    else {
                        var notes = emp.instructions;
                    }

                    if (emp.morning == null) {
                        var morning = "0";
                    }
                    else {
                        var morning = emp.morning;
                    }
                    if (emp.afternoon == null) {
                        var afternoon = "0";
                    }
                    else {
                        var afternoon = emp.afternoon;
                    }
                    if (emp.evening == null) {
                        var evening = "0";
                    }
                    else {
                        var evening = emp.evening;
                    }
                    if (emp.night == null) {
                        var night = "0";
                    }
                    else {
                        var night = emp.night;
                    }

                    var color = 'style="color:blue"';

                    row_data = "<tr " + color + "><td>" + emp.medicine_type + "</td><td>" + emp.medicine_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + morning + "-" + afternoon + "-" + evening + "-" + night + "</td><td>" + notes + "</td><td>" + emp.days_to_take + " -days" + "</td></tr>";
                    $('#tbl-med_comp').append(row_data);

                })

                $.each(data1["del_med"], function (i, emp) {
                    if (emp.instructions == null) {
                        var notes = "-";
                    }
                    else {
                        var notes = emp.instructions;
                    }

                    if (emp.morning == null) {
                        var morning = "0";
                    }
                    else {
                        var morning = emp.morning;
                    }
                    if (emp.afternoon == null) {
                        var afternoon = "0";
                    }
                    else {
                        var afternoon = emp.afternoon;
                    }
                    if (emp.evening == null) {
                        var evening = "0";
                    }
                    else {
                        var evening = emp.evening;
                    }
                    if (emp.night == null) {
                        var night = "0";
                    }
                    else {
                        var night = emp.night;
                    }

                    var color = 'style="color:red"';

                    row_data = "<tr " + color + "><td>" + emp.medicine_type + "</td><td>" + emp.medicine_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + morning + "-" + afternoon + "-" + evening + "-" + night + "</td><td>" + notes + "</td><td>" + emp.days_to_take + " -days" + "</td></tr>";
                    $('#tbl-med_comp').append(row_data);

                })

                $('#tbl-med_comp').append("</tbody>");
            }
        }
    });
}
//medicine comparision ended


//procedure start
function procedure() {
    //commented by nandhini for performance issue on 20/09/2022 and this section already removed in ui.
    //P_labtype();
    var labval = {
        Dml_Indicator: 'S',
        patient_id: patient_id,
        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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table.length > 0) {
                        if (data.Table[0].VVisit_report_id == '' || data.Table[0].VVisit_report_id == null) {

                        }
                        else {
                            var tr = '';
                            $('#P_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='btn btn-primaryuse btn-xs mr20' onclick='P_scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger btn-xs' onclick='P_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);
                            }
                            $('#P_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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table.length > 0) {
                        var tr = '';
                        $('#P_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='btn addicon-btn btn-sm mr20' onclick='P_scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='P_deleteRow(\"" + (data.Table[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        }
                        $('#P_DiagnosticsTestTable').html(tr);
                    }
                    else {
                        $('#P_DiagnosticsTestTable').empty();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function P_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) {
            $('#P_labtype').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var tr = '';
                    $('#P_labtype').append('');
                    $.each(data1, function (i, emp) {
                        tr = tr + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';
                    });
                    $('#P_labtype').append(tr);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#P_Add_Lab_record').click(function () {
    insert_lab_prescription();
});


function P_deleteRow(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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                loadlab_prescription();
            }
            else {
                console.log(data);
            }
        }
    });
}

function P_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 {
                    for (var i = 0; i < data.length; i++) {
                        var lab_type = data[0].lab_type;
                        $('#P_report').val(data[0].lab_prescription);
                        $('#P_labtype').val(data[0].lab_type);
                    }
                    $('#P_Add_Lab_record').hide();
                    $('#P_Update_Lab_record').show();
                    $('#P_hdn_scan_id').val(scan_id);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function insert_lab_prescription() {
    debugger;
    if ($('#P_labtype').val() == 0) {
        $('#P_PSelFacilityId').show();
        $('#P_PSelFacilityId').fadeOut(8000);
        $('#P_PSelFacilityId').html('Select test type');
        $('#P_SelFacilityId').focus();
        $('#P_SelFacilityId').val('0');
        return false;
    }

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

    var visitreportid = ($('#VisitReportID').val() == "" || $('#VisitReportID').val() == null) ? $('#EditVisitReportID').val() : $('#VisitReportID').val();

    var labval = {
        Dml_Indicator: 'I',
        visit_report_id: visitreportid,
        patient_id: $('#Hdnpatient_id').val(),
        lab_prescription: $('#P_report').val(),
        lab_type: $('#P_labtype').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 (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    var tr = '';
                    $('#P_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='btn addicon-btn' onclick='P_scanedit(\"" + data.Table[i].prescription_scan_id + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn deleteicon-btn btn-sm' onclick='P_deleteRow(\"" + (data.Table[i].prescription_scan_id) + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    }
                    $('#P_DiagnosticsTestTable').html(tr);
                }
                $('#P_report').val('');
                $('#P_labtype').val(0);
            }
            else {
                console.log(data);
            }
        }
    });
}


$('#P_Update_Lab_record').click(function () {
    var table_id = $('#P_hdn_scan_id').val();

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

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

    $('#P_Add_Lab_record').show();
    $('#P_Update_Lab_record').hide();

    var sms = {
        Dml_Indicator: 'UU',
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        lab_prescription: $('#P_report').val(),
        lab_type: $('#P_labtype').val(),
        prescription_scan_id: $('#P_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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '';
                loadlab_prescription();
                $('#P_report').val('');
            }
            else {
                console.log(data);
            }
        }
    });
});

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

//procedure end

//view chart(health and fitness,medication,quality assurance)
function graph1_bpbsall(dataValue, lablevalue, id, labletext) {
    var chartColors = {
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        greenfade: 'rgba(75, 192, 192,0.8)',
        bluefade: 'rgba(54, 162, 235,0.4)',
        white: 'rgb(255, 255, 255)',
        whitefade: 'rgba(255, 255, 255,0.7)',
        newgreen: '#94fc13',
        neworange: '#ff502f',
        darkblue: '#36a2eb',
        darkpink: '#ff6b8b',
        lightwhite: '#fff'
    };
    var config = {
        type: 'line',
        data: {
            labels: lablevalue,
            datasets: [{
                label: labletext,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkblue,
                data: dataValue,
            }]
        },
        options: {
            responsive: true,
            tooltips: {
                mode: 'label',
            },
            legend: {
                display: false,
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: labletext,
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                    },
                    gridLines: {
                        display: false,
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: false,
                        labelString: 'Value',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: false,
                    }
                }]
            }
        }
    };
    var ctx = document.getElementById(id).getContext("2d");
    window.myLine1 = new Chart(ctx, config);
}


function graph2_bpbsall(dataValue1, dataValue2, lablevalue, id, lable1, lable2) {
    var chartColors = {
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        greenfade: 'rgba(75, 192, 192,0.8)',
        bluefade: 'rgba(54, 162, 235,0.4)',
        white: 'rgb(255, 255, 255)',
        whitefade: 'rgba(255, 255, 255,0.7)',
        newgreen: '#94fc13',
        neworange: '#ff502f',
        darkblue: '#36a2eb',
        darkpink: '#ff6b8b',
        lightwhite: '#fff'
    };
    var config = {
        type: 'line',
        data: {
            labels: lablevalue,
            datasets: [{
                label: lable1,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkblue,
                data: dataValue1,

            }, {
                label: lable2,
                backgroundColor: chartColors.lightwhite,
                borderColor: chartColors.darkpink,
                data: dataValue2,
            }]
        },
        options: {
            responsive: true,
            tooltips: {
                mode: 'label',
            },
            legend: {
                display: false,
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'Date',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                    },
                    gridLines: {
                        display: false,
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: false,
                        labelString: 'Value',
                        fontSize: 9
                    },
                    ticks: {
                        fontSize: 9,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: false,
                    }
                }]
            }
        }
    };
    var ctx = document.getElementById(id).getContext("2d");
    window.myLine1 = new Chart(ctx, config);
}


//view chart end
$('#sellangs').change(function () {
    var MedicinePrescriptiondate = {
        patient_id: $('#Hdnpatient_id').val(),
        print_flag: $('#sellangs').val(),
        Dml_Indicator: 'PF',
        doctor_id: $('#doctorId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(MedicinePrescriptiondate),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                if (data.length > 2) {
                }
            }
        }
    })
});


$('#csTab_14').click(function () {
    //if ($('#divtxtComplaints_1 .tag-editor-tag').hasClass('active')) {
    //    $('#divtxtComplaints_1 .tag-editor-tag.active').closest('li').addClass('cshide');
    //}


});


$('#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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        $('#txtRef').html(data[0].reference_value);
                        $('#txtunits').html(data[0].unit);
                        $('#parameter_id').val(data[0].parameter_id);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});


$('#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="btn deleteicon-btn btn-sm" 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="btn deleteicon-btn btn-sm" 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))) {
                }
                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="btn deleteicon-btn btn-sm" 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 {
                console.log(data);
            }
        }
    });
}



$('#btn_casesheet_popup').click(function () {
    labtest();
});

function labtest() {
    $('.da-load-quickentry').show();
    LC_pat_cardiac_details();
    if ($('#LC_txtHypoglycemic').val() == '' && $('#LC_txtGlycemic').val() == 0 && $('#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) {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
            }
        });
    }
    //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) {

    }
    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];

        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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }

    //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(),
            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(),
            NHDL: $('#LC_txtNHDL').val(),
            T_cholestrol_Hdl_ratio: $('#LC_txtHDLRatio').val(),
            dyslipedemia: dyslipedemia,
            note: $('#LC_txtnotes_cholesterol').val(),
            NHDL_unit: $('#LC_SelNHDL').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 end point

    //opthal start point
    if (($('#LC_PDRradio').val() == '' || $('#LC_PDRradio').val() == 0) && ($('#LC_NPDRradio').val() == '' || $('#LC_NPDRradio').val() == 0) && ($('#LC_ChkHemorrhage').val() == '0' || $('#LC_ChkHemorrhage').val() == '') && ($('#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: $('#doctorId').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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }
    //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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }
    //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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }

    //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) {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
            }
        });
    }
    //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) {
            }
        });
    }
    //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) {
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                }
            }
        });
    }
    // ultrasound end point
    //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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }

    //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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                }
            }
        });
    }
    //urine routine end

    setTimeout(function () {
        $('#btn_casesheet_popup_cls').click();
    }, 5000);
    $('#lab_details').modal('toggle');
}


function LC_pat_cardiac_details() {
    //patient level cardiac started
    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_ladradio').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) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    });
    //patient level cardica ended
}


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: $('#doctorId').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) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#LC_Selbloodgroup').val(data.Table20[0].patient_blood_group);
                    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);
                        $('#LC_txtnotes_glycemic').val(data.Table3[0].note);
                    }
                    //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("hello-----" + 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);
                            $("#LC_Chkecg").click();
                        }
                        if (echo_abnormal == '1') {
                            $("#LC_Selecho").prop('checked', true);
                            $("#LC_Selecho").click();
                        }
                        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');
                    }
                    // cardiac coronary disease
                    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');
                    }
                    //thyroid
                    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);
                    }
                    //ultrasound 
                    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');
                    }
                    //liver function test
                    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);
                    }
                    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)
                    }
                    //urine routine
                    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);
            }
        }
    });
}


//doctor patient chat start

function uschathelpscroller() {
    console.log($('.msg_container_base').innerHeight())
    $('.chat').scrollTop($('#textchatursugar')[0].scrollHeight);
    listenChat();
}


//ar ref = new Firebase("https://ursugartest.firebaseio.com/");
//var ref = '';
//var messagesRef = ref.child("ChatMessages");
//var UserRef = ref.child("Users");
var AllMessages = new Array();
var AllPatients = new Array();
var KeyArray = new Array();
var KeyForDelete;
var ReplytoPatientID;
var DoctorId = $('#doctorId').val();
var DRref = ref.child("doctor_list/" + DoctorId + "/chat_list");
var Chatref = "";


function listenChat() {
    $("#textchatursugar").empty();
    var pid = $('#Hdnpatient_id').val();
    var pname = $('#PatientName').html();
    DRref.child(pid).once("value", function (snap) {
        console.log(snap.val())
        if (snap.val() != null) {
            var roomid = snap.val().roomid;
            openchat(roomid, pid);
        } else {
            var roomid = ref.child("chat_room/").push().key();
            var pdoc = {
                id: pid,
                name: pname,
                roomid: roomid,
                url: ""
            }
            var ddoc = {
                id: DoctorId,
                name: $('#txtDusername').html(),
                roomid: roomid,
                url: ""
            }
            var PRref = ref.child("patient_list/" + pid + "/chat_list");
            DRref.child(pid).set(pdoc);
            ref.child("chat_room").child(roomid).set({
                patientId: pid,
                doctorId: DoctorId
            })
            PRref.child(DoctorId).set(ddoc);
            openchat(roomid, pid);
        }
    })

}
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
};
function openchat(roomid, pid) {
    $(".user_item").css("background", "white")
    //$(e).css("background", "#f0f0f0")
    var name = $('#PatientName').html();
    $('#chat_name').html(name);
    Chatref = ref.child("chat_room/" + roomid + "/messages");
    $("#chat_wapper").css("display", "block");
    ref.child("chat_room/" + roomid + "/messages");
    if (Chatref != "") { Chatref.off() }
    enterevent();
    Chatref.on("value", function (docs) {
        $("#textchatursugar").empty();
        docs.forEach(function (doc) {
            var data = doc.val();
            var msg = data.msg;
            if (msg == "b_f_d") msg = "Broadcast Message";
            var type = data.type;
            var docimg = $("#ProfilePhotoTop").attr("src");
            var time = gettime(data.ts)
            if (type == "p") {
                $("#textchatursugar").append('<span class="muted-color-left"></span><li class="left clearfix"><div class="chat-body clearfix"><p>' + msg + '</p></div></li>')
            } else {
                $("#textchatursugar").append('<li class="right clearfix"><p class="chat-adj-he-name"><span class="muted-color-right"></span></p><div class="chat-body clearfix"><p>' + msg + '</p></div></li>')
            }
        })
        var $target = $('.inbox-body');
        $target.animate({ scrollTop: $target.height() }, 1000);
    })
}
function gettime(ts) {
    var ts = new Date(ts);
    var hour = ts.getHours();
    var min = ts.getMinutes();
    var am = "AM"
    if (hour > 11) {
        am = "PM"
        if (hour > 12) {
            hour = hour - 12;
        }
    }
    if (hour < 10) {
        hour = "0" + hour
    }
    if (min < 10) {
        min = "0" + min
    }
    var time = hour + ":" + min + " " + am;
    return time;
}

function enterevent() {
    $("#textchatursugar").empty();
    var input = document.getElementById("btn-input");
    input.addEventListener("keyup", function (event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            sendChatMessage();
        }
    });
}
function sendChatMessage() {
    var msg = $("#btn-input").val().trim();
    if (msg == "") return;
    Chatref.push().set({
        msg: msg,
        ts: new Date().getTime(),
        type: "d"
    })
    $("#btn-input").val("");
}

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

UserRef.on("value", function (snapshot) {
    snapshot.forEach(function (child) {

    });
});

messagesRef.limitToFirst(1).on("child_added", function (snapshot) {
});
messagesRef.on('child_removed', function (oldChildSnapshot) {
});
function redirectToChat(patientId) {
    window.location = '/PatientChat?patientId=' + patientId;
}
function GetMessages() {
    var DoctorId = $('#myHiddenVar').val();
    messagesRef.orderByChild('DoctorId').startAt(DoctorId).endAt(DoctorId).on("value", function (snapshot) {
        AllMessages = new Array();
        snapshot.forEach(function (child) {
            AllMessages.push(child.val())
            var newUserData = {
                "PatientId": child.val().PatientId,
                "DoctorId": child.val().DoctorId,
                "Key": child.key(),
                "Message": child.val().Message
            };
            KeyArray.push(newUserData);
        });
        $("#contentNonRead").empty();
        $('#contentstarred').empty();
        $('#content').empty();
        var displayedMessages = new Array();
        var ages = AllMessages.map(function (obj) { return obj.PatientId });
        ages = ages.filter(function (v, i) { return ages.indexOf(v) == i; });
        for (var i = 0; i < ages.length; i++) {
            var filtered = AllMessages.filter(function (x) { return x.PatientId == ages[i] && x.Message.indexOf(x.PatientId) > -1; });
            displayedMessages.push(filtered[filtered.length - 1]);
        }
        $('#userul').empty();
        $('#userul').append('<li> <h4>Buddy online</h4> </li>');
        for (var i = 0; i < displayedMessages.length; i++) {
            var PatientName = AllPatients.filter(function (x) { return x.Patient_id == displayedMessages[i].PatientId; });
            if (PatientName.length > 0 && PatientName[0].ChatStatus == 1) {

                loadData(PatientName[0].Patient_first_Name, PatientName[0].patient_photo, displayedMessages[i])
            }
            if (PatientName.length > 0) {
                loadPatientData(PatientName[0].Patient_first_Name, PatientName[0].patient_photo);
            }
        }
    });
}


function loadPatientData(Patient_Name, patient_photo) {
    var image = patient_photo;
    var photoSrc;
    var PatientPhoto = $('#hdnPatientPhoto').val();
    if ($.trim(image) == "" || image == null) {
        photoSrc = "/Content/img/profile_icon.png";
    }
    else {
        photoSrc = PatientPhoto + image;
    }
    var content = '<li> <a href="#"> <img src="' + photoSrc + '" class="img-circle img-responsive" alt="" style="border-radius:50%; max-width:100%; width:100%;"><i class=" fa fa-circle text-white f9"></i>' + Patient_Name + ' </a>  </li>';
    $('#userul').append(content);
}
function loadData(Patient_Name, patient_photo, displayedMessages) {
    var Message = displayedMessages.Message.replace(displayedMessages.PatientId, '');
    var image = patient_photo;
    var PatientId = displayedMessages.PatientId;
    var DoctorRead = displayedMessages.DoctorRead;
    var DoctorId = displayedMessages.DoctorId;
    var IsStarred = displayedMessages.IsStarred;
    var starColor = "gold";
    if (IsStarred == 0) {
        starColor = "gray";
    }

    var photoSrc;
    var PatientPhoto = $('#hdnPatientPhoto').val();
    if ($.trim(image) == "" || image == null) {
        photoSrc = "/Content/img/profile_icon.png";
    }
    else {
        photoSrc = PatientPhoto + image;
    }
    var content = '<div class="search-boxa"><div class="box mobile-top"><div class="box-header with-border">';
    content = content + '<table class="message-user"><tbody><tr><td onclick="StarTheMessage(this,\'' + Message + '\',\'' + PatientId + '\',\'' + DoctorId + '\')" class="starred"><i class="fa fa-star ' + starColor + '" aria-hidden="true"></i></td><td class="profile-icon"><img src=' + photoSrc + ' class="img-circle img-responsive" alt="" style="border-radius:50%; max-width:100%; width:100%;"></td>';
    content = content + '<td><div class="name-ar"><a onclick="return redirectToChat(\'' + PatientId + '\')" href="#"><i class=" fa fa-circle text-danger"></i>' + Patient_Name + ',</a></div><div class="place-m">Chennai</div></td></tr></tbody></table></div>';
    content = content + '<div class="box-body"><p>' + Message + '</p></div></div><div class="box-footer message-box-f"><div class="search-boxb"><a onclick="return Reply(\'' + PatientId + '\');" href="#" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#replay-p" data-backdrop="static" data-keyboard="true"><i class="fa fa-reply" aria-hidden="true"></i> Reply </a><a onclick="return Delete(\'' + Message + '\',\'' + PatientId + '\',\'' + DoctorId + '\');" href="#" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#delete-p" data-backdrop="static" data-keyboard="true"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete </a></div></div></div>';

    if (DoctorRead == 0) {
        $('#contentNonRead').append(content);
    }

    if (IsStarred == 1) {
        $('#contentstarred').append(content);
    }
    $('#content').append(content);
    $('#starredCount')[0].innerText = AllMessages.filter(function (x) { return x.IsStarred == 1; }).length;
    $('#UnreadCount')[0].innerText = AllMessages.filter(function (x) { return x.DoctorRead == 0; }).length;
    $('#allCount')[0].innerText = AllMessages.filter(function (x) { return x.Message.indexOf(DoctorId) == -1; }).length;

}
function StarTheMessage(obj, Message, PatientId, DoctorId) {
    var starred = 0;
    if (obj.children['0'].className.indexOf("gray") > -1) {
        starred = 1;
    }
    Message = PatientId + Message;
    var filtered = KeyArray.filter(function (x) { return x.PatientId == PatientId && x.DoctorId == DoctorId && x.Message == Message; });
    ref.child('/ChatMessages/' + filtered[0].Key).update({ IsStarred: starred });
}
function Delete(Message, PatientId, DoctorId) {
    Message = PatientId + Message;
    var filtered = KeyArray.filter(function (x) { return x.PatientId == PatientId && x.DoctorId == DoctorId && x.Message == Message; });
    KeyForDelete = filtered[0].Key;

}
function Reply(PatientId) {
    ReplytoPatientID = PatientId;
}
function ConfirmDelete() {
    messagesRef.child(KeyForDelete).remove();
    KeyForDelete = "";
    document.getElementById('closeDelete').click();

    AllMessages = new Array();
    KeyArray = new Array()
    KeyForDelete = "";
    GetMessages();
}
function CancelDelete() {
    KeyForDelete = "";
    document.getElementById('closeDelete').click();
}

function replyMessage() {

    messagesRef.push({
        DoctorId: $('#myHiddenVar').val(),
        PatientId: ReplytoPatientID,
        Message: $('#myHiddenVar').val() + ' ' + $('#comment').val(),
        TimeStamp: Date.now(),
        PatientRead: 0,
        DoctorRead: 1,
        IsStarred: 0
    }, function (error) {
        if (error) {
            console.log("Error adding new message:", error);
        }
    });
    document.getElementById('close').click();
    $('#comment').val("");
}

//doctor patient chat end

//packkage coupon creation

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((data)) || data.length == "0") {
                }
                else if (data.length > 0) {
                    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"] = $('#doctorId').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"] = $('#doctorId').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"] = $('#doctorId').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: $('#doctorId').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 (data.length > 0) {
                    toastr.success("Thank you for buying this package!!!");
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

//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((data))) {

//                }
//                else {
//                    $('.da-load-casestudy').hide();
//                    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(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((data))) {

//                                }
//                                else {
//                                    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)
//                                                    }

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

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

function LoadPatientGeneralInformation() {
    debugger;
    DeitPlan();
    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 {
                    //$('.da-load-casestudy').hide();
                    var row = '';
                    var j = 0;
                    $('#PatientGeneralInformationBody').empty();
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            if (data1[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_' + (i + 1) + '">' + data1[i].type + '</label> <input type="checkbox" style="float:right;" id="check_' + (i + 1) + '" name="check_' + (i + 1) + '" value="' + data1[i].id + '" onchange=premorbic(' + data1.length + ');> </div><div><input type="text" class="form-control" id="GeneralInformation_' + (i + 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_' + (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(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((data))) {

                                }
                                else {
                                    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++) {
                                                                debugger;
                                                                $('#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)
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                                debugger;
                                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) {
            //$('.da-load-casestudy').hide();
            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);

                        var data2 = data1.Table1;
                        if (data2.length > 0) {
                            for (var i = 0; i < data1.Table.length; i++) {
                                var options = '';
                                var type = '';
                                j++;

                                for (var k = 0; k < data2.length; k++) {
                                    if (data1.Table[i].id == data2[k].type_id) {

                                        type = '<div class="col-xs-12" id="ObservedType_' + (j) + '"><p class="cs-on-head">' + data2[k].type + '<p></div><span id="ObservedTypeID_' + (j) + '" hidden>' + data2[k].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[k].id + '><span>' + data2[k].type_name + '</span></label></div></div>'
                                    }
                                }
                                row = type + options;
                                $('#PatientObservedNutritionBody').append(row);
                            }

                            LoadObservedNutritionVisitID();


                        }



                        //commented by nandhini for performance issue on 20/09/2022  -- start

                        //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) + '"><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);
                        //                    }
                        //                    LoadObservedNutritionVisitID();
                        //                }
                        //            }
                        //            else {
                        //                console.log(data2);
                        //            }
                        //        }
                        //    });
                        //}

                        ///commented end


                    }
                }
            }
            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);
                }
            }
        });


        //old commented by nandhini on 10/01/2022
        //var doctorData = {
        //    patient_id: $('#Hdnpatient_id').val(),
        //    type_id: typeId,
        //    type_value: typeValue,
        //    Dml_Indicator: 'I',
        //    is_active: isActive,
        //    created_by: $('#doctorId').val()
        //}
        //$.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") {
        //            var data = data.data;
        //            j++;
        //            if (count == j) {
        //                debugger;
        //                SaveObservedNutrition();
        //            }
        //        }
        //        else {
        //            console.log(data);
        //        }
        //    }
        //});

    }
    else {
        SaveObservedNutrition();
    }

}


function SaveObservedNutrition() {
    debugger;
    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) {
                    debugger;
                    var data = JSON.parse(data);
                    if (data.msg == "Success") {

                        //diagnosis();
                        Future_Req_Submit();

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

        }
        else {
            //diagnosis();
            Future_Req_Submit()
        }
    }
    else {
        // diagnosis();
        Future_Req_Submit()
    }

    //old commented by nandhini on 11/01/2022
    //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
    //        }
    //        $.ajax({
    //            async: true,
    //            type: 'POST',
    //            url: '/CaseStudy/Patient_Observed_Nutrition',
    //            contentType: 'application/json; charset=UTF-8',
    //            data: JSON.stringify(doctorData),
    //            success: function (data) {
    //                debugger;
    //                var data = JSON.parse(data);
    //                if (data.msg == "Success") {
    //                    var data = data.data;
    //                    debugger;
    //                    j++;
    //                    if (valCount == j) {
    //                        diagnosis();
    //                    }
    //                }
    //                else {
    //                    console.log(data);
    //                }
    //            }
    //        });
    //    }
    //    else {
    //        continue;
    //    }
    //}


}

//package coupon creation done
//Book Physio
$('#BtnBookPhysioAppointment').click(function () {
    isBookAppointment = true;
    $('#BtnLabSubmit').click();
    $('#BookPhysioIFrame').attr('src', '/DirectPatientEnroll/AppointmentSlot?patient_id=' + $('#Hdnpatient_id').val() + '&PName=' + $('#PatientName').html() + '&Type=1');
    $('#bookAppointment').modal();
    $('.da-load-casestudy').hide();


});


//$('#req_add').click(function () {
$('#req_add').click(function () {
    debugger;
    $('#req_add').attr('disabled', true);
    if ($('#Hmaster_service_id').val() == '' || $('#Hmaster_service_id').val() == 0) {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('req_service').focus();
        $('#req_add').attr('disabled', false);
        return false;
    }
    if (($('#Hbase_amount_type').val() == 1 || $('#Hbase_amount_type').val() == 3) && ($('#service_amount').val() == '' || $('#service_amount').val() == 0)) {
        $('#Pservice_amount').show();
        $('#Pservice_amount').fadeOut(8000);
        $('#Pservice_amount').html('Enter the amount');
        $('#service_amount').focus();
        $('#req_add').attr('disabled', false);
        return false;
    }
    if ($('#req_quantity').val() == '' || $('#req_quantity').val() == 0) {
        $('#Preq_quantity').show();
        $('#Preq_quantity').fadeOut(8000);
        $('#Preq_quantity').html('Enter Quantity');
        $('req_quantity').focus();
        $('#req_add').attr('disabled', false);
        return false;
    }


    //service_add();
    else {
        debugger;
        if ($('#desc_div').hasClass('hidden') == false) {
            if ($.trim($('#req_remarks').val()) == "") {
                $('#Preq_remarks').show();
                $('#Preq_remarks').fadeOut(8000);
                $('#Preq_remarks').html('Enter Description');
                $('#req_remarks').focus();
                $('#req_add').attr('disabled', false);
                return false;
            }
        }
        var tot_rowM = $.trim($('#ServiceTableRowCount').val());
        if ($('#H_is_package').val() == 1) {
            if (tot_rowM > 0) {
                package_check_scenario1()
            }
            else {
                service_add();
            }
        }
        else {
            if (tot_rowM > 0) {
                package_check_scenario2()
            }
            else {
                service_add();
            }
        }

    }
})


//Package check-(if any individual service present in package that is going to be added)
function package_check_scenario1() {

    var request_data = {
        master_service_id: $('#Hmaster_service_id').val(),
        Dml_Indicator: 'CPP'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    debugger;
                    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
                    var l = 0;
                    for (i = 0; i < data1.length; i++) {
                        var service_id = data1[i].master_service_id;
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            if (l == 0) {
                                var a = $('#req_table tbody').children('tr').eq(L);
                                var b = a.prop('id');
                                var s_id = b.split('_')[1];
                                L++;
                                if (s_id == service_id) {
                                    Servicedelete(b);
                                    //var row_data = sessionStorage.getItem(b);
                                    //var row_data_split = row_data.split(',');
                                    //var ser_name=row_data_split[0];
                                    //$('#Preq_service').show();
                                    //$('#Preq_service').fadeOut(8000);
                                    //$('#Preq_service').html('Please delete ' + ser_name+' and include the Package');
                                    //$('#req_service').focus();
                                    //l++;
                                    //break;
                                    //return false;
                                }
                            }
                        }
                    }

                    service_add();

                }
            }
        }
    })
}
//Package Check-checking the individual service present in package that is in table
function package_check_scenario2() {
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
    var total_amount = 0, count = 0;

    var L = 0, t1 = 0;
    for (let j = 1; j <= tot_rowM; j++) {
        debugger;
        count++;


        var a = $('#req_table tbody').children('tr').eq(L);
        var b = a.prop('id');
        var s_id = b.split('_')[1];
        L++;
        var request_data = {
            master_service_id: s_id,
            Dml_Indicator: 'CP'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(request_data),
            success: function (data) {

                console.log(data);
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    console.log(data1);
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {

                    }
                    else {

                        if (data1[0].Stringmsg == 'Not_Package') {
                            //service_add();
                        }
                        else {

                            var service_id = $('#Hmaster_service_id').val();
                            var i;
                            for (i = 0; i < data1.length; i++) {

                                debugger;
                                if (service_id == data1[i].master_service_id) {

                                    $('#Preq_service').show();
                                    $('#Preq_service').fadeOut(8000);
                                    $('#Preq_service').html('Service Name already included in Package you listed..');
                                    $('#req_service').focus();
                                    $('#req_service').val('');
                                    $('#req_service_code').val('');
                                    $('#req_quantity').val('');
                                    $('#SelDoctor').val('');

                                    t1 = t1 + 1;
                                    break;
                                    return false;
                                    $('#req_add').attr('disabled', false);
                                }
                            }


                        }
                        if (count == 1) {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add();
                            }
                        }
                        else {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add();
                            }
                        }
                    }
                }
            }
        })
    }


}
//Service add
function service_add() {
    debugger;
    var ser_name = $("#req_service").val();
    var ser_id = $('#Hmaster_service_id').val();
    if (ser_name == null || ser_name == "") {
        return false;
    }
    var ser_code = $('#Hservice_code').val();
    var num_use = $('#req_quantity').val();
    var work_order = $('#Hworkorder').val();
    var work_order_type = $('#Hwork_order_type').val();
    var pack = $('#Hpackage_id').val();
    var req_time = $('#req_time').val();
    var req_end_time = $('#req_end_time').val();
    var base_amount_type = $('#Hbase_amount_type').val();
    var range_min = $('#Hrange_min').val();
    var range_max = $('#Hrange_max').val();
    var remarks = $('#req_remarks').val();
    var doc_name = '-', doc_id = '';

    var base_amount = $('#service_amount').val()
    var total_amount = base_amount * num_use
    var sess_key;
    var rowcount = $.trim($('#ServiceTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var sess_data_ser = ser_name + "," + ser_code + "," + num_use + "," + doc_name + "," + base_amount + "," + total_amount + "," + doc_id + "," + work_order + "," + work_order_type + "," + pack + "," + req_time + "," + req_end_time + "," + base_amount_type + "," + 0 + "," + range_min + "," + range_max + "," + remarks;
    var key = '';
    if (rowcount >= 1) {
        var getEid = $('#req_table  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterSplit = afterSplit[1].split('_')
        afterInc = parseInt(afterSplit[0]) + 1;
        console.log(afterInc);
        ikey_Deit = 'row' + afterInc;
    }
    else {
        ikey_Deit = 'row' + tot_row;
    }
    ikey_Deit = ikey_Deit + "_" + ser_id

    var value = ''
    if (remarks == '') {
        remarks = '-'
    }
    if (rowcount == 0 || work_order != 1) {
        sessionStorage.setItem(ikey_Deit, sess_data_ser);

        if ($('#Hbase_amount_type').val() != 4) {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
        else {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }


    }
    else {
        debugger;
        var L = 0;
        var arr = [];
        for (i = 0; i < $('#req_table >tbody >tr').length; i++) {
            var b = $('#req_table tbody').children('tr').eq(L)
            var id = b.prop('id');
            L++;
            id = id.split('_')[1];
            arr.push(id);
        }
        console.log(arr);
        if ($.inArray(ser_id, arr) == -1) {
            sessionStorage.setItem(ikey_Deit, sess_data_ser);

            if ($('#Hbase_amount_type').val() != 4) {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }
            else {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }

        }
        else {
            $('#Preq_service').show();
            $('#Preq_service').fadeOut(8000);
            $('#Preq_service').html('This particular service can be added only after the completion of the previous similar service');
            $('#req_service').focus();
            $('#req_service').val('');
            $('#req_quantity').val(1);
            $('#attr').prop('disabled', false);
            return false;
        }
    }
    //if ($('table#req_table').find('#' + ser_id).length == 0) {
    //    if ($('#Hbase_amount_type').val() != 4) {
    //        var value = "<tr id=" + ser_id + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    //    }
    //    else {
    //        var value = "<tr id=" + ser_id + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    //    }
    //}
    //else {
    //    $('#Preq_service').show();
    //    $('#Preq_service').fadeOut(8000);
    //    $('#Preq_service').html('Service Name already selected');
    //    $('req_service').focus();
    //    $('req_service').val('');
    //    return false;
    //}

    $('#req_table > tbody:last').append(value);
    $('#ServiceTableRowCount').val(tot_row);
    $('#req_service').val('');
    $('#req_service_code').val('');
    $('#req_quantity').val(1);
    $('#Hmaster_service_id').val('');
    $('#req_remarks').val('');
    $('#desc_div').addClass("hidden");
    $('#req_quantity').prop('disabled', false);
    var dateNow = new Date();

    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    $('#req_time').val(new_date);
    $('#req_time').prop('disabled', true);
    $('#div_service_amt').hide();
    $('#Pservice_amount').html('');
    $('#datetimepicker1').datetimepicker({
        // format: 'DD/MM/YYYY hh:mm A',
        defaultDate: new_date
    });

    $('#req_end_time').val('');
    $('#div_req_end').hide();
    $('#req_add').attr('disabled', false);
}

//Service Table Delete
function Servicedelete(id) {
    sessionStorage.removeItem(id);
    $('#' + id).remove();
    var rowcount = $.trim($('#ServiceTableRowCount').val());
    rowcount = rowcount - 1;
    $('#ServiceTableRowCount').val(rowcount);
}

//Submitting IP/OP request 
$('#req_submit').click(function () {

    if ($('#req_table  >tbody >tr').length == 0) {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('req_service').focus();
        return false;
    }
    else {
        $('#req_submit').attr('disabled', true);
        var service_data = {
            Dml_Indicator: "LR",
            visit_type: '1',
            branch_id: $('#HBranchID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(service_data),
            success: function (data) {
                var data1 = JSON.parse(data);

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    console.log(data1);
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        $('#Hservicerequest_code').val(data1[0].request_code);
                        request_insert_update();
                    }

                }
            }
        });


    }
})

function request_insert_update() {
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
    var total_amount = 0;
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            debugger;
            var a = $('#req_table tbody').children('tr').eq(L);
            var b = a.prop('id');
            L++;
            //var C = b.split('_');
            var gkey = b;
            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(',');
                total_amount = total_amount + parseInt(row_data[5]);
            }
        }
    }
    var indicator = '', wardid = 0, bedid = 0; var billing_class = '10';

    indicator = 'I'
    indicator_ser = 'SI'

    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();

    var date = output.split('/');
    var req_date = date[2] + '-' + date[1] + '-' + date[0];
    var request_data = {
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        visit_type: '1',
        total_amount: total_amount,
        billing_class: $('#Hpatient_BillingClass').val(),
        doctor_id: $('#doctorId').val(),
        wardid: $('#Hpatient_Wardid').val(),
        bedid: bedid,
        Dml_Indicator: indicator,
        request_code: $('#Hservicerequest_code').val(),
        request_date: req_date,
        branch_id: $('#HBranchID').val(),
        is_casesheet: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var service = new Array();
                    var req_id = data1[0].request_id
                    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
                    var total_amount = 0;
                    if (tot_rowM > 0) {
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            var service_data = {}
                            var a = $('#req_table tbody').children('tr').eq(L);
                            var b = a.prop('id');
                            L++;
                            //var C = b.split('_');
                            var gkey = b;
                            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 date = row_data[10].split(" ")[0];
                                var time = row_data[10].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                var end_date, end_time;
                                if (row_data[12] == 4) {
                                    end_date = row_data[11].split(" ")[0];
                                    end_time = row_data[11].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                }
                                else {
                                    end_date = null;
                                    end_time = null;
                                }
                                service_data.master_service_id = gkey.split('_')[1],
                                    service_data.quantity = row_data[2],
                                    service_data.request_id = req_id,
                                    service_data.Dml_Indicator = indicator_ser
                                service_data.user_created_by = $('#hiddenUser_id').val(),
                                    service_data.total_amount = row_data[5],
                                    service_data.base_amount = row_data[4],
                                    service_data.doctor_id = $('#doctorId').val(),
                                    service_data.work_order = row_data[7],
                                    service_data.work_order_type = row_data[8],
                                    service_data.package_id = row_data[9],
                                    service_data.service_date = date,
                                    service_data.service_time = time,
                                    service_data.service_end_date = end_date,
                                    service_data.service_end_time = end_time,
                                    service_data.request_details_id = row_data[13],
                                    service_data.remarks = row_data[16]
                            }
                            service.push(service_data);
                        }
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Billing/IP_OP_Service',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(service),
                        success: function (data) {
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                var data1 = data1.data;
                            }
                            else {
                                console.log(data1);
                            }

                            toastr.success('Service Added Successfully',
                                {
                                    closeButton: false,
                                    progressBar: true,
                                    allowHtml: true,
                                    timeOut: 0,
                                })

                            setTimeout(function () {
                                $('#req_table tbody').empty();
                                $('#req_submit').attr('disabled', false);
                                $('#ServiceTableRowCount').val(0)
                                $('.clsServicePopUpClose').click();
                            }, 2000);


                        }
                    })

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

}

//service request end date change function


$('#datetimepicker2,#datetimepicker1').on('change dp.change', function (e) {
    debugger;
    var start_date = $('#req_time').val();
    var end_date = $('#req_end_time').val();
    if (start_date != '' && end_date != '') {
        var quantity = 0;
        var start_date = new Date(moment($('#req_time').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        var end_date = new Date(moment($('#req_end_time').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        console.log(start_date);
        console.log(end_date);
        var diff = (end_date - start_date) / 1000 / 60 / 60;
        console.log(diff);
        diff1 = diff.toString();
        var a = diff1.split('.')[0];
        if (diff != a) {
            console.log(a);
            var chk = a + '.5';
            if (parseFloat(diff) <= parseFloat(chk)) {
                quantity = parseFloat(chk);
            }
            else {
                quantity = Math.ceil(diff);
            }
        }
        else {
            quantity = diff;
        }
        console.log(quantity);
        $('#req_quantity').val(quantity);
        $('#req_quantity').prop("disabled", true);
    }
})
//service list
$('#service_list').click(function () {
    debugger;
    var request_data = {
        Dml_Indicator: 'CSL',
        doctor_id: $('#doctorId').val(),
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

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

                    debugger;
                    $('#req_service_list tbody').empty();
                    var tr = "";
                    $.each(data, function (i, emp) {
                        var action = "-";
                        var payment = '';
                        if (emp.is_lab == 1 || emp.is_appointment == 1) {
                            var lab_document = '';
                            if (emp.document_path != null && emp.document_path != "") {
                                var str = emp.document_path;
                                var temp = new Array();
                                temp = str.split(",");
                                var strarray = str.split(',');
                                for (var k = 0; k < strarray.length; k++) {
                                    lab_document = lab_document + '<a href="' + $('#hdngetlabfilepath').val() + $('#HdnHospitalid').val() + "/" + $('#HBranchID').val() + "/Lab_Documents/" + strarray[k] + '" target="_blank" style="margin-right: 10px;">Lab Document ' + (k + 1) + '</a>' + "/";
                                }
                            }

                            action = ((emp.flag == 3 || emp.flag == 4)) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprint("' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.master_service_id + '","' + emp.samplbarcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : (emp.flag == 2) ? lab_document + " Result Pending" : "Result Pending";
                            payment = ((emp.is_bill == 1 || emp.is_bill == "1") && emp.due_amount == "0.00") ? '<a><span class="label label-success" style="background-color: green !important;">PAID</span></a>' : '<a><span class="label label-danger">PENDING</span></a>';
                            if (emp.is_appointment == 1 && emp.is_lab != 1) {
                                action = (emp.aflag == 4) ? lab_document + '<button type="button" class="btn btn-primaryuse btn-xs mr-5" style="margin-right: 10px;" onclick=jobprintappointemnt("' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.patientid + '","' + emp.branchid + '","' + emp.work_order_details_id + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : "Result Pending";
                            }
                        }

                        if (emp.base_amount_type == 4) {
                            var date_time = emp.service_date + " " + emp.service_time + " - " + emp.service_end_date + " " + emp.service_end_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + payment + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td><td>' + action + '</td></tr>'
                        }
                        else {
                            var date_time = emp.service_date + " " + emp.service_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + payment + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td><td>' + action + '</td></tr>'
                        }
                    })
                    $('#req_service_list tbody').append(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    })
})

//preview lab result
function job_preview(work_order_id, hospitalid, patientid, branchid) {
    var load_data = {
        indicator_id: "LRD",
        //ReportId: '73'
        ReportId: '108'
    }
    $.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 = '';

                        var load_data = {
                            dmlind: dml_indicator,
                            report_name: ReportName,
                            branchid: branchid,
                            hospitalid: hospitalid,
                            patientid: patientid,
                            work_order_id: work_order_id,
                            reportparameters: reportparameters

                        }
                        $.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: 254%;min-height: 450px; max-height: 450px; overflow: auto;"></iframe>');
                            }
                        });
                    }
                }
            }
            else {
                console.log(data2);
            }
        }
    });

}

//print lab result
function jobprint(work_order_id, hospitalid, patientid, branchid, master_service_id, barcodeid) {
    debugger;
    var load_data = {
        //formid: "73", 
        formid: "108",
        branchid: branchid,
        hospitalid: hospitalid,
        work_order_id: work_order_id,
        patientid: patientid,
        barcodeid: barcodeid,
        masterserviceid: master_service_id

    }

    $.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');

        }
    });

}

//print lab result
function jobprintappointemnt(work_order_id, hospitalid, patientid, branchid, work_order_details_id) {
    debugger;
    var load_data = {
        //formid: "73", 
        formid: "135",
        branchid: branchid,
        hospitalid: $('#HdnHospitalid').val(),
        work_order_id: work_order_id,
        work_order_details_id: work_order_details_id

    }

    $.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');

        }
    });

}

// Transfer IP start //

function TransferIP() {

    $('#transfer_to_ip_popup').modal('show');

    $('#tfPatientName').val($('#PatientName').html());
    $('#tfPatientID').val($('#Hdnpatient_id').val());
}

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

    var IPTF_data = {

        patient_id: $('#tfPatientID').val(),
        visit_report_id: $('#VisitReportID').val(),
        reason: $('#txt_tfReason').val(),
        DML_indicator: "I"

    }

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

            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

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

                    if (data2.Table.length > 0) {

                        toastr.success('Patient Transferred to IP Successfully.',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        $('#IPTF_SubmitBtn').hide();
                        $('#transfer_to_ip_popup').modal('hide');

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

        }
    });

});

//Transfer IP End //




//Dental Casesheet  start//

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

    if ($.trim($('#ChkDentalType').val()) == "" || $('#ChkDentalType').val() == null) {
        $('#PChkDentalType').show();
        $('#PChkDentalType').fadeOut(8000);
        $('#PChkDentalType').html('Select Dental Type');
        $('#ChkDentalType').focus();
        $('#PChkDentalType').focus();
        return false;
    }

    if ($.trim($('#toothno').html()) == "" || $('#toothno').html() == null) {
        $('#Ptoothno').show();
        $('#Ptoothno').fadeOut(8000);
        $('#Ptoothno').html('Please select any one of the tooth number');
        $('#toothno').focus();
        return false;
    }

    var dml_indicator = $('#btnAddDentalDetails').html() == 'Update' ? "U" : "I";
    var tooth_align = 0;
    if ($('#childtoothtab').hasClass('active')) {
        tooth_align = 1;
    }
    else {
        tooth_align = 2;
    }
    var DentalData = {
        Dml_Indicator: dml_indicator,
        visit_report_id: $('#VisitReportID').val(),
        tooth_alignment: tooth_align,
        tooth_no: $('#toothno').html(),
        diagnosis: $('#txtToothDiagnosis').val(),
        notes: $('#txtToothNotes').val(),
        loss_of_tooth: $('#ChkLossofTooth').val(),
        reason_for_loss: $('#ChkReasonForLoss').val(),
        patient_dental_casesheet_id: $('#txtPatientDentalCasesheetID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Dental_Casesheet_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DentalData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#btnAddDentalDetails').html('Add');
                    if (data.length > 0) {
                        if (data[0].StringMsg == "already") {
                            toastr.warning('Already exists');
                            if ($('#txtPatientDentalCasesheetID').val() != null && $('#txtPatientDentalCasesheetID').val() != "") {
                                $('#btnAddDentalDetails').html('Update');
                            }
                        }
                        else {
                            $('#txtPatientDentalCasesheetID').val('');
                            $('#toothno').html('');
                            $('#txtToothDiagnosis').val('');
                            $('#txtToothNotes').val('');
                            $('#ChkLossofTooth').val('');
                            $('#ChkReasonForLoss').val('');
                            $('a[data-toggle=ChkLossofTooth]').removeClass('active');
                            $('a[data-toggle=ChkLossofTooth]').addClass('not-active');
                            $('a[data-toggle=ChkReasonForLoss]').removeClass('active');
                            $('a[data-toggle=ChkReasonForLoss]').addClass('not-active');
                            //$('a[data-toggle=ChkDentalType]').removeClass('active');
                            //$('a[data-toggle=ChkDentalType]').addClass('not-active');
                            $('.dental_point').removeClass("dental_blue");
                            DentalCasesheetDataBinding(data);
                        }
                    }
                }
            }
        }
    });
});


$('#ChkLossofTooth').change(function () {
    $('#divReasonForLoss').hide();
    $('#ChkReasonForLoss').val('');
    if ($('#ChkLossofTooth').val() == "1") {
        $('#divReasonForLoss').show();
    }

});

function LoadDentalCasesheetData() {
    var visit_id;
    if ($('#VisitReportID').val() != '') visit_id = $('#VisitReportID').val();
    else visit_id = $('#EditVisitReportID').val();

    var DentalData = {
        Dml_Indicator: 'S',
        visit_report_id: visit_id,

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Dental_Casesheet_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DentalData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        DentalCasesheetDataBinding(data);
                    }
                }
            }
        }
    });
}
function DentalCasesheetDataBinding(data) {
    $('#tblDentalCasesheet_body').empty();
    if (data.length > 0) {
        var tr = '';

        for (var i = 0; i < data.length; i++) {
            var toothalign = data[i].tooth_alignment == 1 ? "Child" : "Adult";
            var loss = data[i].loss_of_tooth == 1 ? "Yes" : "No";
            var reason = data[i].reason_for_loss == 1 ? "Periodontal" : data[i].reason_for_loss == 2 ? "Caries" : data[i].reason_for_loss == 3 ? "Others" : '-';

            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + toothalign + '</td><td>' + data[i].tooth_no + '</td><td>' + (!(data[i].diagnosis) ? '-' : data[i].diagnosis) + '</td><td>' + (!(data[i].notes) ? '-' : data[i].notes) + '</td><td>' + loss + '</td><td>' + reason + '</td><td><button class="btn addicon-btn btn-sm mr20" title="Edit Dental" onclick=EditDental(' + data[i].patient_dental_casesheet_id + ')><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" title="Delete Dental" onclick=DeleteDental(' + (data[i].patient_dental_casesheet_id) + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
        }

        $('#tblDentalCasesheet_body').append(tr);
    }
}


function EditDental(patient_dental_id) {

    $('#txtPatientDentalCasesheetID').val('');
    $('#toothno').html('');
    $('#txtToothDiagnosis').val('');
    $('#txtToothNotes').val('');
    $('#ChkLossofTooth').val('');
    $('#ChkReasonForLoss').val('');
    $('a[data-toggle=ChkLossofTooth]').removeClass('active');
    $('a[data-toggle=ChkLossofTooth]').addClass('not-active');
    $('a[data-toggle=ChkReasonForLoss]').removeClass('active');
    $('a[data-toggle=ChkReasonForLoss]').addClass('not-active');
    //$('a[data-toggle=ChkDentalType]').removeClass('active');
    //$('a[data-toggle=ChkDentalType]').addClass('not-active');
    $('.dental_point').removeClass("dental_blue");

    var DentalData = {
        Dml_Indicator: 'SS',
        visit_report_id: $('#EditVisitReportID').val(),
        patient_dental_casesheet_id: patient_dental_id

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Dental_Casesheet_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DentalData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        $('#txtPatientDentalCasesheetID').val(patient_dental_id);
                        $('#btnAddDentalDetails').html('Update');
                        $('#toothno').html(data[0].tooth_no);
                        $('#txtToothDiagnosis').val(data[0].diagnosis);
                        $('#txtToothNotes').val(data[0].notes);

                        $('#ChkLossofTooth').val(data[0].loss_of_tooth);
                        $('a[data-toggle=ChkLossofTooth][data-title="' + data[0].loss_of_tooth + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkLossofTooth][data-title="' + data[0].loss_of_tooth + '"]').addClass('active');

                        $('#ChkReasonForLoss').val(data[0].reason_for_loss);
                        $('a[data-toggle=ChkReasonForLoss][data-title="' + data[0].reason_for_loss + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkReasonForLoss][data-title="' + data[0].reason_for_loss + '"]').addClass('active');
                        if (data[0].tooth_alignment == 1) {
                            $('.child_dental_' + data[0].tooth_no).addClass("dental_blue");
                            $('#adulttoothtab').removeClass('active');
                            $('#childtoothtab').addClass('active');
                            $('#dental_adult').removeClass('in active');
                            $('#dental_child').addClass('in active');

                        }
                        else {
                            $('.adult_dental_' + data[0].tooth_no).addClass("dental_blue");
                            $('#childtoothtab').removeClass('active');
                            $('#adulttoothtab').addClass('active');
                            $('#dental_child').removeClass('in active');
                            $('#dental_adult').addClass('in active');

                        }



                    }
                }
            }
        }
    });
}


function DeleteDental(patient_dental_id) {
    var DentalData = {
        Dml_Indicator: 'D',
        visit_report_id: $('#VisitReportID').val(),
        patient_dental_casesheet_id: patient_dental_id

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Dental_Casesheet_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DentalData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#tblDentalCasesheet_body').empty();
                }
                else {
                    if (data.length > 0) {
                        $('#txtPatientDentalCasesheetID').val('');
                        $('#toothno').html('');
                        $('#txtToothDiagnosis').val('');
                        $('#txtToothNotes').val('');
                        $('#ChkLossofTooth').val('');
                        $('#ChkReasonForLoss').val('');
                        $('a[data-toggle=ChkLossofTooth]').removeClass('active');
                        $('a[data-toggle=ChkLossofTooth]').addClass('not-active');
                        $('a[data-toggle=ChkReasonForLoss]').removeClass('active');
                        $('a[data-toggle=ChkReasonForLoss]').addClass('not-active');
                        //$('a[data-toggle=ChkDentalType]').removeClass('active');
                        //$('a[data-toggle=ChkDentalType]').addClass('not-active');
                        $('.dental_point').removeClass("dental_blue");
                        DentalCasesheetDataBinding(data);
                    }
                }
            }
        }
    });
}


function dental_procedures_list() {
    var DentalData = {
        Dml_Indicator: 'list',
        doctor_id: $('#doctorId').val(),
        patient_id: $('#Hdnpatient_id').val()

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Patient_Dental_Casesheet_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DentalData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        var tr = '';
                        $('#tbldental_previous_procedures_body').empty();
                        for (var i = 0; i < data.length; i++) {

                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data[i].created_on + '</td><td>' + data[i].dental_procedure_done + '</td><td>' + data[i].dental_procedure_remaining + '</td><td>' + data[i].next_appointment_date + '</td></tr>';
                        }

                        $('#tbldental_previous_procedures_body').append(tr);
                    }
                }
            }
        }
    });
}
//Dental Casesheet End


//added by nandhini on 17/10/2022
//Writing Pad  Start

//var lineWidth = 2;
//var canvasdefaultColor;
//let is_drawing = false;

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

//    canvasdefaultColor = $('#colorpickerWritingPad').val();
//});

//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mousedown', function () {
//    var canvas = document.getElementById("canvasPrescriptionWritingPad");
//    start();
//});
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mousemove', function () {
//    var canvas = document.getElementById("canvasPrescriptionWritingPad");
//    mousemove(canvas, event);
//});
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mouseup',mouseup);



//commented by nandhini
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("touchstart", start, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("touchmove", draw, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("touchend", stop, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("mousedown", start, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("mousemove", draw, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("mouseup", stop, false);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener("mouseout", stop, false);

//document.getElementById("canvasPrescriptionWritingPad").width = window.innerWidth - 1;
//document.getElementById("canvasPrescriptionWritingPad").height = window.innerHeight - 1;

//function start(event) {
//    is_drawing = true;
//    let context = document.getElementById("canvasPrescriptionWritingPad").getContext("2d");
//    context.beginPath();
//    context.moveTo(getX(event), getY(event));
//    event.preventDefault();
//}

//function draw(event) {
//    if (is_drawing) {
//        let context = document.getElementById("canvasPrescriptionWritingPad").getContext("2d");
//        context.lineTo(getX(event), getY(event));
//        context.strokeStyle = canvasdefaultColor;
//        context.lineWidth = canvasdefaultPointerSize;
//        context.lineCap = "round";
//        context.lineJoin = "round";
//        context.stroke();
//    }
//    event.preventDefault();
//}

//function stop(event) {
//    if (is_drawing) {
//        let context = document.getElementById("canvasPrescriptionWritingPad").getContext("2d");
//        context.stroke();
//        context.closePath();
//        is_drawing = false;
//    }
//    event.preventDefault();
//    //restore_array.push(context.getImageData(0, 0, canvas.width, canvas.height));
//    //start_index += 1;
//}

//function getX(event) {
//    if (event.pageX == undefined) { return event.targetTouches[0].pageX - document.getElementById("canvasPrescriptionWritingPad").offsetLeft }
//    else { return event.pageX - document.getElementById("canvasPrescriptionWritingPad").offsetLeft }
//}


//function getY(event) {
//    if (event.pageY == undefined) { return event.targetTouches[0].pageY - document.getElementById("canvasPrescriptionWritingPad").offsetTop }
//    else { return event.pageY - document.getElementById("canvasPrescriptionWritingPad").offsetTop }
//}

//const state = {
//    mousedown: false
//};

//const shadowColor = '#333';
//const shadowBlur = lineWidth / 4;

//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mousedown', handleWritingStart);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mousemove', handleWritingInProgress);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mouseup', handleDrawingEnd);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('mouseout', handleDrawingEnd);

//document.getElementById("canvasPrescriptionWritingPad").addEventListener('touchstart', handleWritingStart);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('touchmove', handleWritingInProgress);
//document.getElementById("canvasPrescriptionWritingPad").addEventListener('touchend', handleDrawingEnd);

////clearButton.addEventListener('click', handleClearButtonClick);
//function handleWritingStart(event) {
//    event.preventDefault();

//    const mousePos = getMosuePositionOnCanvas(event);

//    const canvasContext = document.getElementById("canvasPrescriptionWritingPad").getContext('2d');
//    canvasContext.beginPath();

//    canvasContext.moveTo(mousePos.x, mousePos.y);

//    canvasContext.lineWidth = lineWidth;
//    canvasContext.strokeStyle = canvasdefaultColor;
//    canvasContext.shadowColor = null;
//    canvasContext.shadowBlur = null;

//    canvasContext.fill();

//    state.mousedown = true;
//}

//function handleWritingInProgress(event) {
//    event.preventDefault();

//    if (state.mousedown) {
//        const mousePos = getMosuePositionOnCanvas(event);

//        const canvasContext = document.getElementById("canvasPrescriptionWritingPad").getContext('2d');
//        canvasContext.lineTo(mousePos.x, mousePos.y);
//        canvasContext.stroke();
//    }
//}

//function handleDrawingEnd(event) {
//    event.preventDefault();

//    if (state.mousedown) {

//        const canvasContext = document.getElementById("canvasPrescriptionWritingPad").getContext('2d');
//        canvasContext.shadowColor = shadowColor;
//        canvasContext.shadowBlur = shadowBlur;

//        canvasContext.stroke();
//    }

//    state.mousedown = false;
//}


//function getMosuePositionOnCanvas(event) {
//    const clientX = event.clientX || event.touches[0].clientX;
//    const clientY = event.clientY || event.touches[0].clientY;
//    const { offsetLeft, offsetTop } = event.target;
//    const canvasX = clientX - offsetLeft;
//    const canvasY = clientY - offsetTop;

//    return { x: canvasX, y: canvasY };
//}


//$('#eraserWritingPad').click(function () {
//    lineWidth = 50;
//    canvasdefaultColor = "#FFFFFF";
//    $('#colorpickerWritingPad').val("#FFFFFF");
//})

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

//    $('#colorpickerWritingPad').val("#000000");
//    lineWidth = 2;
//    canvasdefaultColor = "#000000";    
//})

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

//    var canvas = document.getElementById("canvasPrescriptionWritingPad");
//    const context = canvas.getContext('2d');
//    context.clearRect(0, 0, canvas.width, canvas.height);
//})

//function getMousePos(canvas, event) {
//        var rect = canvas.getBoundingClientRect();
//        return {
//            x: event.clientX - rect.left,
//            y: event.clientY - rect.top
//        };
//    }

//function mousedown(canvas, event) {
//    var mousePos = getMousePos(canvas, event);
//    isMouseDown = true
//    var currentPosition = getMousePos(canvas, event);
//    var ctx = canvas.getContext('2d');
//    ctx.moveTo(currentPosition.x, currentPosition.y)
//    ctx.beginPath();
//    //ctx.fillStyle = "white";
//    //ctx.fillRect(0, 0, canvas.width, canvas.height);
//    ctx.lineWidth = canvasdefaultPointerSize;
//    ctx.lineCap = "round";
//    ctx.strokeStyle = canvasdefaultColor;

//}

//function mousemove(canvas, event) {

//    if (isMouseDown) {
//        var currentPosition = getMousePos(canvas, event);
//        var ctx = canvas.getContext('2d');
//        ctx.lineTo(currentPosition.x, currentPosition.y)
//        ctx.stroke();
//        //store(currentPosition.x, currentPosition.y, currentSize, currentColor);
//    }
//}

//function mouseup() {
//        isMouseDown = false
//        // store()
//}


const canvas = new fabric.Canvas('canvasPrescriptionWritingPad', {
    width: window.innerWidth,
    height: window.innerHeight
})
const myShadow = {
    color: 'black',
    blur: 1,
    offsetX: 1,
    offsetY: 1
}

//const clearBtn = $('clearWritingPad')
//const modeBtn = $('mode')
//const lineWidthInput = $('lineWidthInput')
const lineWidthValue = $('#lineWidthValue')
const lineColorInput = '';

function clearCanvas() {
    canvas.clear()
}

function changeLineColor() {
    canvas.freeDrawingBrush.color = this.value
}

function changeLineWidth() {
    const newWidth = parseInt(this.value, 10) || 1
    canvas.freeDrawingBrush.width = newWidth
    $('#lineWidthValue').html(newWidth);
}

$('#eraserWritingPad').click(function () {
    //$('#lineWidthValue').html(50);
    canvasdefaultColor = "#FFFFFF";
    $('#colorpickerWritingPad').val("#FFFFFF");

    //  same as `PencilBrush`
    canvas.freeDrawingBrush = new fabric.EraserBrush(canvas);
    canvas.freeDrawingBrush.width = 50;
    canvas.isDrawingMode = true;

})

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

    $('#colorpickerWritingPad').val("#000000");
    $('#lineWidthValue').html(1);
    $('#colorpickerWritingPad').val("#000000");
})

document.getElementById("colorpickerWritingPad").addEventListener('change', changeLineColor)
document.getElementById("lineWidthInputwritingpad").addEventListener('change', changeLineWidth)
document.getElementById("clearWritingPad").addEventListener('click', clearCanvas)
canvas.isDrawingMode = true


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

    var canvasWriting = document.getElementById("canvasPrescriptionWritingPad");

    if ($('#uploadWritingPad').html() != "Update") {
        if (isCanvasBlank(canvasWriting)) {
            toastr.warning('No changes detected');
            return false;
        }
    }

    $('#uploadWritingPad').prop('disabled', true);
    var canvas1 = document.createElement("canvas");
    canvas1.width = canvasWriting.width;
    canvas1.height = canvasWriting.height;

    var destCtx = canvas1.getContext('2d');

    //create a rectangle with the desired color
    destCtx.fillStyle = "#FFFFFF";
    destCtx.fillRect(0, 0, canvasWriting.width, canvasWriting.height);

    //draw the original canvas onto the destination canvas
    destCtx.drawImage(canvasWriting, 0, 0);


    const file = dataURLtoBlob(canvas1.toDataURL("image/png"));
    var fileData = new FormData();
    fileData.append(file.name, file);

    fileData.append('username', 'Manas');
    $.ajax({
        url: '/CaseStudy/UploadPrescriptionWritingPad?visitreportid=' + $('#VisitReportID').val(),
        type: "POST",
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        data: fileData,
        success: function (result) {
            debugger;
            $.each(result, function (i, emp) {

                if (emp != null && emp != "") {
                    //Save image path into database

                    var dml_indicator = 'I';
                    if ($('#uploadWritingPad').html() == 'Update') {
                        dml_indicator = 'U'
                    }
                    var prescriptionData = {
                        Dml_Indicator: dml_indicator,
                        visit_report_id: $('#VisitReportID').val(),
                        patient_id: $('#Hdnpatient_id').val(),
                        prescription_scan_id: '2',
                        patient_testname: 'Writing Pad Prescription',
                        patient_lab_record_path: emp,
                        patient_lab_record_id: $('#HdnPatientLabRecordID').val()
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/WritingPad_Prescription_Ins_Upd',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(prescriptionData),
                        success: function (data) {
                            var data = JSON.parse(data);
                            console.log(data);
                            debugger;
                            if (data.msg == "Success") {
                                var data = data.data;
                                if (jQuery.isEmptyObject((data))) {
                                }
                                else {
                                    toastr.success("Changes Saved Successfully");
                                    //$('#clearWritingPad').click();
                                    canvas.clear();
                                    $('#uploadWritingPad').prop('disabled', false);
                                    $('#uploadWritingPad').html('Save');
                                    $('#createNewWritingPadPage').show();
                                    BindWritingPadImages(data.Table);

                                }
                            }
                        }
                    });
                }
                else {
                    toastr.warning('Error occurred. Please contact support team');
                    return false;
                }

            });
        }
    });

});

function BindWritingPadImages(data) {
    $('#tbluploadPrescriptionWiringPadImages').empty();
    if (data.length > 0) {
        var tr = '';
        for (var i = 0; i < data.length; i++) {
            tr = tr + '<tr><td>' + (i + 1) + '</td><td><a href="' + $('#hdngetlabfilepath').val() + $('#doctorId').val() + "/PrescriptionWritingPad/" + data[i].patient_lab_record_path + '"  class="writingpadimages" target="_blank" style="margin-right: 10px;">Image_' + (i + 1) + '</a></td><td><button class="btn addicon-btn btn-sm mr20" title="Edit Image" onclick=LoadWritingPadImage("' + data[i].patient_lab_record_path + '","' + data[i].patient_lab_record_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn deleteicon-btn btn-sm" title="Delete Image" onclick=DeleteWritingPadImage("' + data[i].patient_lab_record_id + '")><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';
        }
        $('#tbluploadPrescriptionWiringPadImages').append(tr);

    }
}

function DeleteWritingPadImage(lab_record_id) {

    canvas.clear();
    $('#uploadWritingPad').prop('disabled', false);
    $('#uploadWritingPad').html('Save');
    $('#createNewWritingPadPage').show();

    var prescriptionData = {
        Dml_Indicator: 'D',
        visit_report_id: $('#VisitReportID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        patient_lab_record_id: lab_record_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/WritingPad_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(prescriptionData),
        success: function (data) {
            var data = JSON.parse(data);
            console.log(data);
            debugger;
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    toastr.success("Deleted Successfully");
                    BindWritingPadImages(data.Table);
                }
            }
        }
    });
}

function dataURLtoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], { type: mimeString });
}

function LoadWritingPadImage(img, lab_record_id) {

    $('#HdnPatientLabRecordID').val(lab_record_id);

    var path = $('#hdngetlabfilepath').val() + $('#doctorId').val() + "/PrescriptionWritingPad/" + img;
    //var path = "http://localhost/img/PCH01202300006-V006_20230120115358313.jpg";
    //var path = "https://medwayphotos.convenientcare.life/USD01344/PrescriptionWritingPad/PABC01202300019-V006_20230120175507964.jpg";

    var img = new Image();
    img.crossOrigin = "Anonymous";
    img.src = path;
    //var ctx = document.getElementById('canvasPrescriptionWritingPad').getContext('2d')

    img.onload = function () {

        var imgInstance = new fabric.Image(img);

        canvas.add(imgInstance);
        // canvas.deactivateAll().renderAll();
        //ctx.drawImage(image, 0, 0);

    };
    img.onerror = function () {
        toastr.warning('Error occurred on loading image.');
        $('#uploadWritingPad').html('Save');
        $('#createNewWritingPadPage').show();
        return false;
    };

    $('#uploadWritingPad').html('Update');
    $('#createNewWritingPadPage').hide();

}


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

    var canvasWrite = document.getElementById("canvasPrescriptionWritingPad");
    if (!isCanvasBlank(canvasWrite)) {

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>YES</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>NO</button>", 'Do you want to save the changes?',
            {
                closeButton: true,
                progressBar: true,
                allowHtml: true,
                timeOut: 20000000,

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

                        $('#uploadWritingPad').click();
                        // clear current canvas content   
                        canvas.clear();
                    })
                    $("#confirmationRevertNo").click(function () {

                        // clear current canvas content   
                        canvas.clear();
                    })
                }
            })
    }
    else {
        debugger;
        // clear current canvas content   
        canvas.clear();
    }


});

function isCanvasBlank(canvas2) {
    return !canvas2.getContext('2d')
        .getImageData(0, 0, canvas2.width, canvas2.height).data
        .some(channel => channel !== 0);
}
//Writing Pad End



// added by nandhini
// Future Add Services Start

$('#req_add_1').click(function () {
    debugger;
    if ($('#Hmaster_service_id_1').val() == '' || $('#Hmaster_service_id_1').val() == 0) {
        $('#Preq_service_1').show();
        $('#Preq_service_1').fadeOut(8000);
        $('#Preq_service_1').html('Select Service Name');
        $('req_service_1').focus();
        return false;
    }
    if (($('#Hbase_amount_type_1').val() == 1 || $('#Hbase_amount_type_1').val() == 3) && ($('#service_amount_1').val() == '' || $('#service_amount_1').val() == 0)) {
        $('#Pservice_amount_1').show();
        $('#Pservice_amount_1').fadeOut(8000);
        $('#Pservice_amount_1').html('Enter the amount');
        $('#service_amount_1').focus();
        return false;
    }
    if ($('#req_quantity_1').val() == '' || $('#req_quantity_1').val() == 0) {
        $('#Preq_quantity_1').show();
        $('#Preq_quantity_1').fadeOut(8000);
        $('#Preq_quantity_1').html('Enter Quantity');
        $('req_quantity_1').focus();
        return false;
    }

    else {
        debugger;
        if ($('#desc_div_1').hasClass('hidden') == false) {
            if ($.trim($('#req_remarks_1').val()) == "") {
                $('#Preq_remarks_1').show();
                $('#Preq_remarks_1').fadeOut(8000);
                $('#Preq_remarks_1').html('Enter Description');
                $('#req_remarks_1').focus();
                return false;
            }
        }
        var tot_rowM = $.trim($('#ServiceTableRowCount_1').val());
        if ($('#H_is_package_1').val() == 1) {
            if (tot_rowM > 0) {
                package_check_scenario1_future()
            }
            else {
                service_add_future();
            }
        }
        else {
            if (tot_rowM > 0) {
                package_check_scenario2_future()
            }
            else {
                service_add_future();
            }
        }

    }
})
//Package check-(if any individual service present in package that is going to be added)
function package_check_scenario1_future() {

    var request_data = {
        master_service_id: $('#Hmaster_service_id_1').val(),
        Dml_Indicator: 'CPP'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    debugger;
                    var tot_rowM = $.trim($('#ServiceTableRowCount_1').val());
                    var l = 0;
                    for (i = 0; i < data1.length; i++) {
                        var service_id = data1[i].master_service_id;
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            if (l == 0) {
                                var a = $('#req_table_1 tbody').children('tr').eq(L);
                                var b = a.prop('id');
                                var s_id = b.split('_')[1];
                                L++;
                                if (s_id == service_id) {
                                    Servicedelete_future(b);

                                }
                            }
                        }
                    }

                    service_add_future();

                }
            }
        }
    })
}
//Package Check-checking the individual service present in package that is in table
function package_check_scenario2_future() {
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount_1').val());
    var total_amount = 0, count = 0;

    var L = 0, t1 = 0;
    for (let j = 1; j <= tot_rowM; j++) {
        debugger;
        count++;


        var a = $('#req_table_1 tbody').children('tr').eq(L);
        var b = a.prop('id');
        var s_id = b.split('_')[1];
        L++;
        var request_data = {
            master_service_id: s_id,
            Dml_Indicator: 'CP'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(request_data),
            success: function (data) {

                console.log(data);
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    console.log(data1);
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {

                    }
                    else {

                        if (data1[0].Stringmsg == 'Not_Package') {

                        }
                        else {

                            var service_id = $('#Hmaster_service_id_1').val();
                            var i;
                            for (i = 0; i < data1.length; i++) {

                                debugger;
                                if (service_id == data1[i].master_service_id) {

                                    $('#Preq_service_1').show();
                                    $('#Preq_service_1').fadeOut(8000);
                                    $('#Preq_service_1').html('Service Name already included in Package you listed..');
                                    $('#req_service_1').focus();
                                    $('#req_service_1').val('');
                                    $('#req_service_code_1').val('');
                                    $('#req_quantity_1').val('');

                                    t1 = t1 + 1;
                                    break;
                                    return false;
                                }
                            }


                        }
                        if (count == 1) {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add_future();
                            }
                        }
                        else {
                            if ((j) == tot_rowM && t1 == 0) {

                                service_add_future();
                            }
                        }
                    }
                }
            }
        })
    }


}
//Service add
function service_add_future() {
    debugger;
    var ser_name = $("#req_service_1").val();
    var ser_id = $('#Hmaster_service_id_1').val();
    var ser_code = $('#Hservice_code_1').val();
    var num_use = $('#req_quantity_1').val();
    var work_order = $('#Hworkorder_1').val();
    var work_order_type = $('#Hwork_order_type_1').val();
    var pack = $('#Hpackage_id_1').val();
    var req_time = $('#req_start_time_1').val();
    var req_end_time = $('#req_end_time_1').val();
    var base_amount_type = $('#Hbase_amount_type_1').val();
    var range_min = $('#Hrange_min_1').val();
    var range_max = $('#Hrange_max_1').val();
    var remarks = $('#req_remarks_1').val();
    var doc_name = '-', doc_id = '';

    var base_amount = $('#service_amount_1').val()
    var total_amount = base_amount * num_use
    var sess_key;
    var rowcount = $.trim($('#ServiceTableRowCount_1').val());
    var tot_row = (Number(rowcount) + 1);
    var sess_data_ser = ser_name + "," + ser_code + "," + num_use + "," + doc_name + "," + base_amount + "," + total_amount + "," + doc_id + "," + work_order + "," + work_order_type + "," + pack + "," + req_time + "," + req_end_time + "," + base_amount_type + "," + 0 + "," + range_min + "," + range_max + "," + remarks;
    var key = '';
    if (rowcount >= 1) {
        var getEid = $('#req_table_1  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterSplit = afterSplit[1].split('_')
        afterInc = parseInt(afterSplit[0]) + 1;
        console.log(afterInc);
        ikey_Deit = 'row' + afterInc;
    }
    else {
        ikey_Deit = 'row' + tot_row;
    }
    ikey_Deit = ikey_Deit + "_" + ser_id

    var value = ''
    if (remarks == '') {
        remarks = '-'
    }
    if (rowcount == 0 || work_order != 1) {
        sessionStorage.setItem(ikey_Deit, sess_data_ser);
        if ($('#Hbase_amount_type_1').val() != 4) {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete_future(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
        else {
            value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete_future(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
    }
    else {
        debugger;
        var L = 0;
        var arr = [];
        for (i = 0; i < $('#req_table_1 >tbody >tr').length; i++) {
            var b = $('#req_table_1 tbody').children('tr').eq(L)
            var id = b.prop('id');
            L++;
            id = id.split('_')[1];
            arr.push(id);
        }
        console.log(arr);
        if ($.inArray(ser_id, arr) == -1) {
            sessionStorage.setItem(ikey_Deit, sess_data_ser);
            if ($('#Hbase_amount_type_1').val() != 4) {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete_future(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }
            else {
                value = "<tr id=" + ikey_Deit + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + num_use + "</td><td>" + req_time + " - " + req_end_time + "</td><td>" + remarks + "</td><td><button class='delete btn btn-danger btn-xs btn-add' onclick='Servicedelete_future(\"" + ikey_Deit + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            }
        }
        else {
            $('#Preq_service_1').show();
            $('#Preq_service_1').fadeOut(8000);
            $('#Preq_service_1').html('This particular service can be added only after the completion of the previous similar service');
            $('#req_service_1').focus();
            $('#req_service_1').val('');
            $('#req_quantity_1').val(1);
            return false;
        }
    }

    $('#req_table_1 > tbody:last').append(value);
    $('#ServiceTableRowCount_1').val(tot_row);
    $('#req_service_1').val('');
    $('#req_service_code_1').val('');
    $('#req_quantity_1').val(1);
    $('#Hmaster_service_id_1').val('');
    $('#req_remarks_1').val('');
    $('#desc_div_1').addClass("hidden");
    $('#req_quantity_1').prop('disabled', false);
    var dateNow = new Date();

    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    //$('#req_time_1').val(new_date);
    //$('#req_time_1').prop('disabled', true);
    $('#div_service_amt_1').hide();
    $('#Pservice_amount_1').html('');
    //$('#datetimepicker3').datetimepicker({
    //    // format: 'DD/MM/YYYY hh:mm A',
    //    defaultDate: new_date
    //});
    $('#req_start_time_1').val($('#req_time_1').val());
    $('#datetimepicker5').data("DateTimePicker").minDate($("#datetimepicker3").date)
    $('#req_end_time_1').val('');
    $('#div_req_end_1').hide();
}
//Service Table Delete
function Servicedelete_future(id) {
    sessionStorage.removeItem(id);
    $('#' + id).remove();
    var rowcount = $.trim($('#ServiceTableRowCount_1').val());
    rowcount = rowcount - 1;
    $('#ServiceTableRowCount_1').val(rowcount);
}

function Future_Req_Submit() {

    if ($('#req_table_1  >tbody >tr').length > 0) {

        var service_data = {
            Dml_Indicator: "LFR",
            visit_type: '1',
            branch_id: $('#HBranchID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(service_data),
            success: function (data) {
                var data1 = JSON.parse(data);

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    console.log(data1);
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        $('#Hservicerequest_code_1').val(data1[0].request_code);
                        future_request_insert_update();
                    }

                }
            }
        });


    }
    else {
        diagnosis();
    }
}


////Submitting IP/OP request 
//$('#req_submit_future').click(function () {

//    if ($('#req_table_1  >tbody >tr').length == 0) {
//        $('#Preq_service_1').show();
//        $('#Preq_service_1').fadeOut(8000);
//        $('#Preq_service_1').html('Select Service Name');
//        $('req_service_1').focus();
//        return false;
//    }
//    else {
//        $('#req_submit_future').attr('disabled', true);
//        var service_data = {
//            Dml_Indicator: "LFR",
//            visit_type: '1',
//            branch_id: $('#HBranchID').val()
//        }
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/Billing/IP_OP_Request',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(service_data),
//            success: function (data) {
//                var data1 = JSON.parse(data);

//                if (data1.msg == "Success") {
//                    var data1 = data1.data;
//                    console.log(data1);
//                    if (jQuery.isEmptyObject((data1))) {
//                    }
//                    else {
//                        $('#Hservicerequest_code_1').val(data1[0].request_code);
//                        future_request_insert_update();
//                    }

//                }
//            }
//        });


//    }
//})

function future_request_insert_update() {
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount_1').val());
    var total_amount = 0;
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            debugger;
            var a = $('#req_table_1 tbody').children('tr').eq(L);
            var b = a.prop('id');
            L++;
            //var C = b.split('_');
            var gkey = b;
            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(',');
                total_amount = total_amount + parseInt(row_data[5]);
            }
        }
    }
    var indicator = '', wardid = 0, bedid = 0; var billing_class = '10';

    indicator = 'FI'
    indicator_ser = 'FSI'


    var servicedatetimesplit = $('#req_time_1').val().split(' ');
    var date = servicedatetimesplit[0].split('/');
    var req_date = date[2] + '-' + date[1] + '-' + date[0];

    var request_data = {
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        visit_type: '1',
        total_amount: total_amount,
        billing_class: $('#Hpatient_BillingClass').val(),
        doctor_id: $('#doctorId').val(),
        wardid: $('#Hpatient_Wardid').val(),
        bedid: bedid,
        Dml_Indicator: indicator,
        request_code: $('#Hservicerequest_code_1').val(),
        request_date: req_date,
        branch_id: $('#HBranchID').val(),
        is_casesheet: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var service = new Array();
                    var req_id = data1[0].request_id
                    var tot_rowM = $.trim($('#ServiceTableRowCount_1').val());
                    var total_amount = 0;
                    if (tot_rowM > 0) {
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            debugger;
                            var service_data = {}
                            var a = $('#req_table_1 tbody').children('tr').eq(L);
                            var b = a.prop('id');
                            L++;
                            //var C = b.split('_');
                            var gkey = b;
                            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 date = row_data[10].split(" ")[0];
                                var time = row_data[10].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                var end_date, end_time;
                                if (row_data[12] == 4) {
                                    end_date = row_data[11].split(" ")[0];
                                    end_time = row_data[11].split(" ")[1] + " " + row_data[10].split(" ")[2];
                                }
                                else {
                                    end_date = null;
                                    end_time = null;
                                }
                                service_data.master_service_id = gkey.split('_')[1],
                                    service_data.quantity = row_data[2],
                                    service_data.request_id = req_id,
                                    service_data.Dml_Indicator = indicator_ser
                                service_data.user_created_by = $('#hiddenUser_id').val(),
                                    service_data.total_amount = row_data[5],
                                    service_data.base_amount = row_data[4],
                                    service_data.doctor_id = $('#doctorId').val(),
                                    service_data.work_order = row_data[7],
                                    service_data.work_order_type = row_data[8],
                                    service_data.package_id = row_data[9],
                                    service_data.service_date = date,
                                    service_data.service_time = time,
                                    service_data.service_end_date = end_date,
                                    service_data.service_end_time = end_time,
                                    service_data.request_details_id = row_data[13],
                                    service_data.remarks = row_data[16]
                            }
                            service.push(service_data);
                        }
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Billing/IP_OP_Service',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(service),
                        success: function (data) {
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                var data1 = data1.data;
                            }
                            else {
                                console.log(data1);
                            }

                            diagnosis();

                            //$('#req_submit_future').attr('disabled', false);
                            //toastr.success('Service Added Successfully',
                            //{
                            //    closeButton: false,
                            //    progressBar: true,
                            //    allowHtml: true,
                            //    timeOut: 0,
                            //})
                            //setTimeout(function () {
                            //    $('#req_table_1 tbody').empty();
                            //       $('.clsServicePopUpClose').click();
                            //   }, 2000);


                        }
                    })

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

}



//service list
//$('#btnfuture_services').click(function () {
//    var request_data = {
//        Dml_Indicator: 'FCSL',
//        doctor_id: $('#doctorId').val(),
//        patient_id: $('#Hdnpatient_id').val(),
//        visit_report_id: $('#VisitReportID').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/IP_OP_Request',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(request_data),
//        success: function (data) {
//            console.log(data);
//            var data1 = JSON.parse(data);
//            if (jQuery.isEmptyObject((data1))) {
//            }
//            else {

//                if (data1.msg == "Success") {
//                    var data = data1.data;
//                    console.log(data);

//                    debugger;
//                    $('#future_req_service_list tbody').empty();
//                    var tr = "";
//                    $.each(data, function (i, emp) {

//                        if (emp.base_amount_type == 4) {
//                            var date_time = emp.service_date + " " + emp.service_time + " - " + emp.service_end_date + " " + emp.service_end_time;
//                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td></tr>'
//                        }
//                        else {
//                            var date_time = emp.service_date + " " + emp.service_time;
//                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td></tr>'
//                        }
//                    })
//                    $('#future_req_service_list tbody').append(tr);
//                }
//                else {
//                    console.log(data);
//                }
//            }
//        }
//    })
//})


function LoadFutureServicesList() {
    var request_data = {
        Dml_Indicator: 'FCSL',
        doctor_id: $('#doctorId').val(),
        patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

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

                    debugger;
                    $('#future_req_service_list tbody').empty();
                    var tr = "";
                    $.each(data, function (i, emp) {

                        if (emp.base_amount_type == 4) {
                            var date_time = emp.service_date + " " + emp.service_time + " - " + emp.service_end_date + " " + emp.service_end_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td></tr>'
                        }
                        else {
                            var date_time = emp.service_date + " " + emp.service_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + ((emp.remarks == '') ? '-' : emp.remarks) + '</td></tr>'
                        }
                    })
                    $('#future_req_service_list tbody').append(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    })
}
// Future Add Services End


//load visit type
function loadvisit_type() {
    debugger;
    var data = {
        P_Dml_Indicator: 'DVT'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data1 = JSON.parse(data);

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

            }
            else {

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

                    if (data2[1].status == 1) {
                        $('#ip_history_tab').removeClass('hidden')
                        $('#trs_ip_btn').removeClass('hidden')
                    }
                    else {
                        $('#ip_history_tab').addClass('hidden')
                        $('#trs_ip_btn').addClass('hidden')
                    }
                }
            }
        }
    })
}


//refer patient start
function PatientReferral() {
    $('#txtPatientName').val($('.PatientName').html());

    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HdnHospitalid').val(),
        branch_id: $('#HBranchID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            $('#SelReferredToDoctor').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelReferredToDoctor').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>';
                        }
                        $('#SelReferredToDoctor').html(default_opt + SelRole);
                        if (parseInt($('#hiddenRole_id').val()) == 1) {
                            $("#SelReferredToDoctor option[value='" + $('#doctorId').val() + "']").remove();
                        }
                    }
                }
            }
        }
    });
}

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

    if ($('#SelReferredToDoctor').val() == 0 || $('#SelReferredToDoctor').val() == null || $('#SelReferredToDoctor').val() == "") {
        $('#PSelReferredToDoctor').show();
        $('#PSelReferredToDoctor').fadeOut(8000);
        $('#PSelReferredToDoctor').html('Select Referred To Doctor');
        $('SelReferredToDoctor').focus();
        return false;
    }

    var request_data = {
        Dml_Indicator: 'I',
        doctor_id: $('#doctorId').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        visit_report_id: $('#VisitReportID').val(),
        referred_to_doctor_id: $('#SelReferredToDoctor').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Doctor_Referral_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data = data1.data;
                    console.log(data);
                    if (data.Table[0].StringMsg == 'already') {
                        toastr.warning('You have already referred this patient');
                    }
                    else {
                        toastr.success('Referred Successfully');
                        $('.clspatientReferralClose').click();
                    }
                }
            }
        }
    });

});
// refer patient end

function job_service_detail_print(work_order_id, hospitalid, patientid, branchid, master_service_id, barcodeid, work_order_detailsid) {
    debugger;
    debugger;
    var work_orderid = work_order_id
    var work_order_detail_id = work_order_detailsid

    var load_data = {
        formid: '135',
        hospitalid: $('#HdnHospitalid').val(),
        work_order_id: work_orderid,
        work_order_details_id: work_order_detail_id,
    }

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

        }
    });

}



// test history section ///

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

            }
            else {
                console.log(data);
                $('#tbl_tests_history').empty();
                if (data.Table.length > 0) {
                    var thead = '<th style="display:none;">Parameter ID</th><th>Test Name</th><th>Unit</th>';
                    var tr = ""; var trheadrows = '';
                    for (var i = 0; i < data.Table1.length; i++) {
                        tr = tr + "<th class='clstestdate_" + data.Table1[i].created_on + "'>" + data.Table1[i].test_date + "</th>";
                    }

                    var totalcolumns = data.Table1.length;
                    if (totalcolumns > 0) {
                        for (k = 0; k < totalcolumns; k++) {
                            trheadrows = trheadrows + "<td></td>";
                        }
                    }

                    thead = "<thead>" + thead + tr + "</thead>";

                    var row = '';
                    for (var j = 0; j < data.Table.length; j++) {
                        row = row + '<tr><td style="display:none;">' + data.Table[j].parameter_id + '</td><td>' + data.Table[j].parameter_name + '</td><td>' + data.Table[j].unit + '</td>' + trheadrows + '</tr>';
                    }

                    $('#tbl_tests_history').append(thead + "<tbody>" + row + "</tbody>");

                    $("#tbl_tests_history tbody tr").each(function () {

                        var value = $(this).find("td").eq(0).html();

                        for (var j = 0; j < data.Table2.length; j++) {
                            if (data.Table2[j].parameter_id == value) {

                                var indexVal = $('.clstestdate_' + data.Table2[j].created_on).index();

                                if (indexVal >= 0) {
                                    $(this).find("td").eq(indexVal).html(data.Table2[j].observation);
                                }
                            }
                        }

                    });

                }
            }
        }
    });
}


$('#btnclicktocall_1').click(function () {
    debugger;
    $('#loaderimgClicktoCall').show();
    var PatientData = {
        Patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'CL',
        visit_report_id: $('#VisitReportID').val(),
        doctor_user_id: $('#HiddenUserCreatedBy').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/clicktocall',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            $('#loaderimgClicktoCall').hide();
            var data = JSON.parse(data);
            var data = data.data;
            if (jQuery.isEmptyObject((data))) {

            }
        }
    });

});





