var whentotakearray = [];
var frequencyarray = [];
$(document).ready(function () {
    debugger;
 
    $('#DiagnosticsTestTable').removeClass('us-loader-template-table');
    $('#tblDietChart').removeClass('us-loader-template-table');
    $('#tbl-medicine').removeClass('us-loader-template-table');
    LoadBranch()
    loadlab_id();
    loadpharmacyid();
    labtype();
    labtemlatelist();
    loadMedicineType();
    Deittemlatelist();
    check_previlige_tabs(12)
    loadvisit_type();
    Medicine_Frequency();
  //  loadwhentoeat();

    if ($('#His_pharmacy').val() == '1') {
        $('#branch_div').shows()
    }
    else {
        $('#branch_div').hide()
    }
    //var dttableremove = $('#tblDietChart').DataTable();
    $('#myModal').on('hidden.bs.modal', function () {
        load_diagnosis();
    });
});
function check_previlige_tabs(formid) {
    debugger;
    var RightData = {
        Stringtype: formid,
        Dml_Indicator: "CTABR"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/User_rights_privileges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RightData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var j = 0

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

                    $.each(data1.Table1, function (i, emp) {
                        if (emp.status == 0) {
                            $("[data-id=" + emp.role_rights_view + "]").addClass('hidden');
                        }
                        else if (emp.status == 1) {
                            if (j == 0) {
                                if (emp.role_rights_view == 'TCP_V1') {
                                    $('#tab_prescription').click();
                                   
                                }
                                else if (emp.role_rights_view == 'TCC_V1') {
                                    $('#conplaintstab').click();
                                }
                                else if (emp.role_rights_view == 'TCG_V1')
                                {
                                    $('#diagnosistab').click();
                                }
                             

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

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

                }
                else {
                    debugger;
                    if (data.Table9.length > 0) {
                        var pharmacyID = data.Table9[0].pharmacy_id;
                        $('#txtPharmacyID').val(pharmacyID);

                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
//lab template start

function loadlab_id() {
    var country = {
        Dml_Indicator: "DI",
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        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;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Country;
                    $.each(data1, function (i, emp) {
                        $('#lab_id').val(emp.lab_id);
                    });
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

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

                    });
                    $('#checkboxs').append(Country);

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

function labtemlatelist() {
    var Template = {
        doctor_id: $('#doctorId').val(),
        Dml_Indicator: 'TS'
    }
    $.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;
                $('#labtemplatelist').html('');
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    for (var i = 0; i < data.length; i++) {
                        tr = tr + '<a href="javascript:void(0)" onclick=onlabtemplatelist(' + data[i].lab_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div></a>';
                    }
                }
                $('#labtemplatelist').html(tr);

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

function onlabtemplatelist(labid) {
    var Template = {
        lab_template_id: labid,
        doctor_id: $('#doctorId').val(),
        Dml_Indicator: 'SS'
    }
    $.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;
                debugger;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {
                    $('#DiagnosticsTestTable').removeClass('us-loader-template-table');
                }
                else {
                    $('#DiagnosticsTestTable > tbody').empty();
                    $('#DiagnosticsTestTable').addClass('us-loader-template-table');

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

                        var sess_key;
                        var rowcount = $.trim($('#labTableRowCount').val());
                        var tot_row = (Number(rowcount) + 1);
                        var ikey = '';
                        var sess_data = data[i].lab_type + "," + data[i].lab_prescription + "," + data[i].lab_type_name;

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

                            ikey = 'row' + tot_row;
                        }

                        sessionStorage.setItem(ikey, sess_data);
                        var testval = '';

                        var value = "<tr id='t_" + ikey + "'><td>" + data[i].lab_prescription + "</td><td>" + data[i].lab_type_name + "</td><td><button class='edit btn btn-primary btn-xs mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger btn-xs' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                        $('#DiagnosticsTestTable > tbody:last').append(value);
                        $('#labTableRowCount').val(tot_row);


                        $('#btnlabsave').html('Update');
                        $('#btnlabdelete').show();
                        $('#labupdateId').val(data[i].lab_template_id);
                        $('#txtlabTemplateName').val(data[i].template_name);
                        $('#txtlabTemplateName').attr("disabled", true);
                    }

                    $('#report').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
                    //$('#Prescription_template').prop('disable');
                    debugger;
                    $('#labCopy_template').hide();
                    $('#DiagnosticsTestTable').removeClass('us-loader-template-table');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#Add_Lab_record').click(function () {
    var TestName = $("#report").val();
    var TestId = $("#checkboxs").val();

    if ($.trim((TestId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((TestName)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    debugger;
    var testval = $("#checkboxs option:selected").text();
    var labtypetest = $('#labtypetest').val();
    var sess_key;
    var rowcount = $.trim($('#labTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var ikey = '';
    var sess_data = TestId + "," + TestName + "," + testval + "," + labtypetest;

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

        ikey = 'row' + tot_row;
    }

    sessionStorage.setItem(ikey, sess_data);

    var labname = '';
    if (labtypetest == 1) {
        labname = 'Test';
    }
    else if (labtypetest == 2) {
        labname = 'Panel';
    }


    var value = "<tr id='t_" + ikey + "'><td>" + TestName + "</td><td>" + testval + "</td><td><button class='edit btn btn-primary btn-xs mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger btn-xs' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#DiagnosticsTestTable > tbody:last').append(value);
    $('#labTableRowCount').val(tot_row);

    $('#report').val('');
    $('#checkboxs').prop('value', 1); // by D
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 1 + '"]').removeClass('not-active').addClass('active');

    //hidecode
    //$('#diet_btn').attr("data-toggle", "");
    //$('#prescription_btn').attr("data-toggle", "");
});


$('#Update_Lab_record').click(function () {
    debugger;
    var table_id = $('#hdn_scan_id').val();

    var TestName = $("#report").val();
    var TestId = $("#checkboxs").val(); //removed :checked
    if ($.trim((TestId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((TestName)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }

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

    var testval = $("#checkboxs option:selected").text();
    var labtypetest = $('#labtypetest').val();

    var sess_data = TestId + "," + TestName + "," + testval + "," + labtypetest;
    var ikey = table_id;
    sessionStorage.setItem(ikey, sess_data);

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




    var tot_row = $.trim($('#labTableRowCount').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 labname = '';
            if (row_data[3] == 1) {
                labname = 'Test';
            }
            else if (row_data[3] == 2) {
                labname = 'Panel';
            }
            debugger;

            var value = "<tr id='t_" + gkey + "'><td>" + row_data[1] + "</td><td>" + row_data[2] + "</td><td><button class='edit btn btn-primary btn-xs mr-10' onclick='labedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger btn-xs' onclick='labdelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

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


    $('#labTableRowCount').val(tot_row);

    $('#report').val('');
    $('#checkboxs').prop('value', 1); // by D
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    //$('a[data-toggle="labtypetest"]').not('[data-title="' + 1 + '"]').removeClass('not-active').addClass('active');
});

function labedit(val) {
    debugger;
    $('#Add_Lab_record').hide();
    $('#Update_Lab_record').show();
    $('#hdn_scan_id').val(val);
    debugger;
    var gkey = val;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#checkboxs').val(row_data_split[0]);
    var rowval = row_data_split[0];
    $('#report').val(row_data_split[1]);
    $('a[data-toggle="checkboxs"][data-title="' + rowval + '"]').addClass('active').removeClass('not-active'); // by D



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


$('#txtlabTemplateName').change(function () {
    var labval = {
        template_name: $('#txtlabTemplateName').val(),
        doctor_id: $('#doctorId').val(),
        Dml_Indicator: 'CHLN'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Lab_template',
        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 b;
                    if (data1[0].msg == "already") {
                        toastr.warning("Lab template name already exists");
                        $('#txtlabTemplateName').val('');
                    }
                    else {
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
});


$('#btnlabsave').click(function () {
    debugger;
    if ($('#btnlabsave').html() == 'Update') {
        labupdate();
    }
    else {
        labinsert();
    }
    $('#diet_btn').attr("data-toggle", "tab");
    $('#prescription_btn').attr("data-toggle", "tab");
    $('#txtlabTemplateName').attr("disabled", false);
});


function labupdate() {
    var labtemplatename = $('#txtlabTemplateName').val();
    if ($.trim((labtemplatename)) == "") {
        $('#PtxtlabTemplateName').show();
        $('#PtxtlabTemplateName').fadeOut(8000);
        $('#PtxtlabTemplateName').html('Enter the template name');
        $('#txtlabTemplateName').focus();
        return false;
    }
    var labbodyrowCount = $('#DiagnosticsTestTable >tbody >tr').length;
    if (labbodyrowCount <= 0) {
        $('#PtxtlabTemplateName').show();
        $('#PtxtlabTemplateName').fadeOut(8000);
        $('#PtxtlabTemplateName').html('Enter the test details');
        $('#report').focus();
        return false;
    }
    var labtemplateId = '';
    if ($('#labTableRowCount').val() > 0) {
        $('#loaderimg').show();
        var labval = {
            lab_template_id: $('#labupdateId').val(),
            doctor_id: $('#doctorId').val(),
            Dml_Indicator: 'D'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Lab_template',
            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;
                    var labval = {
                        template_name: $('#txtlabTemplateName').val(),
                        doctor_id: $('#doctorId').val(),
                        Dml_Indicator: 'TI'
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/Lab_template',
                        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 watch_id = '';
                                    if (data1.length > 0) {
                                        for (var i = 0; i < data1.length; i++) {
                                            labtemplateId = data1[0].lab_template_id;
                                        }

                                        var tot_rowM = $.trim($('#labTableRowCount').val());
                                        if (tot_rowM > 0) {
                                            var L = 0;
                                            for (j = 1; j <= tot_rowM; j++) {
                                                var a = $('#DiagnosticsTestTable_body').children('tr').eq(L);
                                                //var a = $('#WatchTable').closest('table').attr('id');
                                                //var b = a;
                                                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: 'TDI',
                                                        lab_type: row_data[0],
                                                        lab_prescription: row_data[1],
                                                        lab_template_id: labtemplateId
                                                    }
                                                    $.ajax({
                                                        async: true,
                                                        type: 'POST',
                                                        url: '/CaseStudy/Lab_template',
                                                        contentType: 'application/json; charset=UTF-8',
                                                        data: JSON.stringify(sms),
                                                        success: function (data) {
                                                        }
                                                    });
                                                }
                                            }

                                            labtemlatelist();
                                            $('#DiagnosticsTestTable > tbody').empty();
                                            $('#labTableRowCount').val(0);
                                            $('#report').val('');
                                            $('#txtlabTemplateName').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
                                            $('#btnlabsave').html('Save');
                                            $('#labCopy_template').show();
                                            toastr.success("Lab Template Updated Successfully")
                                            location.reload();
                                        }
                                    }
                                }
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                }
                else {
                    console.log(data);
                }
            }
        });
        $('#loaderimg').hide();
        //location.reload();
    }
}
$('#submit_Diet').click(function () {
    labinsert();
});

function labinsert() {
    debugger;
    var labtemplatename = $('#txtlabTemplateName').val();
    if ($.trim((labtemplatename)) == "") {
        $('#PtxtlabTemplateName').show();
        $('#PtxtlabTemplateName').fadeOut(8000);
        $('#PtxtlabTemplateName').html('Enter the template name');
        $('#txtlabTemplateName').focus();
        return false;
    }
    var labbodyrowCount = $('#DiagnosticsTestTable >tbody >tr').length;
    if (labbodyrowCount <= 0) {
        $('#PtxtlabTemplateName').show();
        $('#PtxtlabTemplateName').fadeOut(8000);
        $('#PtxtlabTemplateName').html('Enter the test details');
        $('#report').focus();
        return false;
    }
    var labtemplateId = '';
    debugger;
    if ($('#labTableRowCount').val() > 0) {
        $('#loaderimg').show();
        var labval = {
            template_name: $('#txtlabTemplateName').val(),
            doctor_id: $('#doctorId').val(),
            Dml_Indicator: 'TI'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Lab_template',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var watch_id = '';
                        var length = Object.keys(data1).length
                        if (length > 0) {
                            for (var i = 0; i < length; i++) {
                                labtemplateId = data1[0].lab_template_id;
                            }

                            var tot_rowM = $.trim($('#labTableRowCount').val());
                            if (tot_rowM > 0) {
                                var L = 0;
                                for (j = 1; j <= tot_rowM; j++) {
                                    var a = $('#DiagnosticsTestTable_body').children('tr').eq(L);
                                    //var a = $('#WatchTable').closest('table').attr('id');
                                    //var b = a;
                                    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: 'TDI',
                                            lab_type: row_data[0],
                                            lab_prescription: row_data[1],
                                            lab_template_id: labtemplateId,

                                        }
                                        $.ajax({
                                            async: true,
                                            type: 'POST',
                                            url: '/CaseStudy/Lab_template',
                                            contentType: 'application/json; charset=UTF-8',
                                            data: JSON.stringify(sms),
                                            success: function (data) {
                                            }
                                        });
                                    }
                                }
                                labtemlatelist();
                                $('#DiagnosticsTestTable > tbody').empty();
                                $('#labTableRowCount').val(0);
                                $('#report').val('');
                                $('#txtlabTemplateName').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
                                $('#btnlabsave').html('Save');
                                $('#labCopy_template').show();
                                toastr.success("Lab Template Added Successfully")
                                location.reload();

                            }
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
        $('#loaderimg').hide();
        //location.reload();
    }
}

$('#btnlabdelete').click(function () {
    var labtemplatename = $('#txtlabTemplateName').val();
    if ($.trim((labtemplatename)) == "") {
        $('#PtxtlabTemplateName').show();
        $('#PtxtlabTemplateName').fadeOut(8000);
        $('#PtxtlabTemplateName').html('Enter the template name');
        $('#txtlabTemplateName').focus();
        return false;
    }
    if (confirm("Are you sure?")) {
        var labtemplateId = '';
        var labval = {
            lab_template_id: $('#labupdateId').val(),
            doctor_id: $('#doctorId').val(),
            Dml_Indicator: 'D'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Lab_template',
            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;
                    labtemlatelist();
                    $('#DiagnosticsTestTable > tbody').empty();
                    $('#labTableRowCount').val(0);
                    $('#report').val('');
                    $('#txtlabTemplateName').val('');
                    $('#txtlabTemplateName').attr("disabled", false);
                    $('#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
                    $('#btnlabsave').html('Save');
                    $('#labCopy_template').show();
                    toastr.success("Lab Template Deleted Successfully")
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    else {
        return false;
    }

});



//lab template end



// Deit template start

function Deittemlatelist() {
    var Template = {
        created_by: $('#doctorId').val(),
        Dml_Indicator: 'TS'
    }
    $.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;
                $('#deittemplatelist').html('');
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    for (var i = 0; i < data.length; i++) {
                        tr = tr + '<a href="javascript:void(0)" onclick=onDeittemplatelist(' + data[i].diet_template_id + ');><div class="pull-left">' + data[i].diet_name + '</div><div class="clearfix"></div></a>';
                    }
                }
                $('#deittemplatelist').html(tr);

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

function onDeittemplatelist(val) {
    $('#deit_template').hide();
    $('#tblDietChart').DataTable().destroy();
    $('#tblDietChart > tbody').empty();
    $('#DietTableRowCount').val(0);
    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
    var Template = {
        diet_template_id: val,
        created_by: $('#doctorId').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;
                debugger;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    $('#tblDietChart').DataTable().destroy();
                    $('#tblDietChart > tbody').empty();
                    $('#txtdietname').val('');
                    $('#DietTableRowCount').val(0);
                    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 != "" && data[i].instructions != null) ? 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 != "" && data[i].instructions != null) ? data[i].instructions : "") + "</td><td><button class='edit btn btn-primary btn-xs mr-10' data-id='TCD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick='Dietedit(\"" + ikey_Deit + "\",this)'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' data-id='TCD_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick='Dietdelete(\"" + ikey_Deit + "\",this)'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                        $('#kcal').val(data[i].kcal);
                        var kcal = '';
                        debugger;
                        if (data[i].kcal == '1500') {
                            kcal = 'kcal1';
                        }
                        else if (data[i].kcal == '1800') {
                            kcal = 'kcal2';
                        }
                        else {
                            kcal = 'kcal3';
                        }
                        $('a[data-toggle=kcal][data-title="' + kcal + '"]').addClass('active');
                        $('a[data-toggle=kcal][data-title="' + kcal + '"]').removeClass('not-active');
                        $('#tblDietChart > tbody:last').append(value);
                        $('#tblDietChart').DataTable();
                        $('#DietTableRowCount').val(tot_row);
                        $('#btndietsave').html('Update');
                        $('#btndietdelete').show();
                        $('#txtdietname').val(data[i].diet_name);
                        $('#deitupdateid').val(data[i].diet_template_id);
                        $('#txtdietname').attr("disabled", true);
                    }
                    $('#txtTime').val('');
                    $('#txtfood').val('');
                    $('#txtQuantity').val('');
                    $('#txtInstructions').val('');
                    $('#Copy_template').hide();
                }
            }
            else {
                console.log(data);
            }
        }
    });
}


$('#Add_Diet_record').click(function () {
    debugger;
   // $('#tblDietChart').DataTable().destroy();
    var Time = $('#txtTime').val();
    var food = $('#txtfood').val();
    var Quantity = $('#txtQuantity').val();
    var Instructions = $('#txtInstructions').val();

    var did = $('#Add_Diet_record').attr("data-id");
    var navigation = $('#Add_Diet_record').attr("data-nav");
    var name = $('#Add_Diet_record').attr("data-name");
    var columntype = $('#Add_Diet_record').attr("data-type");

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

                     return;
                 }
                 else {
                     if ($.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;
                     }

                     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  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>" + Time + "</td><td>" + food + "</td><td>" + Quantity + "</td><td>" + Instructions + "</td><td><button title='edit' class='edit btn btn-primary btn-xs mr-10' data-id='TCD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick='Dietedit(\"" + ikey_Deit + "\",this)'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' data-id='TCD_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick='Dietdelete(\"" + ikey_Deit + "\",this)'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                     $('#tblDietChart > tbody:last').append(value);
                     $('#DietTableRowCount').val(tot_row);
                     $('#tblDietChart').DataTable();
                     // $('#txtTime').val('');
                     $('#txtfood').val('');
                     $('#txtQuantity').val('');
                     $('#txtInstructions').val('');

                     //hide code
                     //$('#prescription_btn').attr("data-toggle", "");
                     //$('#labtest_btn').attr("data-toggle", "");
                 }
             }
         }
     });
});




function Dietedit(val, event) {
    debugger;
    $('#Add_Diet_record').hide();
    $('#Update_Diet_record').show();
    $('#hdn_diet_id').val(val);

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");

    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;

         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {

                     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, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     sessionStorage.removeItem(val);
                     $('#t_' + val).remove();
                     var a = $.trim($('#DietTableRowCount').val());
                     var a = (a) - (1);
                     $('#DietTableRowCount').val(a);

                    
                     //var dttableremove = $('#tblDietChart').DataTable();

                     //var removingRow = e.closest('tr');
                     //dttableremove.row(removingRow).remove().draw();

                 }
             }
         }
     });
}

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

$('#Update_Diet_record').click(function () {
    debugger;

    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').DataTable().destroy();
    $('#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  title='edit' class='edit btn btn-primary btn-xs mr-10' data-id='TCD_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick='Dietedit(\"" + gkey + "\",this)'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' data-id='TCD_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick='Dietdelete(\"" + gkey + "\",this)'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

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


    $('#DietTableRowCount').val(tot_row);


    //$('#txtTime').val('');
    $('#txtfood').val('');
    $('#txtQuantity').val('');
    $('#txtInstructions').val('');

});



$('#txtdietname').change(function () {
    var labval = {
        diet_name: $('#txtdietname').val(),
        created_by: $('#doctorId').val(),
        Dml_Indicator: 'CHDT'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/DeitTemplate',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var b;
                    if (data1[0].msg == "already") {
                        toastr.warning("Diet template Name already exists");
                        $('#txtdietname').val('');
                    }
                    else {
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
});



$('#btndietsave').click(function () {
    debugger;
    var diettemplatename = $('#txtdietname').val();
    if ($.trim((diettemplatename)) == "") {
        $('#Ptxtdietname').show();
        $('#Ptxtdietname').fadeOut(8000);
        $('#Ptxtdietname').html('Enter the template name');
        $('#Ptxtdietname').focus();
        return false;
    }
    var labbodyrowCount = $('#tblDietChart >tbody >tr').length;
    if (labbodyrowCount <= 0) {
        $('#Ptxtdietname').show();
        $('#Ptxtdietname').fadeOut(8000);
        $('#Ptxtdietname').html('Enter the diet details');
        $('#txtTime').focus();
        return false;
    }
    if ($('#btndietsave').html() == 'Update') {
        $('#loaderimg').show();
        var labval = {
            diet_template_id: $('#deitupdateid').val(),
            created_by: $('#doctorId').val(),
            Dml_Indicator: 'D'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    insertdiet();
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    else {
        insertdiet();
    }
    $('#labtest_btn').attr("data-toggle", "tab");
    $('#prescription_btn').attr("data-toggle", "");

    $('#loaderimg').hide();
    $('#txtdietname').attr("disabled", false);
    //location.reload();
});


function insertdiet() {
    debugger;
    var dietname = $('#txtdietname').val();
    if ($.trim((dietname)) == "") {
        $('#Ptxtdietname').show();
        $('#Ptxtdietname').fadeOut(8000);
        $('#Ptxtdietname').html('Enter the template name');
        $('#txtdietname').focus();
        return false;
    }
    var deittemplateId = '';
    if ($('#DietTableRowCount').val() > 0) {
        var kcal = $('#kcal').val();
        var kcalval = '';
        if (kcal == 'kcal1') {
            kcalval = '1500';
        }
        else if (kcal == 'kcal2') {
            kcalval = '1800';
        }
        else {
            kcalval = '2000';
        }
        var labval = {
            diet_name: $('#txtdietname').val(),
            created_by: $('#doctorId').val(),
            kcal: kcalval,
            Dml_Indicator: 'I'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var length = Object.keys(data1).length;
                        if (length > 0) {
                            debugger;
                            for (var i = 0; i < data1.length; i++) {
                                deittemplateId = data1[0].diet_template_id;
                            }
                            var totalresponsesuccess = 0;
                            var tot_rowM = $.trim($('#DietTableRowCount').val());
                            if (tot_rowM > 0) {
                                var L = 0;
                                for (j = 1; j <= tot_rowM; j++) {
                                    var a = $('#tblDietChart_body').children('tr').eq(L);
                                    //var a = $('#WatchTable').closest('table').attr('id');
                                    //var b = a;
                                    var b = a.prop('id');
                                    L++;
                                    if (b != undefined)
                                    {
                                        var C = b.split('_');
                                    }
                                    var gkey = C[1];

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

                                        var sms = {
                                            Dml_Indicator: 'DI',
                                            diet_template_id: deittemplateId,
                                            time: row_data[0],
                                            created_by: $('#doctorId').val(),
                                            instructions: row_data[3],
                                            benefits: '',
                                            sodium_restriction: 0,
                                            food_diet_code: 0,
                                            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) {
                                                totalresponsesuccess++;
                                                debugger;

                                                if (L == totalresponsesuccess) {

                                                    $('#tblDietChart > tbody').empty();
                                                    $('#DietTableRowCount').val(0);
                                                    $('#txtTime').val('');
                                                    $('#txtfood').val('');
                                                    $('#txtQuantity').val('');
                                                    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
                                                    $('#txtInstructions').val('');
                                                    $('#txtdietname').val('');
                                                    if ($('#btndietsave').html() == 'Update') {
                                                        toastr.success("Diet Template Updated")
                                                    }
                                                    else {
                                                        toastr.success("Diet Template Added")
                                                    }
                                                    $('#btndietsave').html('Save');
                                                    $('#Copy_template').show();
                                                    Deittemlatelist();
                                                    location.reload();
                                                }
                                            }
                                        });
                                    }
                                }
                                //labtemlatelist();
                                //$('#tblDietChart > tbody').empty();
                                //$('#DietTableRowCount').val(0);
                                //$('#txtTime').val('');
                                //$('#txtfood').val('');
                                //$('#txtQuantity').val('');
                                //$("#radioBtn > a.active").removeClass("active").addClass("not-active");
                                //$('#txtInstructions').val('');
                                //$('#txtdietname').val('');
                                //if ($('#btndietsave').html() == 'Update') {
                                //    toastr.success("Diet Template Updated")
                                //}
                                //else {
                                //    toastr.success("Diet Template Added")
                                //}
                                //$('#btndietsave').html('Save');
                                //$('#Copy_template').show();
                                //Deittemlatelist();
                                //location.reload();
                            }
                        }
                    }
                }
            }
        });
    }
}

$('#btndietdelete').click(function () {
    var labval = {
        diet_template_id: $('#deitupdateid').val(),
        created_by: $('#doctorId').val(),
        Dml_Indicator: 'D'
    }
    if (confirm("Are you sure?")) {
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/DeitTemplate',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(labval),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    $('#tblDietChart > tbody').empty();
                    $('#DietTableRowCount').val(0);
                    $('#txtTime').val('');
                    $('#txtfood').val('');
                    $('#txtQuantity').val('');
                    $("#radioBtn > a.active").removeClass("active").addClass("not-active");
                    $('#txtInstructions').val('');
                    $('#txtdietname').val('');
                    $('#txtdietname').attr("disabled", false);
                    $('#btndietsave').html('Save');
                    $('#Copy_template').show();
                    $('#deit_template').show();
                    Deittemlatelist();
                }
                else {
                    console.log(data);
                }
            }

        });
        toastr.success("Diet Template Deleted Successfully")
    }
    else {
        return false;
    }
    location.reload();
});

// Deit template end




//  Prescription template start


//Added By Akshaya - new prescription

//health plix prescription


// Use event delegation to attach Autocomplete to dynamically generated elements
$(document).on('focus', '.durationinput', function () {
    $(this).autocomplete({
        source: function (request, response) {
            var inputValue = request.term; // Get the user's input
            debugger;
            // Generate duration options based on the input
            var options = [];
            if (!isNaN(inputValue) && inputValue > 0) {
                options.push(inputValue + " Days");
                options.push(inputValue + " Weeks");
                options.push(inputValue + " Months");
                options.push(inputValue + " Years");
            }

            // Provide the generated options to the autocomplete
            response(options);
        },
        minLength: 0, // Show suggestions even with no characters entered
        select: function (event, ui) {
            // Automatically populate the duration field with the selected value
            $(this).val(ui.item.value);
            $('#txttdno_duration').val('1')
            return false; // Prevent the value from being inserted twice
        },
    });
});



//$(document).on("focus", ".dosage-autocomplete", function () {
//    $(this).autocomplete({
//        source: ["1-0-1", "1-1-1", "1-0-1", /* Add your medicine names here */],
//        minLength: 0,
//        select: function (event, ui) {
//            // Automatically add a new row when a medicine is selected

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


// Medicine Type auto complete
$(document).on("focus", ".SelMedicineTypeA", function () {
    debugger;
    console.log(medicinetypearray)
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");

    $(this).autocomplete({
        source: medicinetypearray.map(item => item.medicine_type), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            MedicineTypeId = medicinetypearray.find(item => item.medicine_type === ui.item.value).medicine_type_id;
            MedicineTypeName = medicinetypearray.find(item => item.medicine_type === ui.item.value).medicine_type;
            newRow1.find('#txttdmedicine_type_id').val(MedicineTypeId)
            newRow1.find('#txttdmedicine_type_name').val(MedicineTypeName)

        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});


// when to take auto complete
$(document).on("focus", ".hndwenttoeatA1", function () {
    debugger;

    $(this).autocomplete({
        source: whentotakearray.map(item => item.when_to_eat_value), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            WhentoTakeId = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_id;
            when_to_eat_value = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_value;

            $('.Hidwhen_to_eat_id').val(WhentoTakeId)
            $('.hndwenttoeatA').val(when_to_eat_value)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("focus", ".hndwenttoeatA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");

    $(this).autocomplete({
        source: whentotakearray.map(item => item.when_to_eat_value), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {
            debugger;
            WhentoTakeId = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_id;
            when_to_eat_value = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_value;

            newRow1.find('#Hidwhen_to_eat_id').val(WhentoTakeId)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("change", ".hndwenttoeatA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    if (newRow1.find('#txttdhndwenttoeat').val() == "") {
        newRow1.find('#Hidwhen_to_eat_id').val(0);
    }
});


// Medicine frequency auto complete
$(document).on("focus", ".medicinefrequencyA1", function () {
    debugger;
    console.log(frequencyarray)

    $(this).autocomplete({
        source: frequencyarray.map(item => item.frequency_name), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            MedicineFrequencyId = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_master_id;
            MedicineFrequencyName = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_name;


            $('.Hidmedicine_frequencyId').val(MedicineFrequencyId)

            $('.medicinefrequencyA').val(MedicineFrequencyName)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("focus", ".medicinefrequencyA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    $(this).autocomplete({
        source: frequencyarray.map(item => item.frequency_name), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            MedicineFrequencyId = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_master_id;
            MedicineFrequencyName = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_name;

            newRow1.find('#Hidmedicine_frequencyId').val(MedicineFrequencyId)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

function Medicine_Frequency() {

    var PatientData = {
        Dml_Indicator: 'IPFR'
    }
    $.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);

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

    });
}

$(document).on("change", ".medicinefrequencyA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    if (newRow1.find('#txttdmedicinefrequency').val() == "") {
        newRow1.find('#Hidmedicine_frequencyId').val(0);
    }


});


//    // Use event delegation for dosage autocomplete
$(document).on("focusout", ".dosage-autocomplete", function () {
    debugger;
    var dosageInput = $(this);
    var dosageValue = $(this).val();

    // Check if the entered value is a non-empty string
    if (typeof dosageValue === "string" && /^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {
        // Split the value into parts
        var parts = dosageValue.split("-");
        var X = parts[0];
        var Y = parts[1] || "0";
        var Z = parts[2] || "0";

        // Update the dosage field with the formatted value
        var formattedDosage = X + " - " + Y + " - " + Z;
        dosageInput.val(formattedDosage);
    }
});


$(document).on("focus", ".dosage-autocomplete", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            debugger;

            $.ajax({
                async: true,
                url: "/CaseStudy/Medicine_Dosage?prescription_notes=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.notes, value: item.notes };
                    }))

                }
            })
        },
    });

});

$(document).on("focus", ".prescriptionNotes", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/CaseStudy/prescription_notes?prescription_notes=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.notes, value: item.notes };
                    }))

                }
            })
        },
    });
});

// Medicine Name Auto complete
$(document).on("focus", ".medicine-autocomplete", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                // url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + inputElement.val() + "&PharmacyID=" + $('#txtPharmacyID').val() + "&typeid=" + 0 + "&BranchId=" + $('#Pat_branchid').val(),
                url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + inputElement.val() + "&PharmacyID=" + $('#txtPharmacyID').val() + "&typeid=" + 0 + "&BranchId=" + $('#SelBranch').val() + "&is_pharmacy=" + $('#His_pharmacy').val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.medicine_status + "   ",
                            value: item.medicine_name,
                            medicine_type_id: item.medicine_type_id,
                            id: item.medicine_id
                        };
                    }))
                }
            })
        },
        select: function (event, ui) {
            var newRow = inputElement.closest("tr").clone();
            var newRow1 = inputElement.closest("tr");
            newRow.find("input").not("#priority").val("");
            var maxVal = Math.max.apply(null, $('.maxlenvalue').map(function () {
                return parseInt($(this).attr('maxlenvalue')) || 0;
            }).get());

            maxVal = maxVal + 1;
            newRow.find(".maxlenvalue").attr('maxlenvalue', maxVal);
            newRow.find("#priority").prop("checked", false);
            newRow.find("#priority").attr('name', 'optradio' + maxVal);

            var inputElement1 = $(event.target)
            var nextInput = newRow1.find("input[type='text']").eq(inputElement1.index() + 2);
            nextInput.focus();

            dosage1(ui.item.value, newRow1);
            if (newRow1.is(":last-child")) {

                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
                $('#tblmedicine tbody').sortable({
                    handle: '.draggable-handle',
                    helper: 'clone',
                    opacity: 1.5,
                    cursor: 'move',
                    update: function (event, ui) {
                        // Update serial numbers when a row is moved
                        updateSerialNumbers();
                    },
                });
            }
            newRow1.find('.deleteicon-btn').show();
        }
    });

});

// Add a global event listener for Enter key press
$(document).on("keydown", ".medicine-autocomplete", handleEnterKey);

//Function to handle appending a new row on Enter key press
function handleEnterKey(event) {
    debugger;
    if (event.keyCode === 13) { // Check if Enter key is pressed
        var inputElement = $(event.target);
        var currentRow = inputElement.closest("tr");
        var nextInput = currentRow.find("input[type='text']").eq(inputElement.index() + 2);
        currentRow.find('.deleteicon-btn').show();
        // If there's a next input in the same row, focus on it

        if (inputElement.val() != "") {
            nextInput.focus();

            // Clone the current row and append it
            if (currentRow.is(":last-child")) {

                var newRow = currentRow.clone();
                newRow.find("input").val(""); // Clear input values in the new row
                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
            }
        }

    }
}

// Add a global event listener for Enter key press
$(document).on("keydown", ".prescriptionNotes ", handleEnterKey1);

//Function to handle appending a new row on Enter key press
function handleEnterKey1(event) {
    debugger;
    if (event.keyCode === 13) { // Check if Enter key is pressed
        var inputElement = $(event.target);
        var currentRow = inputElement.closest("tr");

        currentRow.find('.deleteicon-btn').show();
        // If there's a next input in the same row, focus on it

        if (inputElement.val() != "") {

            // Clone the current row and append it
            if (currentRow.is(":last-child")) {
                var newRow = currentRow.clone();

                newRow.find("input").val(""); // Clear input values in the new row

                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
            }

            var lastRow = $("#tbl-medicine1 tr:last");
            var thirdColumn = lastRow.find("td:eq(2)");
            var inputInSecondColumn = thirdColumn.find("input[type='text']");
            inputInSecondColumn.focus();
        }

    }
}


$(document).on("focus", ".txtGenericName", function () {
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/CaseStudy/AutoCompletelist_genericName?generic_name=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    debugger;
                    response($.map(data, function (item) {
                        return { label: item.generic_name, value: item.generic_name, id: item.generic_id };
                    }));
                }
            })
        }
    });
});


$(document).on("click", ".add-row", function () {
    //var newRow = $(this).closest("tr").clone();
    //newRow.find("input").val(""); // Clear input values in the new row
    //$("#tbl-medicine1").append(newRow);
    addNewRow();
});
$(document).on("click", ".delete-row", function () {
    // Delete the clicked row
    $(this).closest("tr").remove();
});
// Event handler for When to take header click
$(".whentotakeheader").click(function (event) {
    debugger;
    event.stopPropagation(); // Prevent event propagation to the document
    $('#hndwenttoeatheader').show();
    $('#hndwenttoeatheader').focus();
});

$(".notesh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#prescriptionNotesheader').show();
    $('#prescriptionNotesheader').focus();
});

$(".durationh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#durationinputheader').show();
    $('#durationinputheader').focus();
});

$(".freaquencyh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#medicinefrequencyheader').show();
    $('#medicinefrequencyheader').focus();
});

$(".dosageautocompleteh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#dosageautocompleteheader').show();
    $('#dosageautocompleteheader').focus();
});

// Clicking anywhere in the document except inside the table header will hide the elements
$(document).click(function () {
    $('#hndwenttoeatheader, #prescriptionNotesheader, #durationinputheader, #medicinefrequencyheader, #dosageautocompleteheader').hide();
});
$('#hndwenttoeatheader').change(function () {
    debugger;
    var item = $(this);
    $('.hndwenttoeat').val(item.val());

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

    var item = $(this);
    $('.hndwenttoeat').val(item.val());

});

$('#prescriptionNotesheader').change(function () {
    var item = $(this);
    $('.prescriptionNotes').val(item.val());
});
$('#durationinputheader').change(function () {
    var item = $(this);
    $('.durationinput').val(item.val());
});
$('#medicinefrequencyheader').change(function () {
    debugger;
    var item = $(this);
    $('.medicinefrequency').val(item.val());
});
$('#dosageautocompleteheader').change(function () {
    var item = $(this);
    var dosageValue = $(this).val();

    // Check if the entered value is a non-empty string
    if (typeof dosageValue === "string" && /^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {
        // Split the value into parts
        var parts = dosageValue.split("-");
        var X = parts[0];
        var Y = parts[1] || "0";
        var Z = parts[2] || "0";
        // Update the dosage field with the formatted value
        var formattedDosage = X + " - " + Y + " - " + Z;
        $('.dosage-autocomplete').val(formattedDosage);
    }
    else {
        $('.dosage-autocomplete').val(item.val());
    }

});
function dosage1(selectedMedicine, row) {
    debugger;
    // 'row' is the row where the medicine was selected
    $('#txtNoDurationMedicine').val('');
    var medicine_name = selectedMedicine; // Use the selected medicine name
    if ($('#doctorId').val() != 'USD00035') {
        if (medicine_name.length > 0) {
            var medicine = {
                medicine_name: medicine_name,
                doctor_id: $('#pop_doctor_id').val(),
                medicine_type_id: $('#SelMedicineType').val()
            };
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/select_Medicine',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(medicine),
                success: function (data) {
                    debugger;
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        data1 = data1.data;
                        if (data1.Table.length > 0) {
                            row.find('#txttdMedicine_id').val(data1.Table[0].medicine_id);
                            row.find('#txttdno_duration').val(data1.Table[0].no_duration);
                            row.find('#txttdmedicine_type_id').val(data1.Table[0].medicine_type_id);
                            //row.find('#txttdmedicine_type').val(data1.Table[0].medicine_type_id);
                            row.find('#txttdmedicine_type').val(data1.Table[0].medicine_type);

                        }
                        if (data1.Table1.length > 0) {
                            // Assign values to the remaining fields in the same row
                            row.find('#txtGenericName').val(data1.Table1[0].generic_name);

                            row.find('#txttdhndwenttoeat').val(data1.Table1[0].when_to_eat_value);
                            row.find('#Hidwhen_to_eat_id').val(data1.Table1[0].how_to_take);

                            //row.find('#txttdmedicinefrequency').val(data1.Table1[0].medicine_frequency);
                            row.find('#Hidmedicine_frequencyId').val(data1.Table1[0].medicine_frequency);
                            row.find('#txttdmedicinefrequency').val(data1.Table1[0].frequency_name);

                            row.find('#txttddosage').val(data1.Table1[0].medicine_dosage);
                            row.find('#txttddurationinput').val(data1.Table1[0].duration);
                            row.find('#txttdprescriptionNotes').val(data1.Table1[0].instructions);

                        }
                        if (data1.Table1.length > 0) {
                            if (data1.Table1[0].no_duration == "1") {
                                row.find('#days').val("");
                            } else {
                                row.find('#days').val(data1.Table1[0].days_to_take);
                            }
                        }
                    } else {
                        console.log(data);
                    }
                }
            });
        }
    }
}
$('#BtnmedtableSubmit').click(function () {
    debugger;
    saveprescription(1)
})





function loadmedicineprescription() {
    debugger;
    var visit_id;
    if ($('#VisitReportID').val() != '') visit_id = $('#VisitReportID').val();
    else visit_id = $('#EditVisitReportID').val();

    var VisitreportId = {
        visit_report_id: visit_id,
        Dml_Indicator: 'S',
        is_pharmacy: $('#His_pharmacy').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    // Handle the case where no data is returned, if needed
                }
                else {
                    if (data1.length > 0) {
                        // Clear the existing table rows
                        bindingprescriptiontable(data1);
                    }
                }
            }
            else {

                console.error("AJAX request failed.");
            }
        },
        error: function (error) {

            console.error("AJAX error:", error);
        }
    });
}
function bindingprescriptiontable(data1) {
    debugger;
    // Assuming you have a JSON response called data1
    // $('#tblmedicine tbody').empty();
    if ($('#tblmedicine tbody tr:last #txtmedicineName').val() == '') {
        $('#tblmedicine tbody tr:last').remove();
    }


    if ($('#tblmedicine tbody tr').length > 0) {
        //$('#tblmedicine tbody').empty();
        $('#tblmedicine tbody tr').each(function (i, el) {
            var medicineprescriptionid = $(this).find('#txttdmedicine_prescription_id').val();
            if (medicineprescriptionid != "" && medicineprescriptionid != null) {
                $(this).remove();
            }
        })
    }



    var medval = '';
    var j = $('#tblmedicine tbody tr').length;


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

        // var j = parseInt(i) + 1
        j++
        var checked1 = '', checked2 = '', checked3 = '';
        if (emp.priority == 3) {
            checked1 = 'checked'
        }
        else if (emp.priority == 2) {
            checked2 = 'checked'
        }
        else if (emp.priority == 1) {
            checked3 = 'checked'
        }
        // Construct the table row based on your data
        var row = '<tr id="' + emp.medicine_prescription_id + '">' +
            '<td class="draggable-handle tblserialnumber" style="cursor:move !important" id="txttdserialnumber">' + j + '</td>' +

            '<td class="">' +
            //'<div class="dropdown-wrapper">' +
            //'<select class="form-control SelMedicineType" tabindex="44" name="SelMedicineType" id="txttdmedicine_type">' +
            //'<option value="' + emp.medicine_type_id + '">' + emp.medicine_type + '</option>' +
            //'</select>' +
            //'</div>' +
            '<input class="SelMedicineTypeA form-control" type="text" name="SelMedicineType" id="txttdmedicine_type" value="' + emp.medicine_type + '"/>' +
            '</td>' +
            '<td>' +
            '<input class="medicine-autocomplete form-control" type="text" value="' + emp.medicine_name + '"  id="txtmedicineName" />' +
            '<div style="margin-bottom:25px" class="maxlenvalue" maxlenvalue=' + j + '><label class="radbtn crbp" id="highhead"><input type="radio"  name="optradio' + j + '" value="3" id="priority"  ' + checked1 + '><span class="checkmark rbrblue"></span></label>' +
             '<label class="radbtn crbp" id="mediumhead"><input type="radio"  name="optradio' + j + '" value="2" id="priority"  ' + checked2 + '><span class="checkmark rbrred"></span></label>' +
             '<label class="radbtn crbp" id="lowhead"><input type="radio"  name="optradio' + j + '" value="1"  id="priority" ' + checked3 + '><span class="checkmark rbrgreen"></span></label></div>' +
            '</td>' +
            '<td>' +
            '<input class="form-control txtGenericName" type="text" value="' + emp.generic_name + '"  id="txtGenericName" />' +
            '</td>' +
            '<td>' +
            '<input class="dosage-autocomplete form-control" name="num_hyphen"  type="text" value="' + emp.medicine_dosage + '" id="txttddosage" />' +
            '</td>' +
            '<td class="header-cell when-to-take-header">' +
            //'<div class="dropdown-wrapper">' +
            //'<select class="form-control hndwenttoeat"  name="when_to_eat" id="txttdhndwenttoeat">' +
            //'<option value="' + emp.how_to_take + '">' + emp.when_to_eat_value + '</option>' +
            //'</select>' +
            //'</div>' +
            '<input class="hndwenttoeatA form-control" type="text" id="txttdhndwenttoeat" value="' + emp.when_to_eat_value + '"/>' +
            '</td>' +
            '<td>' +
            //'<select class="form-control medicinefrequency"  name="medicinefrequency" id="txttdmedicinefrequency">' +
            //'<option value="' + emp.medicine_frequency + '">' + emp.frequency_name + '</option>' +
            //'</select>' +
            '<input class="medicinefrequencyA form-control" type="text" name="medicinefrequency" id="txttdmedicinefrequency" value="' + emp.frequency_name + '"/>' +
            '</td>' +
            '<td>' +
            '<input class="durationinput form-control" type="text" value="' + emp.duration + '" id="txttddurationinput" />' +
            '</td>' +
            '<td>' +
            '<input type="text" class="form-control prescriptionNotes" value="' + emp.instructions + '" id="txttdprescriptionNotes" />' +
            '</td>' +
            '<td class="hidden"><input type="text" class="form-control txttdmedicine_type_id" value="' + emp.medicine_type_id + '" id="txttdmedicine_type_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdMedicine_id" value="' + emp.medicine_id + '" id="txttdMedicine_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdno_duration" value="' + emp.days_to_take + '" id="txttdno_duration" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdmedicine_prescription_id" value="' + emp.medicine_prescription_id + '" id="txttdmedicine_prescription_id" /></td>' +

            '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" value="' + emp.how_to_take + '" id="Hidwhen_to_eat_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" value="' + emp.medicine_frequency + '" id="Hidmedicine_frequencyId" /></td>' +


            '<td><button class="btn deleteicon-btn btn-sm" title="Delete Medicine" onclick="deleteMedicine(this,\'' + emp.medicine_prescription_id + '\')"><i class="fa fa-trash" aria-hidden="true"></i></button></td>' +
            '</tr>';

        medval += row;

    });
    // Append the constructed rows to the table
    $('#tblmedicine tbody').append(medval);
    addNewRow();
    //loadmedicinetype(medicinetypearray);
    //loadfrequencytype(frequencyarray);
    //loadwhentotake(whentotakearray)
}
function addNewRow() {
    // Get the current number of rows in the table
    var rowCount = $('#tblmedicine tbody tr').length + 1;
    var maxVal = Math.max.apply(null, $('.maxlenvalue').map(function () {
        return parseInt($(this).attr('maxlenvalue')) || 0;
    }).get());
    maxVal = maxVal + 1;
    var newRow = '<tr>' +
        '<td class="draggable-handle tblserialnumber" style="cursor:move !important" id="txttdserialnumber">' + rowCount + '</td>' + // Add serial number
        '<td class="header-cell when-to-take-header">' +
        //'<div class="dropdown-wrapper">' +
        //'<select class="form-control SelMedicineType" tabindex="44" name="SelMedicineType" id="txttdmedicine_type">' +
        //'</select>' +
        //'</div>' +
        '<input class="SelMedicineTypeA form-control" type="text" name="SelMedicineType" id="txttdmedicine_type" />' +
        '</td>' +
        '<td><input class="medicine-autocomplete form-control" type="text" id="txtmedicineName" />' +
         '<div style="margin-bottom:25px" class="maxlenvalue" maxlenvalue=' + maxVal + '><label class="radbtn crbp" id="highhead"><input type="radio" class="maxlenvalue" name="optradio' + maxVal + '" id="priority" value="3"><span class="checkmark rbrblue"></span></label>' +
             '<label class="radbtn crbp" id="mediumhead"><input type="radio"  name="optradio' + maxVal + '" id="priority" value="2"><span class="checkmark rbrred"></span></label>' +
             '<label class="radbtn crbp" id="lowhead"><input type="radio"  name="optradio' + maxVal + '" id="priority" value="1"><span class="checkmark rbrgreen"></span></label></div>' +
        '</td>' +
        '<td><input class="form-control txtGenericName" type="text" id="txtGenericName" /></td>' +
        '<td>' +
        '<input class="dosage-autocomplete form-control" type="text" name="num_hyphen" id="txttddosage" />' +
        '</td>' +
        '<td class="header-cell when-to-take-header">' +
        //'<div class="dropdown-wrapper">' +
        //'<select class="form-control hndwenttoeat" tabindex="44" name="when_to_eat" id="txttdhndwenttoeat">' +

        //'<option value=""></option>' +
        //'</select>' +
        //'</div>' +
        '<input class="hndwenttoeatA form-control" type="text" name="when_to_eat" id="txttdhndwenttoeat" value=""/>' +
        '</td>' +
        '<td>' +
        //'<select class="form-control medicinefrequency" tabindex="44" name="medicinefrequency" id="txttdmedicinefrequency">' +
        //'<option value=""></option>' +
        //'</select>' +
        '<input class="medicinefrequencyA form-control" type="text" name="medicinefrequency" id="txttdmedicinefrequency" value=""/>' +
        '</td>' +
        '<td>' +
        '<input class="durationinput form-control" type="text" id="txttddurationinput" />' +
        '</td>' +
        '<td>' +
        '<input type="text" class="form-control prescriptionNotes" id="txttdprescriptionNotes" />' +
        '</td>' +
        '<td class="hidden"><input type="text" class="form-control txttdmedicine_type_id" id="txttdmedicine_type_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdMedicine_id" id="txttdMedicine_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdno_duration" id="txttdno_duration" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdmedicine_prescription_id" id="txttdmedicine_prescription_id" /></td>' +

        '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" id="Hidwhen_to_eat_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" id="Hidmedicine_frequencyId" /></td>' +

        '<td><button class="btn deleteicon-btn btn-sm" title="Delete Medicine" onclick="deleteMedicine(this,0)"><i class="fa fa-trash" aria-hidden="true"></i></button></td></td>' +
        '</tr>';

    $('#tblmedicine tbody').append(newRow);
    // Enable row sorting with jQuery UI Sortable
    $('#tblmedicine tbody').sortable({
        handle: '.draggable-handle',
        helper: 'clone',
        opacity: 1.5,
        cursor: 'move',
        update: function (event, ui) {
            updateSerialNumbers(); // Update serial numbers when a row is moved
        },
    });
}
//function updateSerialNumbers() {
//    $('.tblserialnumber').each(function (index) {
//        $(this).text(index + 1);
//    });
//}

function updateSerialNumbers() {
    $("#tbl-medicine1 tr").each(function (index, row) {
        $(row).find("td:first").text(index + 1); // Update serial number
    });
}
function deleteMedicine(e, id) {
    debugger;
    var rowCount = $("#tblmedicine tbody tr").length;

    if (rowCount === 1) {

        toastr.warning("Cannot delete the last row.");
    }
    else {
        if (id == 0) {
            var rowToDelete = $(e).closest("tr");
            rowToDelete.remove();
            toastr.success("Medicine deleted");
            // Optionally, update the serial numbers for the remaining rows
            updateSerialNumbers();
        }
        else {

            var medicineId = id;
            var mdescription = {
                Dml_Indicator: 'D',
                medicine_prescription_id: medicineId,
                visit_report_id: $('#VisitReportID').val(),
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(mdescription),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        var data1 = data1.data;
                        var medval = '';


                        var rowToDelete = $(e).closest("tr");
                        rowToDelete.remove();
                        updateSerialNumbers();
                        toastr.success("Medicine deleted");

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

$('table').on('keyup', 'input[name="num_hyphen"]', function (e) {
    debugger
    var value = this.value;
    var id = this.id;
    var preg_check = /[^0-9-.]/g;
    if (preg_check.test(value)) {
        var parentRow = $(this).closest('tr');
        $(this).val(value.replace(/[^0-9-.]/g, ''));
    }
});
$('table').on('keyup', 'input[name="num_only"]', function (e) {
    debugger
    var value = this.value;
    var id = this.id;
    var preg_check = /[^0-9]/ig;
    if (preg_check.test(value)) {
        var parentRow = $(this).closest('tr');
        $(this).val(value.replace(/[^0-9-]/g, ''));
    }
});

function loadwhentoeat() {

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

                }
                else {

                    $('#hndwenttoeat').empty();
                    trs = '';
                    var defaultoption = '<option value="">--select--</option>';

                    whentotakearray = [];
                    whentotakearray = data1;
                    for (var i = 0; i < data1.length; i++) {
                        trs = trs + '<option value="' + data1[i].when_to_eat_id + '">' + data1[i].when_to_eat_value + '</option>';
                    }
                    $('#hndwenttoeat').append(defaultoption + trs);
                    copyprescriptionlist();
                }

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

    });
}

function copyprescriptionlist() {
    debugger
    var visiti = $('#VisitReportID').val();
    visiti = visiti.split('-');
    if (visiti[1] == "V001") {
        $('#copymed').hide();
    }
    else {
        $('#copymed').show();
        var VisitreportId = {
            patient_id: $('#Hdnpatient_id').val(),
            visit_report_id: $('#VisitReportID').val(),
            Dml_Indicator: 'CPL',
            doctor_id: ($('#hiddenRole_id').val() == 1) ? $('#myHiddenVar').val() : $('#doctorId').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(VisitreportId),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {
                        tr = $('<table class="table table-condensed body-borderless table_borderless m5" id="copyprestablel" />');
                        tr.append("<thead><tr><th>S No</th><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead><tbody>");
                    }
                    else {
                        var trlist = '', trlist_final = '', j = 0, k = 0, medtable, medtableend, medheadTable;
                        $('#copyprestablelist').empty();
                        for (var i = 0; i < data.length; i++) {
                            if (i < ((data.length) - 1)) {
                                if (data[i].visit_report_id == data[i + 1].visit_report_id) {
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                }
                                else {
                                    k = k + 1;
                                    medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                    medtableend = '</table></div></div>';
                                    medheadTable = '<thead><tr><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                    trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                    medtable, medtableend, medheadTable, trlist = '';
                                }
                            }
                            else if (i <= ((data.length) - 1)) {
                                k = k + 1;
                                trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                medtableend = '</table></div></div>';
                                medheadTable = '<thead><tr><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                medtable, medtableend, medheadTable, trlist = '';
                            }
                            else {
                                if (i == data.length) {
                                    k = k + 1;
                                    medtable = '<div class="table-responsive"><table class="table table-condensed body-borderless table_borderless id=' + k + '">';
                                    medtableend = '</table></div></div>';
                                    medheadTable = '<thead><th>Medicine Type</th><th>Medicine Name</th><th>Days To Take</th><th>Visit Date</th></tr></thead>';
                                    trlist = trlist + "<tr><td>" + data[i].medicine_type + "</td><td>" + data[i].medicine_name + "</td><td>" + data[i].days_to_take + "</td><td>" + data[i].visit_date + "</td></tr>";
                                }
                                else {
                                    trlist_final = trlist_final + '<div class="col-xs-12 table-responsive cus-pop-table-charts"><button class="prescopy-btn btn btn-xs btn-primaryuse"><div class="copy-pres-head pull-right" onclick=Copy_prescription_id("' + data[i].visit_report_id + '")>Copy Medicine</div></button>' + medtable + medheadTable + trlist + medtableend;
                                    trlist, medtable, medtableend, medheadTable = '';
                                }
                            }
                        }
                        $('#copyprestablelist').html(trlist_final);
                    }
                }
                else {
                    console.log(data);
                }
            }
        });
    }
    templatelist();
}

function templatelist() {
    debugger
    var Template = {
        doctor_id: ($('#hiddenRole_id').val() == 1) ? $('#myHiddenVar').val() : $('#doctorId').val(),
        Dml_Indicator: 'S',
        is_ip: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                $('#templatelist').empty();
                var data = data.data;
                var tr = '';
                if (jQuery.isEmptyObject((data))) {
                    // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                    tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                }
                else {
                    if (data.length <= 0) {
                        // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                        tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" class="Clscopytemplate" onclick=copytemplate(' + data[i].medicine_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div></a><br>';
                        }
                    }
                }
                $('#templatelist').html(tr);

                //commented by nandhini for performance issue on 20/09/2022 and lab prescription section removed already.
                //labtemlatelist();
                //labtype();

                //Deittemlatelist();

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


function loadMedicineType() {
    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#HiddenDoctorID').val(),
        is_pharmacy: $('#His_pharmacy').val(),
        hospital_id: $('#HdnHospitalid').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();
                    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);

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

    });
    //PatientNeuropathyLoad();
   // Prescriptiontemplatelist();
    loadwhentoeat();
}

//function loadwhentoeat() {

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

//                }
//                else {

//                    $('#hndwenttoeat').empty();
//                    trs = '';
//                    debugger;
//                    for (var i = 0; i < data1.length; i++) {
//                        debugger;
//                        trs = trs + '<option value="' + data1[i].when_to_eat_id + '">' + data1[i].when_to_eat_value + '</option>';
//                    }
//                    $('#hndwenttoeat').append(trs);
//                }
//                //hide_preloader('prescription_');
//            }
//            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');
//    }

//    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);
//    }

//});

//$('#selPatientType').change(function () {
//    Prescriptiontemplatelist();
//});


//function Prescriptiontemplatelist() {
//    debugger;
//    var Template = {
//        doctor_id: $('#doctorId').val(),
//        Dml_Indicator: 'TS',
//        is_ip: $('#selPatientType').val()
//    }
//    $.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") {
//                var data = data.data;
//                $('#Prescriptiontemplatelist').html('');
//                var tr = '';
//                if (jQuery.isEmptyObject((data))) {

//                }
//                else {
//                    console.log(data);
//                    for (var i = 0; i < data.length; i++) {
//                        tr = tr + '<a href="javascript:void(0)" onclick=OnPrescriptiontemplatelist(' + data[i].medicine_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div></a>';
//                    }

//                    if (data[0].lab_data_flag == 1) {
//                        $('#lab_data_flag').val(data[0].lab_data_flag);
//                    }
//                    else {
//                        $('#lab_data_flag').val('0');
//                    }
//                    if (data[0].medicine_data_flag == 1) {
//                        $('#phy_data_flag').val(data[0].medicine_data_flag);
//                    }
//                    else {
//                        $('#phy_data_flag').val('0');
//                    }
//                }
//                console.log('tr----->' + tr);
//                debugger;
//                $('#Prescriptiontemplatelist').html(tr);
//            }
//            else {
//                console.log(data);
//            }
//        }
//    });
//}

//function OnPrescriptiontemplatelist(val) {
//    var Template = {
//        medicine_template_id: val,
//        Dml_Indicator: 'SS'
//    }
//    $.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") {
//                var data = data.data;
//                debugger;
//                var tr = '';
//                if (jQuery.isEmptyObject((data))) {

//                }
//                else {
//                    $('#PreTableRowCount').val(0);
//                    $('#tblDietChart').DataTable().destroy();
//                    $('#tbl-medicine > tbody').empty();
//                    $('#txtPrescriptionName').val('');
//                    for (var i = 0; i < data.length; i++) {
//                        var sess_key_pre;
//                        var rowcount = $.trim($('#PreTableRowCount').val());
//                        var tot_row = (Number(rowcount) + 1);
//                        var ikey_pre = '';
//                        var sess_data_pre = data[i].medicine_name + "," + data[i].how_to_take + "," + data[i].days_to_take + "," + "1" + "," + data[i].morning + "," + data[i].afternoon + "," + data[i].night + "," + ((data[i].instructions != "" && data[i].instructions != null) ? data[i].instructions : "") + "," + data[i].medicine_type_id + "," + data[i].medicine_dosage + "," + data[i].medicine_unit + "," + data[i].generic_name + "," + data[i].evening + "," + data[i].when_to_eat_value + "," + data[i].medicine_type + "," + data[i].priority;

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

//                            ikey_pre = 'row' + tot_row;
//                        }

//                        sessionStorage.setItem(ikey_pre, sess_data_pre);

//                        var medicine_unit = data[i].medicine_unit;
//                        var medicineUnit = '';
//                        if (medicine_unit == 1) {
//                            medicineUnit = 'gm';
//                        }
//                        else if (medicine_unit == 2) {
//                            medicineUnit = 'mg';
//                        }
//                        else if (medicine_unit == 3) {
//                            medicineUnit = 'units';
//                        }
//                        else if (medicine_unit == 4) {
//                            medicineUnit = 'mcg';
//                        }
//                        else if (medicine_unit == 5) {
//                            medicineUnit = 'ng';
//                        }
//                        else if (medicine_unit == 6) {
//                            medicineUnit = 'ml';
//                        }
//                        else if (medicine_unit == 7) {
//                            medicineUnit = '%';
//                        }
//                        else if (medicine_unit == 8) {
//                            medicineUnit = '';
//                        }
//                        var medicine_dosage = data[i].medicine_dosage;
//                        var dosage = '';
//                        if (medicine_dosage == null || medicine_dosage == '') {
//                            dosage = '';
//                        }
//                        else {
//                            dosage = medicine_dosage + medicineUnit;
//                        }
//                        //var Durations = $('#hndduration').val();
//                        //var day = $('#days').val();
//                        //var days = 0;
//                        //if (Durations == 1) {
//                        //    days = day;
//                        //}
//                        //else if (Durations == 2) {
//                        //    days = ((day) * (7));
//                        //}
//                        //else if (Durations == 3) {
//                        //    days = ((day) * (30));
//                        //}
//                        var how_to_take = '';
//                        if (data[i].how_to_take == 1) {
//                            how_to_take = 'Before Food';
//                        }
//                        else if (data[i].how_to_take = 2) {
//                            how_to_take = 'With Food';
//                        }
//                        else {
//                            how_to_take = 'After Food';
//                        }

//                        var color = '';
//                        if (data[i].priority == 1) {
//                            color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
//                        }
//                        else if (data[i].priority == 2) {
//                            color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
//                        }
//                        else if (data[i].priority == 3) {
//                            color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
//                        }
//                        else {
//                            color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
//                        }


//                        var value = "<tr id='t_" + ikey_pre + "'><td>" + data[i].medicine_type + "</td><td style='text-transform: capitalize;'>" + color + data[i].medicine_name + "</td><td>" + data[i].when_to_eat_value + "</td><td>" + data[i].days_to_take + "</td><td>" + ((data[i].instructions != "" && data[i].instructions != null) ? data[i].instructions : "") + "</td><td>" + data[i].morning + "</td><td>" + data[i].afternoon + "</td><td>" + data[i].evening + "</td><td>" + data[i].night + "</td><td><button title='edit' class='edit btn btn-primary btn-xs mr-10' onclick='medicineedit(\"" + ikey_pre + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' onclick='medicinedelete(\"" + ikey_pre + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
//                        $('#medicine_template_id').val(data[i].medicine_template_id);
//                        $('#txtPrescriptionName').val(data[i].template_name);
//                        debugger;
//                        //$('#selPatientType').val(data[i].is_ip);
//                        $('#tbl-medicine > tbody:last').append(value);
//                        $('#tbl-medicine').DataTable();
//                        $('#PreTableRowCount').val(tot_row);
//                        $('#btnPrescriptionsave').html('Update');
//                        $('#btnPrescriptiondelete').show();
//                        $('#txtPrescriptionName').attr("disabled", true);
//                    }
//                }

//                $('#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('');
//                $('#txtGenericName').val('');
//                $('#lblGenericName').html('');

//                //when_to eat reset
//                $('#before_food').prop('checked', true);
//                $('#with_food').prop('checked', false);
//                $('#after_food').prop('checked', false);
//                $('.when_to_eat_disp').text('Before Food');
//                $('p.before_food').addClass('text_before_btn');
//                $('p.with_food').removeClass('text_before_btn');
//                $('p.after_food').removeClass('text_before_btn');
//                $('#hndwenttoeat').val(1);
//                //duration reset
//                $('#duration_days').prop('checked', true);
//                $('#duration_week').prop('checked', false);
//                $('#duration_month').prop('checked', false);
//                $('p.duration_days').addClass('text_before_btn');
//                $('p.duration_week').removeClass('text_before_btn');
//                $('p.duration_month').removeClass('text_before_btn');
//                $('.duration_disp').html('Days');
//                $('#hndduration').val(1);

//                $('#prescriptionNotesToggle').hide();
//                $('#Prescription_template').hide();
//            }
//            else {
//                console.log(data);
//            }
//        }
//    });
//}


//function dosage_old() {
//    var medicine_name = $('#medicine_name').val();

//    if (medicine_name.length > 0) {
//        var medicine = {
//            medicine_name: medicine_name,
//        }

//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/PatientDashboard/select_Medicine',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(medicine),
//            success: function (data) {
//                //alert(data);
//                var data1 = JSON.parse(data);
//                if (data1.msg == "Success") {
//                    var data1 = data1.data;
//                    if (data1.length > 2) {
//                        //$("#dosage").attr("readonly", true);


//                        $.each(data1, function (i, emp) {
//                            var dosage = emp.medicine_dosage;
//                            //alert(dosage);
//                            $('#dosage').val(dosage);
//                            $('#SelUnit').val(emp.medicine_type);
//                            $('#SelMedicineType').val(emp.medicine_type_id);
//                            if (emp.generic_name == '' || emp.generic_name == null) {
//                                $('#txtGenericName').val(emp.generic_name);
//                                $('#lblGenericName').html(emp.generic_name);
//                                $('#txtGenericName').show();
//                                $('#lblGenericName').hide();
//                            }
//                            else {
//                                $('#txtGenericName').val(emp.generic_name);
//                                $('#lblGenericName').html(emp.generic_name);
//                                $('#txtGenericName').hide();
//                                $('#lblGenericName').show();
//                            }
//                        });
//                    }
//                    else {
//                        // $("#dosage").attr("readonly", false);
//                    }
//                    var medicine_names = $('#medicine_name').val();
//                    var medicine_names_temp = medicine_names.split('/');
//                    if (medicine_names_temp.length > 2) {
//                        medicine_names = medicine_names_temp[0] + '/' + medicine_names_temp[1];
//                    }
//                    else {
//                        medicine_names = medicine_names_temp[0];
//                    }
//                    $('#medicine_name').val(medicine_names);
//                }
//                else {
//                    console.log(data);
//                }
//            }
//        });
//    }
//}


//function dosage() {
//    var medicine_name = $('#medicine_name').val();

//    if (medicine_name.length > 0) {
//        var medicine = {
//            medicine_name: medicine_name,
//            doctor_id: $('#doctorId').val(),
//        }

//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/PatientDashboard/select_Medicine',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(medicine),
//            success: function (data) {
//                var data1 = JSON.parse(data);
//                if (data1.msg == "Success") {
//                    var data1 = data1.data;
//                    if (data1.length > 2) {
//                        //$("#dosage").attr("readonly", true);

//                        if (data1.Table1.length > 0) {
//                            if (data1.Table1[0].generic_name == '' || data1.Table1[0].generic_name == null) {
//                                $('#SelMedicineType').val(data1.Table[0].medicine_type_id);
//                                $('#txtGenericName').val(data1.Table[0].generic_name);
//                            }
//                            else {
//                                $('#SelMedicineType').val(data1.Table1[0].medicine_type_id);
//                                $('#txtGenericName').val(data1.Table1[0].generic_name);
//                            }
//                            $('#hndwenttoeat').val(data1.Table1[0].how_to_take);
//                            $('#days').val(data1.Table1[0].days_to_take);
//                            $('#mor').val(data1.Table1[0].morning);
//                            $('#aft').val(data1.Table1[0].afternoon);
//                            //$('#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').val(data1.Table[0].generic_name);
//                        }
//                        else {
//                            $('#txtGenericName').val('');
//                        }
//                    }
//                    else {
//                        // $("#dosage").attr("readonly", false);
//                    }


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


//    }
//}



//$('.btn_dec_mor').click(function () {
//    var morning = $('#mor').val();
//    if (morning < "1") {
//        $('#btn_dec').attr('disabled', true);
//    }
//    else {
//        morning = Number(morning) - 1;
//        $('#mor').val(morning);
//    }
//});

//$('.btn_inc_mor').click(function () {
//    debugger;
//    var mor = $('#mor').val();
//    if (mor > "4") {
//        $('#btn_inc_mor').attr('disabled', true);
//    }
//    else {
//        mor = Number(mor) + 1;
//        $('#mor').val(mor);
//    }
//});

//$('.btn_dec_aft').click(function () {
//    var aft = $('#aft').val();
//    if (aft < "1") {
//        $('#btn_dec_aft').attr('disabled', true);
//    }
//    else {
//        aft = Number(aft) - 1;
//        $('#aft').val(aft);
//    }
//});

//$('.btn_inc_aft').click(function () {
//    var aft = $('#aft').val();
//    if (aft > "4") {
//        $('#btn_inc_aft').attr('disabled', true);
//    }
//    else {
//        aft = Number(aft) + 1;
//        $('#aft').val(aft);
//    }
//});


//$('.btn_dec_eve').click(function () {
//    var eve = $('#eve').val();
//    if (eve < "1") {
//        $('#btn_dec_eve').attr('disabled', true);
//    }
//    else {
//        eve = Number(eve) - 1;
//        $('#eve').val(eve);
//    }
//});

//$('.btn_inc_eve').click(function () {
//    var eve = $('#eve').val();
//    if (eve > "4") {
//        $('#btn_inc_eve').attr('disabled', true);
//    }
//    else {
//        eve = Number(eve) + 1;
//        $('#eve').val(eve);
//    }
//});

//$('.btn_dec_nit').click(function () {
//    var nit = $('#nit').val();
//    if (nit < "1") {
//        $('#btn_dec_nit').attr('disabled', true);
//    }
//    else {
//        nit = Number(nit) - 1;
//        $('#nit').val(nit);
//    }
//});

//$('.btn_inc_nit').click(function () {
//    var nit = $('#nit').val();
//    if (nit > "4") {
//        $('#btn_inc_nit').attr('disabled', true);
//    }
//    else {
//        nit = Number(nit) + 1;
//        $('#nit').val(nit);
//    }
//});



//$('#radioBtn a').on('click', function () {
//    debugger;
//    var sel = $(this).data('title');
//    var tog = $(this).data('toggle');
//    $('#' + tog).prop('value', sel).trigger('change');

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

//});

//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);
//    }
//});

//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);
//    }
//}


//$('#ADD_Medicine').click(function () {
//    debugger;
//    var mor = $('#mor').val();
//    var aft = $('#aft').val();
//    var nit = $('#nit').val();

//    var did = $('#ADD_Medicine').attr("data-id");
//    var navigation = $('#ADD_Medicine').attr("data-nav");
//    var name = $('#ADD_Medicine').attr("data-name");
//    var columntype = $('#ADD_Medicine').attr("data-type");

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

//                     return;
//                 }
//                 else {

//                     if (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();
//                     var days = 0;
//                     if (Durations == 1) {
//                         days = day;
//                     }
//                     else if (Durations == 2) {
//                         days = ((day) * (7));
//                     }
//                     else if (Durations == 3) {
//                         days = ((day) * (30));
//                     }
//                     if (day==9999) {
//                         days = "Daily";
//                     }

//                     var days1 = days;
//                     if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
//                         $('#PSelMedicineType').show();
//                         $('#PSelMedicineType').fadeOut(8000);
//                         $('#PSelMedicineType').html('Select Types');
//                         $('#SelMedicineType').focus();
//                         $('#SelMedicineType :selected').val('0');
//                         return false;
//                     }
//                     if ($.trim($('#medicine_name').val()) == "") {
//                         $('#Pmedicine_name').show();
//                         $('#Pmedicine_name').fadeOut(8000);
//                         $('#Pmedicine_name').html('Enter Medicine Name');
//                         $('#medicine_name').focus();
//                         $('#medicine_name').val('');
//                         return false;
//                     }
//                     if ($.trim($('#days').val()) == "") {
//                         $('#Pdays').show();
//                         $('#Pdays').fadeOut(8000);
//                         $('#Pdays').html('Enter days');
//                         $('#days').focus();
//                         $('#days').val('');
//                         return false;
//                     }

//                     var medicineType = $('#dosage').val();
//                     var priority = $("input[name='optradio']:checked").val();

//                     if (priority > 0) {
//                         priority = priority;
//                     }
//                     else {
//                         priority = 0;
//                     }

//                     var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
//                     max_quantity = parseFloat(max_quantity) * parseFloat(days);

//                     var sess_key_pre;
//                     var rowcount = $.trim($('#PreTableRowCount').val());
//                     var tot_row = (Number(rowcount) + 1);
//                     var ikey_pre = '';
//                     var sess_data_pre = $('#medicine_name').val() + "," + $('#hndwenttoeat').val() + "," + days + "," + $('#hndduration').val() + "," + $('#mor').val() + "," + $('#aft').val() + "," + $('#nit').val() + "," + $('#prescriptionNotes').val() + "," + $('#SelMedicineType').val() + "," + $('#dosage').val() + "," + $('#SelUnit').val() + "," + $('#txtGenericName').val() + "," + $('#eve').val() + "," + $('#hndwenttoeat :selected').html() + "," + $('#SelMedicineType :selected').html() + "," + priority + "," + max_quantity;


//                     if (rowcount >= 1) {
//                         $('#tbl-medicine').DataTable().destroy();
//                         var getEid = $('#tbl-medicine  tr').last();
//                         var actId = getEid.prop('id');
//                         var afterSplit = actId.split('row');
//                         afterInc = parseInt(afterSplit[1]) + 1;
//                         console.log(afterInc);
//                         ikey_pre = 'row' + afterInc;
//                     }
//                     else {

//                         ikey_pre = 'row' + tot_row;
//                     }

//                     sessionStorage.setItem(ikey_pre, sess_data_pre);


//                     var Durations = $('#hndduration').val();
//                     var day = $('#days').val();
//                     var days = 0;
//                     if (Durations == 1) {
//                         days = day;
//                     }
//                     else if (Durations == 2) {
//                         days = ((day) * (7));
//                     }
//                     else if (Durations == 3) {
//                         days = ((day) * (30));
//                     }
//                     if (day == 9999) {
//                         days = "Daily";
//                     }

//                     var color = '';
//                     if (priority == 1) {
//                         color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
//                     }
//                     else if (priority == 2) {
//                         color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
//                     }
//                     else if (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;';
//                     }

//                     var value = "<tr id='t_" + ikey_pre + "'><td>" + $('#SelMedicineType :selected').html() + "</td><td style='text-transform: capitalize;'>" + color + $('#medicine_name').val() + "</td><td>" + $('#hndwenttoeat :selected').html() + "</td><td>" + days + "</td><td>" + $('#prescriptionNotes').val() + "</td><td>" + $('#mor').val() + "</td><td>" + $('#aft').val() + "</td><td>" + $('#eve').val() + "</td><td>" + $('#nit').val() + "</td><td><button title='edit' class='edit btn btn-primary btn-xs mr-10' data-id='TCP_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick='medicineedit(\"" + ikey_pre + "\",this)'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' data-id='TCP_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick='medicinedelete(\"" + ikey_pre + "\",this)'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

//                     $('#tbl-medicine > tbody:last').append(value);
//                     $('#tbl-medicine').DataTable();
//                     $('#PreTableRowCount').val(tot_row);

//                     $('#SelMedicineType').val('0');
//                     $('#food').val('1');
//                     $('#medicine_name').val('');
//                     $('#days').val('');
//                     $('#dosage').val('');
//                     $('input:checkbox').prop('checked', false);
//                     $('#mor').val(0);
//                     $('#aft').val(0);
//                     $('#eve').val(0);
//                     $('#nit').val(0);
//                     $('#prescriptionNotes').val('');
//                     $('#txtGenericName').val('');
//                     $('#lblGenericName').html('');

//                     //when_to eat reset
//                     $('#before_food').prop('checked', true);
//                     $('#with_food').prop('checked', false);
//                     $('#after_food').prop('checked', false);
//                     $('.when_to_eat_disp').text('Before Food');
//                     $('p.before_food').addClass('text_before_btn');
//                     $('p.with_food').removeClass('text_before_btn');
//                     $('p.after_food').removeClass('text_before_btn');
//                     $('#hndwenttoeat').val(1);
//                     //duration reset
//                     $('#duration_days').prop('checked', true);
//                     $('#duration_week').prop('checked', false);
//                     $('#duration_month').prop('checked', false);
//                     $('p.duration_days').addClass('text_before_btn');
//                     $('p.duration_week').removeClass('text_before_btn');
//                     $('p.duration_month').removeClass('text_before_btn');
//                     $('.duration_disp').html('Days');
//                     $('#hndduration').val(1);
//                     $('#prescriptionNotesToggle').hide();
//                     //$('#diet_btn').attr("data-toggle", "tab");
//                     //$('#prescription_btn').attr("data-toggle", "tab");


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

//                     $("input[name='optradio']").prop('checked', false);
//                 }
//             }
//         }
//     });
//});

//function medicineedit(val) {
//    $('#ADD_Medicine').hide();
//    $('#Update_Medicine').show();
//    $('#hddn_medicine_prescription_id').val(val);

//    var gkey = val;
//    var row_data_per = sessionStorage.getItem(gkey);
//    console.log('row_data_per------>' + row_data_per);
//    var row_data_split = row_data_per.split(',');

//    $('#medicine_name').val(row_data_split[0]);
//    $('#hndwenttoeat').val(row_data_split[1]);
//    debugger;
//    if (row_data_split[1] == 1) {
//        $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//        $("input:radio.before_food").prop('checked', true);
//        $('.when_to_eat_disp').html('Before Food');
//        $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//        $('.radio_wrapper_1 > .before_food').addClass('text_before_btn');
//    }
//    else if (row_data_split[1] == 2) {
//        $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//        $("input:radio.with_food").prop('checked', true);
//        $('.when_to_eat_disp').html('With Food');
//        $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//        $('.radio_wrapper_1 > .with_food').addClass('text_before_btn');
//    }
//    else {
//        $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//        $("input:radio.after_food").prop('checked', true);
//        $('.when_to_eat_disp').html('After Food');
//        $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//        $('.radio_wrapper_1 > .after_food').addClass('text_before_btn');
//    }
//    $('.radio_wrapper_2 > .duration_disp').text('Days');
//    if (row_data_split[2] == "Daily") {
//        $('#days').val(9999);
//    }
//    else {
//        $('#days').val(row_data_split[2]);
//    }
//   // $('#days').val(row_data_split[2]);
//    $('#hndduration').val(row_data_split[3]);
//    debugger;
//    if (row_data_split[1] == 9 || row_data_split[1] == 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');
//    }
//    $('#mor').val(row_data_split[4]);
//    $('#aft').val(row_data_split[5]);
//    $('#nit').val(row_data_split[6]);
//    $('#prescriptionNotes').val(row_data_split[7]);
//    $('#SelMedicineType').val(row_data_split[8]);
//    $('#dosage').val(row_data_split[9]);
//    $('#SelUnit').val(row_data_split[10]);
//    $('#txtGenericName').val(row_data_split[11]);
//    $('#eve').val(row_data_split[12]);


//    if (row_data_split[15] == 3) {
//        $("#high").prop("checked", true);
//    }
//    else if (row_data_split[15] == 2) {
//        $("#medium").prop("checked", true);
//    }
//    else if (row_data_split[15] == 1) {
//        $("#low").prop("checked", true);
//    }
//    else { }
//}

//commented by nandhini on 15/03/2022
//function medicineedit(val, event) {
//    debugger;

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

//                     return;
//                 }
//                 else {
//                     $('#ADD_Medicine').hide();
//                     $('#Update_Medicine').show();
//                     $('#hddn_medicine_prescription_id').val(val);

//                     var gkey = val;
//                     var row_data_per = sessionStorage.getItem(gkey);
//                     console.log('row_data_per------>' + row_data_per);
//                     var row_data_split = row_data_per.split(',');

//                     $('#medicine_name').val(row_data_split[0]);
//                     $('#hndwenttoeat').val(row_data_split[1]);
//                     debugger;
//                     if (row_data_split[1] == 1) {
//                         $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//                         $("input:radio.before_food").prop('checked', true);
//                         $('.when_to_eat_disp').html('Before Food');
//                         $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//                         $('.radio_wrapper_1 > .before_food').addClass('text_before_btn');
//                     }
//                     else if (row_data_split[1] == 2) {
//                         $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//                         $("input:radio.with_food").prop('checked', true);
//                         $('.when_to_eat_disp').html('With Food');
//                         $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//                         $('.radio_wrapper_1 > .with_food').addClass('text_before_btn');
//                     }
//                     else {
//                         $("input[type='radio'][name='when_to_eat']").prop('checked', false);
//                         $("input:radio.after_food").prop('checked', true);
//                         $('.when_to_eat_disp').html('After Food');
//                         $('.radio_wrapper_1 > p').removeClass('text_before_btn');
//                         $('.radio_wrapper_1 > .after_food').addClass('text_before_btn');
//                     }
//                     $('.radio_wrapper_2 > .duration_disp').text('Days');

//                     $('#days').val(row_data_split[2]);
//                     $('#hndduration').val(row_data_split[3]);
//                     debugger;
//                     if (row_data_split[1] == 9 || row_data_split[1] == 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');
//                     }
//                     $('#mor').val(row_data_split[4]);
//                     $('#aft').val(row_data_split[5]);
//                     $('#nit').val(row_data_split[6]);
//                     $('#prescriptionNotes').val(row_data_split[7]);
//                     $('#SelMedicineType').val(row_data_split[8]);
//                     $('#dosage').val(row_data_split[9]);
//                     $('#SelUnit').val(row_data_split[10]);
//                     $('#txtGenericName').val(row_data_split[11]);
//                     $('#eve').val(row_data_split[12]);


//                     if (row_data_split[15] == 3) {
//                         $("#high").prop("checked", true);
//                     }
//                     else if (row_data_split[15] == 2) {
//                         $("#medium").prop("checked", true);
//                     }
//                     else if (row_data_split[15] == 1) {
//                         $("#low").prop("checked", true);
//                     }
//                     else { }
//                 }
//             }
//         }
//     });
//}

//function medicinedelete(val, event) {
//    sessionStorage.removeItem(val);
//    $('#t_' + val).remove();
//    var a = $.trim($('#PreTableRowCount').val());
//    var a = (a) - (1);
//    $('#PreTableRowCount').val(a);
//}

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

//                     return;
//                 }
//                 else {
//                     sessionStorage.removeItem(val);
//                     $('#t_' + val).remove();
//                     var a = $.trim($('#PreTableRowCount').val());
//                     var a = (a) - (1);
//                     $('#PreTableRowCount').val(a);
//                 }
//             }
//         }
//     });
//}


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

//    debugger;
//    var table_id = $('#hddn_medicine_prescription_id').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();
//    var days = 0;
//    if (Durations == 1) {
//        days = day;
//    }
//    else if (Durations == 2) {
//        days = ((day) * (7));
//    }
//    else if (Durations == 3) {
//        days = ((day) * (30));
//    }
//    if (day==9999) {
//        days = "Daily";
//    }
    
//    var days1 = days;
//    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
//        $('#PSelMedicineType').show();
//        $('#PSelMedicineType').fadeOut(8000);
//        $('#PSelMedicineType').html('Select Types');
//        $('#SelMedicineType').focus();
//        $('#SelMedicineType :selected').val('0');
//        return false;
//    }
//    if ($.trim($('#medicine_name').val()) == "") {
//        $('#Pmedicine_name').show();
//        $('#Pmedicine_name').fadeOut(8000);
//        $('#Pmedicine_name').html('Enter Medicine Name');
//        $('#medicine_name').focus();
//        $('#medicine_name').val('');
//        return false;
//    }
//    if ($.trim($('#days').val()) == "") {
//        $('#Pdays').show();
//        $('#Pdays').fadeOut(8000);
//        $('#Pdays').html('Enter days');
//        $('#days').focus();
//        $('#days').val('');
//        return false;
//    }
//    if ($.trim($('#days').val()) == "") {
//        $('#Pdays').show();
//        $('#Pdays').fadeOut(8000);
//        $('#Pdays').html('Enter days');
//        $('#days').focus();
//        $('#days').val('');
//        return false;
//    }
//    if (mor == 0 && aft == 0 && nit == 0) {
//        $('#Pmor').show();
//        $('#Pmor').fadeOut(8000);
//        $('#Pmor').html('Select the Frequency');
//        return false;
//    }

//    var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
//    max_quantity = parseFloat(max_quantity) * parseFloat(days);

//    debugger;
//    $('#ADD_Medicine').show();
//    $('#Update_Medicine').hide();
//    var priority = $("input[name='optradio']:checked").val();
//    if (priority > 0) {
//        priority = priority;
//    }
//    else {
//        priority = 0;
//    }



//    var sess_data_pre = $('#medicine_name').val() + "," + $('#hndwenttoeat').val() + "," + days + "," + $('#hndduration').val() + "," + $('#mor').val() + "," + $('#aft').val() + "," + $('#nit').val() + "," + $('#prescriptionNotes').val() + "," + $('#SelMedicineType').val() + "," + $('#dosage').val() + "," + $('#SelUnit').val() + "," + $('#txtGenericName').val() + "," + $('#eve').val() + "," + $('#hndwenttoeat :selected').html() + "," + $('#SelMedicineType :selected').html() + "," + priority + "," + max_quantity;
//    var ikey_pre = table_id;
//    sessionStorage.setItem(ikey_pre, sess_data_pre);


//    $('#tbl-medicine > tbody:last').empty();




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

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

//        if (row_data_split == null) {
//            //console.log(gkey + '--------->' + row_data);
//        }
//        if (row_data_split != null) {
//            row_data_split = row_data_split.split(',');

//            var wenttoeat = '';
//            if (row_data_split[1] == 1) {
//                wenttoeat = "Before Food";
//            }
//            else if (row_data_split[1] == 2) {
//                wenttoeat = "With Food";
//            }
//            else {
//                wenttoeat = "After Food";
//            }

//            var medicine_unit = row_data_split[10];
//            var medicineUnit = '';
//            if (medicine_unit == 1) {
//                medicineUnit = 'gm';
//            }
//            else if (medicine_unit == 2) {
//                medicineUnit = 'mg';
//            }
//            else if (medicine_unit == 3) {
//                medicineUnit = 'units';
//            }
//            else if (medicine_unit == 4) {
//                medicineUnit = 'mcg';
//            }
//            else if (medicine_unit == 5) {
//                medicineUnit = 'ng';
//            }
//            else if (medicine_unit == 6) {
//                medicineUnit = 'ml';
//            }
//            else if (medicine_unit == 7) {
//                medicineUnit = '%';
//            }
//            else if (medicine_unit == 8) {
//                medicineUnit = '';
//            }
//            var medicine_dosage = row_data_split[9];
//            var dosage = '';
//            if (medicine_dosage == null || medicine_dosage == '') {
//                dosage = '';
//            }
//            else {
//                dosage = medicine_dosage + medicineUnit;
//            }


//            var color = '';
//            if (row_data_split[15] == 1) {
//                color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
//            }
//            else if (row_data_split[15] == 2) {
//                color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
//            }
//            else if (row_data_split[15] == 3) {
//                color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
//            }
//            else {
//                color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
//            }

//            //var value = "<tr id='t_" + ikey_pre + "'><td>" + row_data_split[14] + "</td><td>" + row_data_split[0] + "</td><td>" + row_data_split[13] + "</td><td>" + row_data_split[2] + "</td><td>" + row_data_split[7] + "</td><td>" + row_data_split[4] + "</td><td>" + row_data_split[5] + "</td><td>"+row_data_split[12]+"</td><td>" + row_data_split[6] + "</td><td><button class='edit btn btn-primary btn-xs mr-10' onclick='medicineedit(\"" + ikey_pre + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='edit btn btn-primary btn-xs mr-10' onclick='medicinedelete(\"" + ikey_pre + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
//            var value = "<tr id='t_" + gkey + "'><td>" + row_data_split[14] + "</td><td>" + color + row_data_split[0] + "</td><td>" + row_data_split[13] + "</td><td>" + row_data_split[2] + "</td><td>" + row_data_split[7] + "</td><td>" + row_data_split[4] + "</td><td>" + row_data_split[5] + "</td><td>" + row_data_split[12] + "</td><td>" + row_data_split[6] + "</td><td><button title='edit' class='edit btn btn-primary btn-xs mr-10' onclick='medicineedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button title='delete' class='btn btn-danger btn-xs' onclick='medicinedelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
//            //gkey
//            $('#tbl-medicine > tbody:last').append(value);
//            $('#tbl - medicine').DataTable();
//        }
//    }


//    $('#PreTableRowCount').val(tot_row);

//    $('#SelMedicineType').val('0');
//    $('#food').val('1');
//    $('#medicine_name').val('');
//    $('#days').val('');
//    $('#dosage').val('');
//    $('input:checkbox').prop('checked', false);
//    $('#mor').val(0);
//    $('#aft').val(0);
//    $('#eve').val(0);
//    $('#nit').val(0);
//    $('#prescriptionNotes').val('');
//    $('#txtGenericName').val('');
//    $('#lblGenericName').html('');

//    //when_to eat reset
//    $('#before_food').prop('checked', true);
//    $('#with_food').prop('checked', false);
//    $('#after_food').prop('checked', false);
//    $('.when_to_eat_disp').text('Before Food');
//    $('p.before_food').addClass('text_before_btn');
//    $('p.with_food').removeClass('text_before_btn');
//    $('p.after_food').removeClass('text_before_btn');
//    $('#hndwenttoeat').val(1);
//    //duration reset
//    $('#duration_days').prop('checked', true);
//    $('#duration_week').prop('checked', false);
//    $('#duration_month').prop('checked', false);
//    $('p.duration_days').addClass('text_before_btn');
//    $('p.duration_week').removeClass('text_before_btn');
//    $('p.duration_month').removeClass('text_before_btn');
//    $('.duration_disp').html('Days');
//    $('#hndduration').val(1);
//    $('#prescriptionNotesToggle').hide();


//    $('#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');
//    $("input[name='optradio']").prop('checked', false);




//});



//$('#txtPrescriptionName').change(function () {
//    var labval = {
//        template_name: $('#txtPrescriptionName').val(),
//        doctor_id: $('#doctorId').val(),
//        Dml_Indicator: 'CHPT'
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/caseStudy/Medicine_template',
//        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 b;
//                    if (data1[0].msg == "already") {
//                        toastr.warning("Prescription template name already exists");
//                        $('#txtPrescriptionName').val('');
//                    }
//                    else {
//                    }
//                }
//            }
//            else {
//                console.log(data1);
//            }
//        }
//    });
//});



$('#btnPrescriptionsave').click(function () {
    debugger;
    if ($('#btnPrescriptionsave').html() == 'Update') {
       // Prescriptioninsert();
        if ($.trim(($('#selPatientType').val())) == "") {
            $('#PPatientType').show();
            $('#PPatientType').fadeOut(8000);
            $('#PPatientType').html('Select Type');
            $('#selPatientType').focus();
            return false;
        }

        var PrescriptionName = $('#txtPrescriptionName').val();
        if ($.trim((PrescriptionName)) == "") {
            $('#PtxtPrescriptionName').show();
            $('#PtxtPrescriptionName').fadeOut(8000);
            $('#PtxtPrescriptionName').html('Enter the template name');
            $('#txtPrescriptionName').focus();
            return false;
        }
        var PrebodyrowCount = $('#tbl-medicine >tbody >tr').length;
        if (PrebodyrowCount <= 0) {
            $('#PtxtPrescriptionName').show();
            $('#PtxtPrescriptionName').fadeOut(8000);
            $('#PtxtPrescriptionName').html('Enter the prescription details');
            $('#medicine_name').focus();
            return false;
        }
        var medicinetemplateId = '';
        if ($('#PreTableRowCount').val() > 0) {
            $('#loaderimg').show();
            var labval = {
                medicine_template_id: $('#medicine_template_id').val(),
                doctor_id: $('#doctorId').val(),
                Dml_Indicator: 'D'
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/caseStudy/Medicine_template',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(labval),
                success: function (data) {
                    var data = JSON.parse(data);
                    if (data.msg == "Success") {
                        Prescriptionupdate();
                    }
                    else {
                        console.log(data);
                    }
                }
            });
        }
    }

    else {
        Prescriptioninsert();
    }
    //$('#diet_btn').attr("data-toggle", "tab");
    //$('#labtest_btn').attr("data-toggle", "tab");
    $('#loaderimg').hide();
    $('#txtPrescriptionName').attr("disabled", false);
});

function Prescriptioninsert() {
    debugger;
    if ($.trim(($('#selPatientType').val())) == "") {
        $('#PPatientType').show();
        $('#PPatientType').fadeOut(8000);
        $('#PPatientType').html('Select Type');
        $('#selPatientType').focus();
        return false;
    }

    var PrescriptionName = $('#txtPrescriptionName').val();
    if ($.trim((PrescriptionName)) == "") {
        $('#PtxtPrescriptionName').show();
        $('#PtxtPrescriptionName').fadeOut(8000);
        $('#PtxtPrescriptionName').html('Enter the template name');
        $('#txtPrescriptionName').focus();
        return false;
    }
    //var PrebodyrowCount = $('#tbl-medicine >tbody >tr').length;
    //if (PrebodyrowCount <= 0) {
    //    $('#PtxtPrescriptionName').show();
    //    $('#PtxtPrescriptionName').fadeOut(8000);
    //    $('#PtxtPrescriptionName').html('Enter the prescription details');
    //    $('#medicine_name').focus();
    //    return false;
    //}
   // $('#tbl-medicine').addClass('us-loader-template-table');
    var medicinetemplateId = '';
   // if ($('#PreTableRowCount').val() > 0) {
        var labval = {
            template_name: $('#txtPrescriptionName').val(),
            doctor_id: $('#doctorId').val(),
            Dml_Indicator: 'CTI',
            is_ip: $('#selPatientType').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Medicine_template',
            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 watch_id = '';
                        if (data1.length > 0) {
                            for (var i = 0; i < data1.length; i++) {
                                medicinetemplateId = data1[0].medicine_template_id;
                            }
                            saveprescription(1, medicinetemplateId)
                            //var tot_rowM = $.trim($('#PreTableRowCount').val());
                            //var tot_rowM = $('#tbl-medicine_body tr').length;
                            //if (tot_rowM > 0) {
                            //    var L = 0, SL = 0;
                            //    for (j = 1; j <= tot_rowM; j++) {
                            //        var a = $('#tbl-medicine_body').children('tr').eq(L);
                            //        //var a = $('#WatchTable').closest('table').attr('id');
                            //        //var b = a;
                            //        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: 'TDI',
                            //                medicine_template_id: medicinetemplateId,
                            //                medicine_type_id: row_data[8],
                            //                medicine_name: row_data[0],
                            //                how_to_take: row_data[1],
                            //                morning: row_data[4],
                            //                afternoon: row_data[5],
                            //                evening: row_data[12],
                            //                night: row_data[6],
                            //                days_to_take: row_data[2],
                            //                medicine_dosage: row_data[9],
                            //                instructions: row_data[7],
                            //                medicine_unit: row_data[10],
                            //                generic_name: row_data[11],
                            //                priority: row_data[15],
                            //                max_quantity: row_data[16]
                            //            }
                            //            $.ajax({
                            //                async: true,
                            //                type: 'POST',
                            //                url: '/CaseStudy/Medicine_template',
                            //                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;
                            //                        SL++;

                            //                        if (SL == tot_rowM) {
                            //                            setTimeout(function () {
                            //                                Prescriptiontemplatelist();
                            //                                $('#tbl-medicine tbody').empty()
                            //                                //$('#PreTableRowCount').val(tot_row);

                            //                                $('#SelMedicineType').val('0');
                            //                                $('#food').val('1');
                            //                                $('#medicine_name').val('');
                            //                                $('#days').val('');
                            //                                $('#dosage').val('');
                            //                                $('input:checkbox').prop('checked', false);
                            //                                $('#mor').val(0);
                            //                                $('#aft').val(0);
                            //                                $('#eve').val(0);
                            //                                $('#nit').val(0);
                            //                                $('#prescriptionNotes').val('');
                            //                                $('#txtGenericName').val('');
                            //                                $('#lblGenericName').html('');

                            //                                //when_to eat reset
                            //                                $('#before_food').prop('checked', true);
                            //                                $('#with_food').prop('checked', false);
                            //                                $('#after_food').prop('checked', false);
                            //                                $('.when_to_eat_disp').text('Before Food');
                            //                                $('p.before_food').addClass('text_before_btn');
                            //                                $('p.with_food').removeClass('text_before_btn');
                            //                                $('p.after_food').removeClass('text_before_btn');
                            //                                $('#hndwenttoeat').val(1);
                            //                                //duration reset
                            //                                $('#duration_days').prop('checked', true);
                            //                                $('#duration_week').prop('checked', false);
                            //                                $('#duration_month').prop('checked', false);
                            //                                $('p.duration_days').addClass('text_before_btn');
                            //                                $('p.duration_week').removeClass('text_before_btn');
                            //                                $('p.duration_month').removeClass('text_before_btn');
                            //                                $('.duration_disp').html('Days');
                            //                                $('#hndduration').val(1);
                            //                                $('#prescriptionNotesToggle').hide();
                            //                                $('#btnPrescriptionsave').html('Save');
                            //                                $('#btnPrescriptiondelete').hide();
                            //                                $('#txtPrescriptionName').val('');
                            //                                $('#Prescription_template').show();
                            //                                $('#tbl-medicine').removeClass('us-loader-template-table');
                            //                                $('#PreTableRowCount').val(0);
                            //                            }, 3000);
                            //                            toastr.success("Prescription Template Saved");
                            //                            location.reload();
                            //                        }
                            //                    }
                            //                    else {
                            //                        console.log(data);
                            //                    }
                            //                }

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

}


function saveprescription(val, medicinetemplateId) {
    debugger;
    formChanged = false;
    var dmlindicator = "";
    if (val == 1) {
        dmlindicator = 'TDI';
        //  dmlindicator = 'MPIUX';
    }
    else {
        dmlindicator = 'MPIUXT';
    }

    var tableData = [];
    var tot_rowM = $('#tblmedicine >tbody >tr').length;
    if (tot_rowM > 0) {
        $('#loaderimg').show();
        $("#tblmedicine tbody tr").each(function () {
            var row = $(this);
            if (row.find("#txtmedicineName").val() !== '') {

                var mor = 0;
                var aft = 0;
                var nit = 0;
                var eve = 0;
                var max_quantity = 0;
                var daysInUnit = 0;
                var dosageValue = row.find("#txttddosage").val();
                dosageValue = dosageValue.replace(/\s*-\s*/g, "-");
                row.find("#txttddosage").val(dosageValue);
                if (typeof dosageValue === "string" && ((/^\s*\d+(?:\s*-\s*\d+)+\s*$/.test(dosageValue)) || (/^\s*\d.+(?:\s*-\s*\d.+)+\s*$/.test(dosageValue)))) {  ///^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {

                    // Split the value into parts
                    var parts = dosageValue.split('-');
                    if (parts.length == 3) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[2])) || 0;
                    }
                    else if (parts.length == 4) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[3])) || 0;
                        eve = parseFloat($.trim(parts[2])) || 0;
                    }
                }
                var txttdno_duration = row.find("#txttdno_duration").val();
                if (txttdno_duration !== '0') {
                    var text = row.find("#txttddurationinput").val();

                    var match = text.match(/^(\d+) (Days|Weeks|Months|Years)$/i);

                    if (match) {
                        var number = parseInt(match[1]);
                        var unit = match[2].toLowerCase();


                        switch (unit) {
                            case "days":
                                daysInUnit = number;
                                break;
                            case "weeks":
                                daysInUnit = number * 7;
                                break;
                            case "months":
                                daysInUnit = number * 30;
                                break;
                            case "years":
                                daysInUnit = number * 365;
                                break;
                            default:
                                daysInUnit = 0;
                        }



                        var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
                        max_quantity = parseFloat(max_quantity) * parseFloat(number);
                    }
                }
                else {
                    max_quantity = 1;
                    daysInUnit = 1
                } 
                
                var mdescription = {
                    Dml_Indicator: dmlindicator,
                    patient_id: $('#Hdnpatient_id').val(),
                    templatename: $('#templateName').val(),
                    visit_report_id: $('#VisitReportID').val(),
                    //medicine_type_id: parseInt(row.find("#txttdmedicine_type").val()),
                    medicine_type_id: parseInt(row.find("#txttdmedicine_type_id").val()),
                    medicine_type_name: row.find('#txttdmedicine_type').val(),
                    is_pharmacy: $('#His_pharmacy').val(),
                    medicine_name: row.find("#txtmedicineName").val(),
                    //how_to_take: parseInt(row.find("#txttdhndwenttoeat").val()),
                    how_to_take: parseInt(row.find("#Hidwhen_to_eat_id").val()),
                    morning: mor,
                    afternoon: aft,
                    evening: eve,
                    night: nit,
                    days_to_take: daysInUnit,
                    pmedicine_dosage: (row.find("#txttddosage").val() == '' ? "" : row.find("#txttddosage").val()),
                    medicine_dosage: (row.find("#txttddosage").val() == '' ? "" : row.find("#txttddosage").val()),
                    medicine_type: parseInt(row.find("#txttdmedicine_type_id").val()),
                    doctor_id: $('#doctorId').val(),
                    slot_start_time: $('#Hdnappointment_date').val(),
                    instructions: row.find("#txttdprescriptionNotes").val(),
                    medicine_unit: parseInt(row.find("#txttdmedicine_type").val()),
                    generic_name: row.find("#txtGenericName").val(),
                    max_quantity: max_quantity,
                    priority: row.find("#priority:checked").val(),
                    display_order: row.find("#txttdserialnumber").text(),
                    pharmacy_id: $('#txtPharmacyID').val(),
                    medicine_id: parseInt(row.find("#txttdMedicine_id").val()),
                    // medicine_frequency: parseInt(row.find("#txttdmedicinefrequency").val()),
                    medicine_frequency: parseInt(row.find("#Hidmedicine_frequencyId").val()),
                    medicine_prescription_id: parseInt(row.find("#txttdmedicine_prescription_id").val()),
                    duration: row.find("#txttddurationinput").val(),
                    BranchId: $('#hnDBranch_id').val(),
                    HospitalIdInt: $('#HdnHospitalidInt').val(),
                    // medicine_type_name: row.find("#txttdmedicine_type_name").val()
                    medicine_template_id: medicinetemplateId
                }
                tableData.push(mdescription);
            }
        });
        if (tableData.length > 0) {
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/Medicine_Prescription_Ins_Upd_XML',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(tableData),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        $('#loaderimg').hide();
                        var data1 = data1.data;

                        if (val == 1) {
                            toastr.success('Saved Successfully');
                            // bindingprescriptiontable(data1.Table)
                        }
                        else {

                            toastr.success('Template Saved Successfully',
                                {
                                    closeButton: false,
                                    progressBar: true,
                                    allowHtml: true,
                                    timeOut: 0,
                                })
                            setTimeout(function () {
                                //  templatelist();
                            }, 2000);
                            $('#myTemplateTitle').modal("toggle");
                        }

                    }
                }
            });
        }
        else {
            $('#loaderimg').hide();
        }
    }

    //if (val == 1) {
    //    diagnosis();
    //}

}

//function Prescriptionupdate() {
//    var PrescriptionName = $('#txtPrescriptionName').val();
//    if ($.trim((PrescriptionName)) == "") {
//        $('#PtxtPrescriptionName').show();
//        $('#PtxtPrescriptionName').fadeOut(8000);
//        $('#PtxtPrescriptionName').html('Enter the template name');
//        $('#txtPrescriptionName').focus();
//        return false;
//    }
//    $('#tbl-medicine').addClass('us-loader-template-table');
//    var medicinetemplateId = '';
//    if ($('#PreTableRowCount').val() > 0) {
//        var labval = {
//            template_name: $('#txtPrescriptionName').val(),
//            doctor_id: $('#doctorId').val(),
//            Dml_Indicator: 'CTI',
//            is_ip: $('#selPatientType').val()
//        }
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/caseStudy/Medicine_template',
//            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 watch_id = '';
//                        if (data1.length > 0) {
//                            for (var i = 0; i < data1.length; i++) {
//                                medicinetemplateId = data1[0].medicine_template_id;
//                            }
//                            debugger;
//                            //var tot_rowM = $.trim($('#PreTableRowCount').val());
//                            var tot_rowM = $('#tbl-medicine_body tr').length;
//                            if (tot_rowM > 0) {
//                                var L = 0, SL = 0;
//                                for (j = 1; j <= tot_rowM; j++) {
//                                    var a = $('#tbl-medicine_body').children('tr').eq(L);
//                                    //var a = $('#WatchTable').closest('table').attr('id');
//                                    //var b = a;
//                                    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: 'TDI',
//                                            medicine_template_id: medicinetemplateId,
//                                            medicine_type_id: row_data[8],
//                                            medicine_name: row_data[0],
//                                            how_to_take: row_data[1],
//                                            morning: row_data[4],
//                                            afternoon: row_data[5],
//                                            evening: row_data[12],
//                                            night: row_data[6],
//                                            days_to_take: row_data[2],
//                                            medicine_dosage: row_data[9],
//                                            instructions: row_data[7],
//                                            medicine_unit: row_data[10],
//                                            generic_name: row_data[11],
//                                            priority: row_data[15],
//                                            max_quantity: row_data[16]
//                                        }
//                                        $.ajax({
//                                            async: true,
//                                            type: 'POST',
//                                            url: '/CaseStudy/Medicine_template',
//                                            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;
//                                                    SL++;
//                                                    if (SL == tot_rowM) {
//                                                        setTimeout(function () {
//                                                            Prescriptiontemplatelist();
//                                                            $('#tbl-medicine tbody').empty();
//                                                            //$('#PreTableRowCount').val(tot_row);

//                                                            $('#SelMedicineType').val('0');
//                                                            $('#food').val('1');
//                                                            $('#medicine_name').val('');
//                                                            $('#days').val('');
//                                                            $('#dosage').val('');
//                                                            $('input:checkbox').prop('checked', false);
//                                                            $('#mor').val(0);
//                                                            $('#aft').val(0);
//                                                            $('#eve').val(0);
//                                                            $('#nit').val(0);
//                                                            $('#prescriptionNotes').val('');
//                                                            $('#txtGenericName').val('');
//                                                            $('#lblGenericName').html('');

//                                                            //when_to eat reset
//                                                            $('#before_food').prop('checked', true);
//                                                            $('#with_food').prop('checked', false);
//                                                            $('#after_food').prop('checked', false);
//                                                            $('.when_to_eat_disp').text('Before Food');
//                                                            $('p.before_food').addClass('text_before_btn');
//                                                            $('p.with_food').removeClass('text_before_btn');
//                                                            $('p.after_food').removeClass('text_before_btn');
//                                                            $('#hndwenttoeat').val(1);
//                                                            //duration reset
//                                                            $('#duration_days').prop('checked', true);
//                                                            $('#duration_week').prop('checked', false);
//                                                            $('#duration_month').prop('checked', false);
//                                                            $('p.duration_days').addClass('text_before_btn');
//                                                            $('p.duration_week').removeClass('text_before_btn');
//                                                            $('p.duration_month').removeClass('text_before_btn');
//                                                            $('.duration_disp').html('Days');
//                                                            $('#hndduration').val(1);
//                                                            $('#prescriptionNotesToggle').hide();
//                                                            $('#btnPrescriptionsave').html('Save');
//                                                            $('#btnPrescriptiondelete').hide();
//                                                            $('#txtPrescriptionName').val('');
//                                                            $('#Prescription_template').show();
//                                                            $('#tbl-medicine').removeClass('us-loader-template-table');
//                                                            $('#PreTableRowCount').val(0);
//                                                        }, 3000);
//                                                        toastr.success("Prescription Template Updated");


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

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

//}

//$('#btnPrescriptiondelete').click(function () {
//    var PrescriptionName = $('#txtPrescriptionName').val();
//    if ($.trim((PrescriptionName)) == "") {
//        $('#PtxtPrescriptionName').show();
//        $('#PtxtPrescriptionName').fadeOut(8000);
//        $('#PtxtPrescriptionName').html('Enter the template name');
//        $('#txtPrescriptionName').focus();
//        return false;
//    }
//    if (confirm("Are you sure?")) {
//        var medicinetemplateId = '';
//        if ($('#PreTableRowCount').val() > 0) {
//            var labval = {
//                medicine_template_id: $('#medicine_template_id').val(),
//                doctor_id: $('#doctorId').val(),
//                Dml_Indicator: 'D'
//            }
//            $.ajax({
//                async: true,
//                type: 'POST',
//                url: '/caseStudy/Medicine_template',
//                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;
//                        //$('#tbl-medicine > tbody:last').append(value);
//                        //$('#PreTableRowCount').val(tot_row);

//                        $('#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('');
//                        $('#txtGenericName').val('');
//                        $('#lblGenericName').html('');
//                        $('#txtPrescriptionName').attr("disabled", false);

//                        //when_to eat reset
//                        $('#before_food').prop('checked', true);
//                        $('#with_food').prop('checked', false);
//                        $('#after_food').prop('checked', false);
//                        $('.when_to_eat_disp').text('Before Food');
//                        $('p.before_food').addClass('text_before_btn');
//                        $('p.with_food').removeClass('text_before_btn');
//                        $('p.after_food').removeClass('text_before_btn');
//                        $('#hndwenttoeat').val(1);
//                        //duration reset
//                        $('#duration_days').prop('checked', true);
//                        $('#duration_week').prop('checked', false);
//                        $('#duration_month').prop('checked', false);
//                        $('p.duration_days').addClass('text_before_btn');
//                        $('p.duration_week').removeClass('text_before_btn');
//                        $('p.duration_month').removeClass('text_before_btn');
//                        $('.duration_disp').html('Days');
//                        $('#hndduration').val(1);
//                        $('#prescriptionNotesToggle').hide();
//                        $('#btnPrescriptionsave').html('Save');
//                        $('#btnPrescriptiondelete').hide();
//                        $('#txtPrescriptionName').val('');
//                        $('#Prescription_template').show();
//                        Prescriptiontemplatelist();
//                        location.reload();
//                    }
//                    else {
//                        console.log(data);
//                    }
//                }
//            });
//            toastr.success("Prescription Template Deleted Successfully")
//        }
//    }
//    else {
//        return false;
//    }
//});

//$('.btn_group').click(function () {

//    clear();
//    //if ($('.-grp').hasClass('btn_active')) {
//    //    alert('yes');
//    //}
//    //else {
//    //    alert('No');
//    //}
//    //if ($('#labtest_btn').hasClass('btn_active')) {
//    //    alert('1');
//    //}
//    //if ($('#diet_btn').hasClass('btn_active')) {
//    //    alert('2');
//    //}
//    //if ($('#prescription_btn').hasClass('btn_active')) {
//    //    alert('3');
//    //}

//});



////$(function () {
////    $('#myTab a:last').tab('show');
////});

////$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
////    debugger;
////    var target = $(e.target).attr("href");
////    if ((target == '#messages')) {
////        alert('ok');
////    } else {
////        alert('not ok');
////    }
////});



////$('tabBtnActive').on('click', 'a', function (e) {
////    console.log('this is the click');
////    alert("this is the click");
////    e.preventDefault();
////});


//// Prescription template end


//function clear() {
//    sessionStorage.clear();
//    $('#txtlabTemplateName').val('');
//    $('#report').val('');
//    $('#DiagnosticsTestTable_body').empty();

//    $('#txtdietname').val('');
//    $('#txtfood').val('');
//    $('#txtQuantity').val('');
//    $('#txtInstructions').val('');
//    $('#tblDietChart_body').empty();

//    $('#medicine_name').val('');
//    $('#days').val('');
//    $('#mor').val(0);
//    $('#aft').val(0);
//    $('#nit').val(0);
//    $('#dosage').val('');
//    $('#prescriptionNotes').val('');
//    $('#tbl-medicine_body').empty();
//    $('#labCopy_template').show();
//    $('#Copy_template').show();
//    $('#Prescription_template').show();
//    $('#txtPrescriptionName').val('');
//}


// complaints code started
var Norecord = '<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" style="height:65px; width:72px; border-radius:0px;"><br><div class="no_data_content">No data found.</div></div>';


$('#conplaintstab').click(function () {
    load_complaints();
});

function load_complaints() {
    $('.load-position').show();
    var labval = {
        doctor_id: $('#HiddenDoctorID').val(),
        indicator_id: 'SC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/complaints_ins_upd_del',
        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;
                $('.load-position').hide();
                $('#complaints_table').empty();
                if (jQuery.isEmptyObject((data1))) {
                    $('#complaints_table').html(Norecord);
                }
                else {
                    var status = '', j = 0;
                    var b = data1.Table;
                    if (b.length > 0) {
                        tr = $('<table class="table-responsive table table-bordered table-striped no-footer dataTable tablecolumnsticky" id="complaints_table_list" />');
                        tr.append("<thead><tr><th>S No</th><th>Complaints</th><th class='tbl-status'>Status</th><th class='tbl-action'>Actions</th></tr></thead><tbody>");
                        $.each(b, function (i, emp) {
                            j++;
                            var status = "";
                            var edit = "<a class='edit_icon' data-toggle='popover' title='Edit' data-id='TCC_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_complaints(this," + emp.complaints_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span>";
                            var del = "<a class='delete_icon' data-toggle='popover' title='Delete' data-id='TCC_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick=delete_complaints(this," + emp.complaints_id + ")><i class='fa fa-trash-o' aria-hidden='true'></i></span>";
                            var active = "<a class='active_icon' data-toggle='popover' title='Activate' data-id='TCC_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_complaints(this," + emp.complaints_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </a>"
                            if (emp.active == "1") {
                                status = "Active";
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li></div></ul></div>';
                                row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.complaints + "</td><td>" + status + "</td><td>" + other_info +"</td></tr>";
                            }
                            else {
                                status = "In Active";
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + active + '</li></div></ul></div>';
                                row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.complaints + "</td><td>" + status + "</td><td>" + other_info +"</td></tr>";
                            }
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#complaints_table').append(tr)).then($('#complaints_table_list').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                    }
                    else {
                        $('#complaints_table').html(Norecord);
                    }

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

$('#btncomplaints').click(function () {
    debugger;
    var did = $('#btncomplaints').attr("data-id");
    var navigation = $('#btncomplaints').attr("data-nav");
    var name = $('#btncomplaints').attr("data-name");
    var columntype = $('#btncomplaints').attr("data-type");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     if ($.trim($('#comp').val()).length == "") {
                         $('#Pcomp').show();
                         $('#Pcomp').fadeOut(8000);
                         $('#Pcomp').html('Please Enter Complaint');
                         $('#comp').focus();
                         $('#comp').val('');
                         return false;
                     }
                     if ($('#comp').val().length > 0) {
                         add_complaints();
                     }
                 }
             }
         }
     });
});

function add_complaints() {
    debugger;
    var ind_id;
    if ($('#btncomplaints').html() == "Update") ind_id = "UC";
    else ind_id = "IC";

    var labval = {
        doctor_id: $('#HiddenDoctorID').val(),
        indicator_id: ind_id,
        complaints: $('#comp').val(),
        complaints_id: $('#hdn_comp_id').val(),
        user_roleid: $('#hiddenRole_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/complaints_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var b;
                    console.log(data1);
                    b = data1.Table;
                    if (b[0].Column1 == 'already') {
                        toastr.warning('Complaints Name already exists');
                    }
                    else if (b[0].Column1 == 'name already') {
                        toastr.warning("Complaints Name already Exist, Status is In-active. Would you like to Activate the Template?");
                    }
                    else {
                        $('#comp').val('');
                        load_complaints();
                        if ($('#btncomplaints').html() == "Update") {
                            $('#btncomplaints').html('ADD');
                            toastr.success("Complaints Updated Successfully");
                        }
                        else {
                            $('#btncomplaints').html('ADD');
                            toastr.success("Complaints Created Successfully");
                        }
                    }
                }

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


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

                     return;
                 }
                 else {
                     var labval = {
                         doctor_id: $('#HiddenDoctorID').val(),
                         indicator_id: 'EC',
                         complaints_id: id
                     }
                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/Template/complaints_ins_upd_del',
                         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 b = data1.Table;
                                     $('#comp').val(b[0].complaints);
                                     $('#hdn_comp_id').val(b[0].complaints_id);
                                     $('#btncomplaints').html("Update");
                                 }
                             }
                             else {
                                 console.log(data1);
                             }
                         }
                     });
                 }
             }
         }
     });
}

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

                     return;
                 }
                 else {
                     if (confirm('Are you sure, Do you want to delete?')) {
                         var labval = {
                             doctor_id: $('#HiddenDoctorID').val(),
                             indicator_id: 'DC',
                             complaints_id: id
                         }
                         $.ajax({
                             async: true,
                             type: 'POST',
                             url: '/Template/complaints_ins_upd_del',
                             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;
                                     toastr.success("Complaint Deleted Successfully")
                                     load_complaints();
                                 }
                                 else {
                                     console.log(data);
                                 }
                             }
                         });
                     }
                     else {

                     }
                 }
             }
         }
     });
}

//complaints code ended

//diagnosis code started

$('#diagnosistab').click(function () {
    if ($('#hiddenRole_id').val() == 2) {
        LoadDoctor()
    }
    else {
        LoadDoctor($('#hiddenUser_id').val(),0)
    }

    load_diagnosis();
});

function load_diagnosis() {

    $('.load-position').show();
    var labval = {
        doctor_id: $('#HiddenDoctorID').val(),
        indicator_id: 'SD',
        diagnosis_id: $('#hiddenRole_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/diagnosis_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(labval),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;             
                console.log(data1);
                $('.load-position').hide();
                $('#diagnosis_table').empty();
                if (jQuery.isEmptyObject((data1))) {
                    $('#diagnosis_table').html(Norecord);
                }
                else {
                    var status = '', j = 0, edit = '', del = '', selpopup = '', other_info='';
                    var b = data1.Table;
                    //$('#Hddoctorid').val(b[0].doctorid)
                    if (b.length > 0) {
                        tr = $('<table class="table-responsive table table-bordered table-striped no-footer dataTable tablecolumnsticky" id="diagnosis_table_list" />');
                        if ($('#hiddenRole_id').val() == 2) {
                            tr.append("<thead><tr><th>S No</th><th>Diagnosis</th><th>Doctor Name</th><th class='tbl-status'>Status</th><th class='tbl-action'>Actions</th></tr></thead><tbody>");
                            $.each(b, function (i, emp) {
                                j++;
                                var status = "";
                                if (emp.active == "1") {
                                    selpopup = "<a class='edit_icon' title='Section Popup' data-toggle='modal'><i class='fa fa-pencil' aria-hidden='true' onclick=diag_click(this," + emp.diagnosis_id + "," + emp.doctorid + ",'" + emp.doctor_id + "')></i></a>";
                                    edit = "<a class='edit_icon'  title='Edit Diagnosis' data-id='TCG_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </a>";
                                    del = "<a class='delete_icon' title='Delete Diagnosis' data-id='TCG_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick=delete_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-trash-o' aria-hidden='true'></i></a>";
                                    other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li><li>' + selpopup + '</li></div></ul></div>';
                                    status = "Active";
                                    row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.diagnosis + "</td><td>" + emp.DoctorName + "</td><td>" + status + "</td><td>"+other_info+"</td></tr>";
                                }
                                else {
                                    status = "In Active";
                                    row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.diagnosis + "</td><td>" + emp.DoctorName + "</td><td>" + status + "</td><td><span class='btn btn-edit btn-xs mr-10' data-toggle='popover' title='Activate Diagnosis' data-id='TCG_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span></td></tr>";
                                }
                                tr.append(row_data);
                            });
                        }
                        else {
                            tr.append("<thead><tr><th>S No</th><th>Diagnosis</th><th class='tbl-status'>Status</th><th class='tbl-action'>Actions</th></tr></thead><tbody>");
                            $.each(b, function (i, emp) {
                                j++;
                                var status = "";
                                if (emp.active == "1") {

                                    status = "Active";
                                    row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.diagnosis + "</td><td>" + status + "</td><td><span class='btn btn-edit btn-xs mr-10' data-toggle='modal'><i class='fa fa-pencil' aria-hidden='true' onclick=diag_click(this," + emp.diagnosis_id + "," + emp.doctorid + ",'" + emp.doctor_id + "')></i></span>&nbsp;<span class='btn btn-edit btn-xs mr-10' data-toggle='popover' title='Edit Diagnosis' data-id='TCG_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span>&nbsp;<span class='btn btn-delete btn-xs' data-toggle='popover' title='Delete Diagnosis' data-id='TCG_D1' data-type='role_rights_delete' data-nav='sp_div' data-name='' onclick=delete_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-trash' aria-hidden='true'></i></span></td></tr>";
                                }
                                else {
                                    status = "In Active";
                                    row_data = "<tr><td>" + j + "</td><td class='tbl-name'>" + emp.diagnosis + "</td><td>" + status + "</td><td><span class='btn btn-edit btn-xs mr-10' data-toggle='popover' title='Activate Diagnosis' data-id='TCG_E1' data-type='role_rights_edit' data-nav='sp_div' data-name='' onclick=edit_Diagnosis(this," + emp.diagnosis_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span></td></tr>";
                                }
                                tr.append(row_data);
                            });
                        }

                        tr.append("</tbody>");
                        $.when($('#diagnosis_table').append(tr)).then($('#diagnosis_table_list').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                    }
                    else {
                        $('#diagnosis_table').html(Norecord);
                    }
                   // diagnosis()
                }
                //if ($('#hiddenRole_id').val() == 2) {
                //    LoadDoctor()
                //}
                //else {
                //    LoadDoctor($('#Hddoctorid').val())
                //}
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#btnadddiag').click(function () {
    debugger;
    var did = $('#btnadddiag').attr("data-id");
    var navigation = $('#btnadddiag').attr("data-nav");
    var name = $('#btnadddiag').attr("data-name");
    var columntype = $('#btnadddiag').attr("data-type");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     if ($.trim($('#diagnosis').val()).length == "") {
                         $('#Pdiagnosis').show();
                         $('#Pdiagnosis').fadeOut(8000);
                         $('#Pdiagnosis').html('Enter Diagnosis');
                         $('#diagnosis').focus();
                         $('#diagnosis').val('');
                         return false;
                     }
                     if ($.trim($('#Doctor_name').val()).length == "") {
                         $('#PDoctor_name').show();
                         $('#PDoctor_name').fadeOut(8000);
                         $('#PDoctor_name').html('Choose Doctor Name');
                         $('#Doctor_name').focus();
                         $('#Doctor_name').val('');
                         return false;
                     }
                     if ($('#diagnosis').val().length > 0) {
                         add_diagnosis();
                     }
                 }
             }
         }
     });
});

function add_diagnosis() {
    var ind_id;
    if ($('#btnadddiag').html() == "Update") ind_id = "UD";
    else ind_id = "TID";

    var labval = {
        doctor_id: $('#Doctor_name').val().toString(),
        indicator_id: ind_id,
        diagnosis: $('#diagnosis').val(),
        diagnosis_id: $('#hdn_diag_id').val(),
        diagnosis_temp_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/diagnosis_ins_upd_del',
        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 b;
                    b = data1.Table;
                    if (b[0].Column1 == "already") {
                        toastr.warning("Doctor Name already Exist");
                    }
                    else if (b[0].Column1 == "name already") {
                        toastr.warning("Diagnosis Name already Exist, Status is In-active. Would you like to Activate the Template?");
                    }
                    else {
                        $('#diagnosis').val('');
                        if ($('#hiddenRole_id').val() == 2) {
                            $('#Doctor_name').val('').change()
                        }
                        load_diagnosis();
                        if ($('#btnadddiag').html() == "Update") {
                            $('#btnadddiag').html('ADD');
                            toastr.success("Diagnosis Updated Successfully");
                            $('#Doctor_name').val('').change()
                        }
                        else {
                            $('#btnadddiag').html('ADD');
                            toastr.success("Diagnosis Created Successfully");
                            $('#Doctor_name').val('').change()
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


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

                     return;
                 }
                 else {
                     var labval = {
                         doctor_id: $('#HiddenDoctorID').val(),
                         indicator_id: 'ED',
                         diagnosis_id: id
                     }
                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/Template/diagnosis_ins_upd_del',
                         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 b = data1.Table;
                                     $('#diagnosis').val(b[0].diagnosis);
                                     $('#hdn_diag_id').val(b[0].diagnosis_id);
                                     LoadDoctor(b[0].doctorid,1)
                                     $('#btnadddiag').html("Update");
                                 }
                             }
                             else {
                                 console.log(data1);
                             }
                         }
                     });
                 }
             }
         }
     });
}


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

                     return;
                 }
                 else {
                     if (confirm('Are you sure, Do you want to delete?')) {
                         var labval = {
                             doctor_id: $('#HiddenDoctorID').val(),
                             indicator_id: 'DD',
                             diagnosis_id: id
                         }
                         $.ajax({
                             async: true,
                             type: 'POST',
                             url: '/Template/diagnosis_ins_upd_del',
                             contentType: 'application/json; charset=UTF-8',
                             data: JSON.stringify(labval),
                             success: function (data) {
                                 var data = JSON.parse(data);
                                 if (data.msg == "Success") {
                                     toastr.success("Diagnosis Deleted Successfully")
                                     load_diagnosis();
                                 }
                                 else {
                                     console.log(data);
                                 }
                             }
                         });
                     }
                     else {

                     }
                 }
             }
         }
     });
}

//diagnosis code ended



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


//load visit type
function loadvisit_type() {
    debugger;
    var data = {
        P_Dml_Indicator: 'STR'
    }
    $.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 data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {
                    $('#selPatientType').empty();
                    var option = "";
                    var data1 = data2.data;
                    //var default_option = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        option = option + '<option value="' + emp.template_id + '">' + emp.visit_type_name + '</option>';
                    })
                    $('#selPatientType').append(option);

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

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

        }
    });
}

//diagnosis template section Starts

function tabsection(secid,docid) {
    debugger;  

    var data = {
        indicator_id: 'DTS',
        doctor_id: docid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/diagnosis_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {
                    $('#diag_section').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        option = option + '<option value="' + emp.casesheet_section_desc_id + '">' + emp.label + '</option>';
                    })
                    $('#diag_section').append(default_opt + option);

                    if (secid != '' || secid != null) {
                        $('#diag_section').val(secid)
                    }

                }
            }
        }
    })
}

function diag_click(event, id, docid, doc_id) {
    debugger
    $('#Hddoctorid').val(doc_id)
    tabsection('', docid)
    $('#diag_section').val(0)
    $('#txtdescription').val('')
    $('#diag_submit').html('Save')
    $('#hdn_diag_id').val(id)
    $('#myModal').modal('show');
    Loaddescription(id)
}

$('#diag_submit').click(function () {
    debugger

    if ($.trim(($('#diag_section').val())) == "" || $.trim(($('#diag_section').val())) == 0) {
        $('#Pdiag_section').show();
        $('#Pdiag_section').fadeOut(8000);
        $('#Pdiag_section').html('Select Tab Section');
        $('#diag_section').focus();
        $('#diag_section').val(0);
        return false;
    }
    if ($.trim(($('#txtdescription').val())) == "") {
        $('#Ptxtdescription').show();
        $('#Ptxtdescription').fadeOut(8000);
        $('#Ptxtdescription').html('Enter Description');
        $('#txtdescription').focus();
        $('#txtdescription').val('');
        return false;
    }

    var indicator = ''
    if ($('#diag_submit').html() == 'Save') {
        indicator = 'DTSI'
    }
    else {
        indicator = 'DTSU'
    }
    var val = {   
        indicator_id: indicator,
        doctor_id: $('#Hddoctorid').val(),
        diagnosis_id: $('#hdn_diag_id').val(),
        diagnosis: $('#diag_section').val(),
        user_created_by: $('#hiddenUser_id').val(),
        description: $('#txtdescription').val().trim(),
        diagnosis_temp_id: $('#Hddiag_temp_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/diagnosis_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(val),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data1 = data.data.Table[0]
                var id = data1.Id
                if (data1.msg == 'Success') {
                    toastr.success('Inserted Successfully')
                }
                else if (data1.msg == 'Update') {
                    toastr.success('Updated Successfully')
                }
                Loaddescription(id)
                clearDiagTemp()
                $('#diag_submit').html('Save')
            }
            else {
                console.log(data);
            }
        }
    });
})

function clearDiagTemp(){
    $('#diag_section').val(0)
    $('#txtdescription').val('')
}

function Loaddescription(id) {
    debugger;
        values = {
            indicator_id: "DTSL",
            diagnosis_id: id
        }

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

                }
                else {
                    $('#tblsection_tbody').empty();
                    $('#tblsection').dataTable().fnClearTable();
                    $('#tblsection').dataTable().fnDraw();
                    $('#tblsection').dataTable().fnDestroy();

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

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++

                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="" data-nav="" data-name=""  href="javascript:void(0);" onclick=\'descedit(this,"' + emp.sectionid + '","' + j + '","' + emp.id + '","' + emp.doctorid + '")\'><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="TPAdel_' + emp.id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=descdel(this,"' + emp.id + '","DTSD")><i class="fa fa-trash" aria-hidden="true"></i></a>';
                        if (emp.status == '1') {
                            //active_inactive = '<span class="label label-success">Active</span>';
                            //active = '<a  data-toggle="tooltip" title="Make In Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","INACT")><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '</div></div>';
                        }
                        else if (emp.status == '2') {
                            //active_inactive = '<span class="label label-warning">Inactive</span>';
                            //active = '<a  data-toggle="tooltip" title="Make Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","ACT")><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + '</div></div>';
                        }
                        // tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.name + '</td><td>' + emp.branch_name + '</td><td>' + emp.mobile_number + '</td><td >' + emp.Address + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                        // one master concept
                        //tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.name + '</td><td>' + emp.branch_name + '</td><td>' + emp.mobile_number + '</td><td >' + emp.Address + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';
                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.label + '</td><td id="ddesc_' + j + '">' + emp.description + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#tblsection_tbody').html(tr);
                    //datatable('TPA_table_list', 'TPA LIST', 'Legal');
                    $('#tblsection').DataTable()
                }
            }
            else {
                console.log(data);
            }
        }       
    });
    $('#tblsection_tbody').empty();
}

function descedit(event, secid, desc, id,docid) {
    debugger
    tabsection(secid, docid),
    $('#txtdescription').val($('#ddesc_' +desc).html())
    $('#Hddiag_temp_id').val(id)
    $('#diag_submit').html('Update')
}

function descdel(event, Id, indicatorid) {
    debugger;

    var status = "";
    if (indicatorid == 'DTSD') {
        status = "Are you sure, Do you want to Delete?";
    }
    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>", status,
     {
         closeButton: true,
         progressBar: true,
         allowHtml: true,
         timeOut: 20000000,

         onShown: function (toast) {
             $("#confirmationRevertYes").click(function () {
                 var Delete = {
                     indicator_id: indicatorid,
                     diagnosis_id: Id
                 }

                 $.ajax({
                     async: true,
                     type: 'POST',
                     url: '/Template/diagnosis_ins_upd_del',
                     contentType: 'application/json; charset=UTF-8',
                     data: JSON.stringify(Delete),
                     success: function (data) {
                         debugger;
                         var data1 = JSON.parse(data);
                         if (data1.msg == "Success") {
                             if (data1.data.Table[0].msg == 'Deleted') {
                                 var diag_id = data1.data.Table[0].diag_id
                                 toastr.success("Deleted Successfully");
                                 Loaddescription(diag_id)
                                 clearDiagTemp()
                             }
                             else {
                                 toastr.warning("Somthing Went Wrong");
                                 return false;
                             }
                         }
                         else {
                             toastr.warning("Somthing Went Wrong");
                             return false;
                         }
                     }
                 });
             });
         }
     })
};

function LoadDoctor(user,flag) {
    debugger;
    var department = {
        Dml_Indicator: "DTDN",
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(department),
        success: function (data) {
            debugger
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                //var data1 = data1.data;
                var tableData = data1.data.Table;
                console.log(tableData)
                if (jQuery.isEmptyObject((tableData))) {
                }
                else {
                    var Department;
                    $('#Doctor_name').empty();

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(tableData, function (i, emp) {
                        Department = Department + '<option value="' + emp.doctorid + '" data-id=' + emp.doctor_user_id + '>' + emp.Doctor + '</option>';
                    });
                    if (tableData.length == 1) {
                        $('#Doctor_name').append(Department);
                      //  $("#Doctor_name").change();

                    }
                    else {
                        $('#Doctor_name').append(default_opt + Department);

                    }

                    if (user != '' && user != null) {
                        if (flag == 0) {
                            $.each(tableData, function (i, emp) {
                                if (emp.doctor_user_id == user) {
                                    var docId = emp.doctorid;
                                    if ($('#hiddenRole_id').val() == 2) {
                                        $('#Doctor_name').val(docId);
                                    } else {
                                        $('#Doctor_name').val(docId);
                                        $('#Doctor_name').prop('disabled', true);
                                    }
                                    return false; // exit each loop
                                }
                            });
                        }
                        else {
                            if ($('#hiddenRole_id').val() == 2) {
                                $('#Doctor_name').val(user);
                            } else {
                                $('#Doctor_name').val(user);
                                $('#Doctor_name').prop('disabled', true);
                            }
                        }
                    }

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

//diagnosis template section Ends