$(document).ready(function () {
    $('#loaderimg').show();
    loadlab_id();

});



function loadlab_id() {
    var role_ID = $('#hiddenRole_id').val(), doc_ID = "", Dml_Indicator = "";
    if (role_ID == "1" || role_ID == "5") {
        doc_ID = $('#HiddenDoctorID').val();
        Dml_Indicator = "DI";
    }
    else {
        doc_ID = $('#HiddenDoctorID').val();
        Dml_Indicator = "DIA";
    }

    var country = {
        Dml_Indicator: Dml_Indicator,
        doctor_id: doc_ID
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);

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

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

                    var Country;
                    $.each(data1, function (i, emp) {
                        $('#lab_id').val(emp.lab_id);
                    });
                }
                else {
                    console.log(data);
                }
            }
            count();
        }
    });
}

function count() {
    var country = {
        Dml_Indicator: "count",
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    console.log(data1);
                    if (data1.length > 0) {
                        $('#testcount').html(data1[0].testcount);
                        $('#panelcount').html(data1[0].panelcount);
                        $('#testcount_app').html(data1[0].testcount_app);
                        $('#panelcount_app').html(data1[0].panelcount_app);
                    }
                }
                else {
                    console.log(data);
                }
            }
            loadgroup();
            labtesttable();
            labpaneltable();
        }
    });
}

// Add lab test  start

function labtesttable() {
    var country = {
        Dml_Indicator: "TL",
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    $('#test_table').empty();
                    tr = '';
                    for (var i = 0; i < data.length; i++) {
                        var testapp_flag = 'Not Allowed'
                        if (data[i].test_app_flag == 1) {
                            testapp_flag = 'Allowed';
                        }
                        tr = tr + '<tr><td>' + data[i].test_id + '</td><td>' + data[i].test_name + '</td><td>' + data[i].test_cost + '</td><td>' + testapp_flag + '</td><td>' + data[i].noofparameters + '</td><td><a class="btn addicon-btn btn-xs mr-20" href="javascript:void(0);" onclick=testedit("' + data[i].test_id + '")><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a><a class="btn deleteicon-btn btn-xs" href="javascript:void(0);" onclick=testdel("' + data[i].test_id + '")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';
                    }
                    $('#test_table').html(tr);
                }
                else {
                    console.log(data);
                }
            }
            loadsampletype();
        }
    });
}
$('#btnLabWalkIn').click(function () {
    $('#tName,#Name,#rValue,#unit,#sType').attr("disabled", false);
    $('#Add_Test_record').show();
    $('#btnTestsave').html('Save');
    $('#testAddTable_body').empty();
});

function testedit(val) {
    debugger;
    $('#btnLabWalkIn').click();
    $('#edit_lab_test').val(val);
    $('#btnTestsave').html('Update');
    var country = {
        Dml_Indicator: "EL",
        test_id: val
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    debugger;
                    //var data = JSON.parse(data);
                    var data = data2.data;
                    $('#AddTestTable > tbody').empty();
                    tr = '';
                    if (data.length > 0) {
                        var data = data2.data;
                        $('#testTableRowCount').val()
                        for (var i = 0; i < data.length; i++) {
                            $('#tName').val(data[i].test_name);
                            $('#tCost').val(data[i].test_cost);
                            $('#gID').val(data[i].lab_type_id);
                            $('#lab_instructions').val(data[i].lab_instructions);
                            if (data[i].test_app_flag == "1") $('#labtest_flag').prop("checked", data[i].test_app_flag);
                            var sess_key;
                            var rowcount = $.trim($('#testTableRowCount').val());
                            var tot_row = (Number(rowcount) + 1);
                            var ikey = '';
                            var ParName, RefValue, Unit, SampleType;
                            if (data[i].parameter_name == "" || data[i].parameter_name == null) ParName = '';
                            else ParName = data[i].parameter_name;
                            if (data[i].reference_value == "" || data[i].reference_value == null) RefValue = '';
                            else RefValue = data[i].reference_value;
                            if (data[i].unit == "" || data[i].unit == null) Unit = '';
                            else Unit = data[i].unit;
                            if (data[i].sample_type == "" || data[i].sample_type == null) SampleType = '';
                            else SampleType = data[i].sample_type;
                            var Instructions = data[i].parameter_instructions;
                            if (Instructions == '' || Instructions == null) {
                                Instructions = '';
                            }
                            var SampleTypeval = data[i].sample_type;
                            var sess_data = ParName + "!" + RefValue + "!" + Unit + "!" + SampleType + "!" + Instructions + "!" + SampleTypeval;

                            console.log('sess_data------>' + sess_data);

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

                                ikey = 'row' + tot_row;
                            }

                            sessionStorage.setItem(ikey, sess_data);

                            //  var value = "<tr id='t_" + ikey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger  btn-sm btn-add' onclick='labdelete_pan(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                            if (ParName == "") {
                                var value = "";
                            }
                            else {
                                var value = "<tr id='t_" + ikey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td>-</td></tr>";
                            }
                            $('#AddTestTable > tbody:last').append(value);
                            $('#testTableRowCount').val(tot_row);

                            $('#Name').val('');
                            $('#rValue').val('');
                            $('#unit').val('');
                            $('#sType').val('');
                            $('#testNotes').val('');
                            $('#tName,#Name,#rValue,#unit,#sType').attr("disabled", true);
                            $('#Add_Test_record').hide();
                            $(".select2-selection__rendered").empty();
                            $("#sType").select2("val", " ");
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });

}
function testdel(val) {
    var country = {
        Dml_Indicator: "D",
        test_id: val
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    toastr.success("Test Deleted Successfully");
                    count();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    loadtestname();
}

function loadgroup() {
    var country = {
        Dml_Indicator: "GS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            $('#gID').empty();
            var data2 = JSON.parse(data);

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

            }
            else {

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

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

                        Country = Country + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';

                    });
                    $('#gID').append(default_opt + Country);
                }
                else {
                    console.log(data);
                }
            }
            loadsampletype();
        }
    });
}


function loadsampletype() {
    var country = {
        Dml_Indicator: "STS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            $('#sType').empty();

            var data2 = JSON.parse(data);

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

            }
            else {

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

                    var Country;
                    $.each(data1, function (i, emp) {

                        Country = Country + '<option value="' + emp.sample_id + '">' + emp.sample_name + '</option>';

                    });
                    $('#sType').append(Country);
                }
                else {
                    console.log(data);
                }
            }
            loadtestname();
        }
    });
}




$('#Add_Test_record').click(function () {
    debugger;
    var ParName = $("#Name").val();
    var RefValue = $("#rValue").val();
    var Unit = $("#unit").val();
    var SampleType = $("#sType").val();
    debugger;
    //var SampleTypeval = $("#sType option:selected").text().split(/[ ,]+/).join(',');
    var SampleTypeval = [];
    let test = $(".select2-selection__rendered").children();
    for (var i = 0; i < test.length; i++) {
        if (test.eq(i).attr('class') == "select2-selection__choice") {
            SampleTypeval.push(test.eq(i).attr('title'));
        }
    }
    var Instructions = $("#testNotes").val();
    if ($.trim((ParName)) == "") {
        $('#PName').show();
        $('#PName').fadeOut(8000);
        $('#PName').html('Enter Parameter Name');
        $('#Name').focus();
        return false;
    }
    if ($.trim((RefValue)) == "") {
        $('#PrValue').show();
        $('#PrValue').fadeOut(8000);
        $('#PrValue').html('Enter Reference Value');
        $('#rValue').focus();
        return false;
    }
    if ($.trim((Unit)) == "") {
        $('#Punit').show();
        $('#Punit').fadeOut(8000);
        $('#Punit').html('Enter unit');
        $('#unit').focus();
        return false;
    }
    if ($.trim((SampleType)) == "") {
        $('#PsType').show();
        $('#PsType').fadeOut(8000);
        $('#PsType').html('Enter Sample Type');
        $('#sType').focus();
        return false;
    }

    var sess_key;
    var rowcount = $.trim($('#testTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var ikey = '';
    var sess_data = ParName + "!" + RefValue + "!" + Unit + "!" + SampleType + "!" + Instructions + "!" + SampleTypeval;

    console.log('sess_data------>' + sess_data);

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

        ikey = 'row' + tot_row;
    }

    sessionStorage.setItem(ikey, sess_data);

    var value = "<tr id='t_" + ikey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete_pan(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#AddTestTable > tbody:last').append(value);
    $('#testTableRowCount').val(tot_row);

    $('#Name').val('');
    $('#rValue').val('');
    $('#unit').val('');
    $('#sType').val('');
    $('#testNotes').val('');
    $(".select2-selection__rendered").empty();
    $("#sType").select2("val", " ");
});

function labedit(val) {
    debugger;
    $('#Add_Test_record').hide();
    $('#Update_Test_record').show();
    $('#hdn_test_id').val(val);
    var gkey = val;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split('!');
    $('#Name').val(row_data_split[0]);
    //if (emp1.home_collection_offered == "1") $('#Chkhmecollected').prop("checked", emp1.home_collection_offered);
    $('#rValue').val(row_data_split[1]);
    $('#unit').val(row_data_split[2]);
    //$('#sType').val(row_data_split[3]);

    var abc = '';
    //alert(row_data_split[3]);
    var val1 = row_data_split[3].split(',');
    // alert(val1);
    let abcdata = row_data_split[5].split(',');

    for (var i = 0; i < val1.length; i++) {
        abc = abc + '<li class="select2-selection__choice" title="' + abcdata[i] + '"><span class="select2-selection__choice__remove" role="presentation">×</span>' + abcdata[i] + '</li>';
        document.getElementById("sType").value = val1[i];
        $('option [value=' + val1[i] + ']').attr("selected", "select");
    }

    $('ul.select2-selection__rendered').append(abc);

    $('#testNotes').val(row_data_split[4]);
}

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

$('#Update_Test_record').click(function () {
    var table_id = $('#hdn_test_id').val();

    var ParName = $("#Name").val();
    var RefValue = $("#rValue").val();
    var Unit = $("#unit").val();
    var SampleType = $("#sType").val();
    var Instructions = $("#testNotes").val();

    if ($.trim((ParName)) == "") {
        $('#PName').show();
        $('#PName').fadeOut(8000);
        $('#PName').html('Enter Parameter Name');
        $('#Name').focus();
        return false;
    }
    if ($.trim((RefValue)) == "") {
        $('#PrValue').show();
        $('#PrValue').fadeOut(8000);
        $('#PrValue').html('Enter Reference Value');
        $('#rValue').focus();
        return false;
    }
    if ($.trim((Unit)) == "") {
        $('#Punit').show();
        $('#Punit').fadeOut(8000);
        $('#Punit').html('Enter unit');
        $('#unit').focus();
        return false;
    }
    if ($.trim((SampleType)) == "") {
        $('#PsType').show();
        $('#PsType').fadeOut(8000);
        $('#PsType').html('Enter Sample Type');
        $('#sType').focus();
        return false;
    }
    var SampleTypeval = $("#sType option:selected").text();
    $('#Add_Test_record').show();
    $('#Update_Test_record').hide();



    var sess_data = ParName + "!" + RefValue + "!" + Unit + "!" + SampleType + "!" + Instructions + "!" + SampleTypeval;
    var ikey = table_id;
    sessionStorage.setItem(ikey, sess_data);

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




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


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

        if (row_data == null) {
            console.log(gkey + '--------->' + row_data);
            continue;
        }
        if (row_data != null) {
            row_data = row_data.split('!');
            var testval = '';
            ParName = row_data[0];
            RefValue = row_data[1];
            Unit = row_data[2];
            SampleType = row_data[3];
            Instructions = row_data[4];
            SampleTypeval = row_data[5]

            var value = "<tr id='t_" + gkey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

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


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

    $('#Name').val('');
    $('#rValue').val('');
    $('#unit').val('');
    $('#sType').val('');
    $('#testNotes').val('');
    $("#sType").select2("val", " ");
});


$('#tName').change(function () {
    var country = {
        Dml_Indicator: "CHTN",
        test_name: $('#tName').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data1[0].msg == "already") {
                        toastr.warning("Lab Test Name already exists");
                        $('#tName').val('');
                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
});



$('#btnTestsave').click(function () {
    var testname = $('#tName').val();
    var testcost = $('#tCost').val();
    var testgroup = $('#gID').val();

    if ($.trim((testname)) == "") {
        $('#PtName').show();
        $('#PtName').fadeOut(8000);
        $('#PtName').html('Enter test Name');
        $('#tName').focus();
        return false;
    }
    if ($.trim((testcost)) == "") {
        $('#PtCost').show();
        $('#PtCost').fadeOut(8000);
        $('#PtCost').html('Enter test cost');
        $('#tCost').focus();
        return false;
    }
    if ($.trim((testgroup)) == 0) {
        $('#PgID').show();
        $('#PgID').fadeOut(8000);
        $('#PgID').html('select group');
        $('#gID').focus();
        return false;
    }
    insert_lab_test();
    $('#tName').attr("disabled", false);
});

//function delete_lab_test()
//{
//    $('#edit_lab_test').val();

//    alert('Something went worng please try after some time !!!');
//}

$('#btnTestdelete').click(function () {
    testdel($('#edit_lab_test').val());
    $('#btncloseX').click();
});

function insert_lab_test() {
    if ($('#btnTestsave').html() == 'Update') {
        test_id = $('#edit_lab_test').val();
        lab_test_update(test_id);
    }
    else {
        var test_app_flag = 0, r;
        var tot_rowMc = $.trim($('#testTableRowCount').val());
        if (tot_rowMc == 0) {
            r = confirm("Do you want to Save without parameter?");
            if (r == true) {
                $('#loaderimg').show();
                if ($('#labtest_flag').prop("checked") == true) {
                    test_app_flag = 1;
                }
                var Dml_Indicator = 'I', test_id = '';
                var country = {
                    lab_id: $('#lab_id').val(),
                    test_name: $('#tName').val(),
                    test_cost: $('#tCost').val(),
                    lab_type_id: $('#gID').val(),
                    lab_instructions: $('#lab_instructions').val(),
                    Dml_Indicator: Dml_Indicator,
                    test_app_flag: test_app_flag,
                    test_id: test_id
                }
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/Template/labtest',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(country),
                    success: function (data) {
                        $('#sType').empty();

                        var data2 = JSON.parse(data);
                        if (jQuery.isEmptyObject((data2.data))) {
                        }
                        else {

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


                                var testId = '';
                                $.each(data1, function (i, emp) {
                                    testId = emp.Vtest_Id;
                                });
                                if (tot_rowMc == 0) {
                                    $('#loaderimg').hide();
                                    $('#tName').val('');
                                    $('#tCost').val('');
                                    $('#gID').val(0);
                                    $('#lab_instructions').val('');
                                    toastr.success("Test Added Successfully");
                                    $('#btncloseX').click();
                                }
                                else {
                                    var tot_rowM = $.trim($('#testTableRowCount').val());
                                    if (tot_rowM > 0) {
                                        var L = 0;
                                        for (j = 1; j <= tot_rowM; j++) {
                                            var a = $('#testAddTable_body').children('tr').eq(L);
                                            var b = a.prop('id');
                                            L++;
                                            var C = b.split('_');
                                            var gkey = C[1];
                                            var row_data = sessionStorage.getItem(gkey);
                                            var K = 0;
                                            if (row_data == "") {
                                                console.log(gkey + '--------->' + row_data);
                                            }
                                            if (row_data != "" && row_data != null) {
                                                console.log(gkey + '-------' + row_data);
                                                row_data = row_data.split('!');
                                                var sms = {
                                                    test_id: testId,
                                                    parameter_name: row_data[0],
                                                    reference_value: row_data[1],
                                                    unit: row_data[2],
                                                    parameter_instructions: row_data[4],
                                                    Dml_Indicator: 'IP',
                                                    sample_type: row_data[5]
                                                }
                                                $.ajax({
                                                    async: true,
                                                    type: 'POST',
                                                    url: '/Template/labtest',
                                                    contentType: 'application/json; charset=UTF-8',
                                                    data: JSON.stringify(sms),
                                                    success: function (datas) {
                                                        if (jQuery.isEmptyObject((datas))) {
                                                        }
                                                        else { }
                                                    }
                                                });
                                            }
                                        }
                                        //clear
                                        $('#tName').val('');
                                        $('#tCost').val('');
                                        $('#gID').val(0);
                                        $('#lab_instructions').val('');
                                        $('#testAddTable_body').empty();
                                        toastr.success("Test Added Successfully");
                                        loadtestname();
                                        count();
                                        $('#btncloseX').click();
                                    }
                                }
                            }
                            else {
                                console.log(data);
                            }

                        }
                    }
                });
            }
            else {
            }
        }
        else {
            $('#loaderimg').show();
            if ($('#labtest_flag').prop("checked") == true) {
                test_app_flag = 1;
            }
            var Dml_Indicator = 'I', test_id = '';
            var country = {
                lab_id: $('#lab_id').val(),
                //lab_id:'L2',
                test_name: $('#tName').val(),
                test_cost: $('#tCost').val(),
                lab_type_id: $('#gID').val(),
                lab_instructions: $('#lab_instructions').val(),
                Dml_Indicator: Dml_Indicator,
                test_app_flag: test_app_flag,
                test_id: test_id
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Template/labtest',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(country),
                success: function (data) {
                    $('#sType').empty();
                    var data2 = JSON.parse(data);
                    if (jQuery.isEmptyObject((data2.data))) {
                    }
                    else {

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

                            var testId = '';
                            $.each(data1, function (i, emp) {
                                testId = emp.Vtest_Id;
                            });
                            var tot_rowM = $.trim($('#testTableRowCount').val());
                            if (tot_rowM > 0) {
                                var L = 0;
                                for (j = 1; j <= tot_rowM; j++) {
                                    var a = $('#testAddTable_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 = {
                                            test_id: testId,
                                            parameter_name: row_data[0],
                                            reference_value: row_data[1],
                                            unit: row_data[2],
                                            parameter_instructions: row_data[4],
                                            Dml_Indicator: 'IP',
                                            sample_type: row_data[5]
                                        }
                                        $.ajax({
                                            async: true,
                                            type: 'POST',
                                            url: '/Template/labtest',
                                            contentType: 'application/json; charset=UTF-8',
                                            data: JSON.stringify(sms),
                                            success: function (datas) {
                                                if (jQuery.isEmptyObject((datas))) {
                                                }
                                                else { }
                                            }
                                        });
                                    }
                                }
                            }
                            $('#tName').val('');
                            $('#tCost').val('');
                            $('#gID').val(0);
                            $('#lab_instructions').val('');
                            $('#testAddTable_body').empty();
                            toastr.success("Test Added Successfully");
                            loadtestname();
                            count();
                            $('#loaderimg').hide();
                            $('#btncloseX').click();
                        }
                        else {
                            console.log(data);
                        }

                    }

                }
            });
        }
    }
    labtesttable();
}
// Add lab test  end


//update lab test started

function lab_test_update(id) {
    $('#loaderimg').show();
    var test_app_flag;
    if ($('#labtest_flag').prop("checked") == true) {
        test_app_flag = 1;
    }
    var country = {
        lab_id: $('#lab_id').val(),
        test_name: $('#tName').val(),
        test_cost: $('#tCost').val(),
        lab_type_id: $('#gID').val(),
        lab_instructions: $('#lab_instructions').val(),
        Dml_Indicator: 'U',
        test_app_flag: test_app_flag,
        test_id: id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    toastr.success("Test Updated Successfully");
                }
                else {
                    console.log(data);
                }
            }
            labtesttable();
            $('#loaderimg').hide();
            $('#sType').empty();
            $('#btncloseX').click();
        }
    });
}


//update lab test ended

//Add panel start

function labpaneltable() {
    $('#loaderimg').show();
    var country = {
        Dml_Indicator: "PL",
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {

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

                    console.log(data);
                    $('#panel_table').empty();
                    tr = '';
                    for (var i = 0; i < data.length; i++) {
                        var panel_app_flag = 'Not Allowed'
                        if (data[i].panel_app_flag == 1) {
                            panel_app_flag = 'Allowed';
                        }
                        tr = tr + '<tr><td>' + data[i].panel_id + '</td><td>' + data[i].panel_name + '</td><td>' + data[i].panel_cost + '</td><td>' + panel_app_flag + '</td><td>' + data[i].noofpanel + '</td><td><a class="btn addicon-btn btn-xs mr-10" data-toggle="modal" data-target="#Addnewpanelbody" href="javascript:void(0);" onclick=paneledit("' + data[i].panel_id + '")><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <a class="btn deleteicon-btn btn-xs" href="javascript:void(0);" onclick=paneldel("' + data[i].panel_id + '")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';
                    }
                    $('#panel_table').html(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    $('#loaderimg').hide();
}

$('#Addnewpanel_1').click(function () {
    $('#Add_panel_record').show();
    $('#btnPanelsave').html('Save');
    //$('#panelAddTable_body').empty();
    $('#Pantestname,#PanName').attr("disabled", false);
    //$('#PanName').val('');
    //$('#PanCost').val('');
    //$('#PanInstructions').val('');
});

function paneledit(val) {
    $('#edit_lab_panel').val(val);
    $('#btnPanelsave').html('Update');
    var country = {
        Dml_Indicator: "EL",
        panel_id: val
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    tr = '';
                    for (var i = 0; i < data.length; i++) {
                        var sess_key;
                        var rowcount = $.trim($('#panelTableRowCount').val());
                        var tot_row = (Number(rowcount) + 1);
                        var ikey = '';
                        $('#PanName').val(data[i].panel_name);
                        $('#PanCost').val(data[i].panel_cost);
                        $('#PanInstructions').val(data[i].panel_instructions);
                        if (data[i].panel_app_flag == "1") $('#labpanel_flag').prop("checked", data[i].panel_app_flag);

                        var TestId = data[i].test_id;
                        var TestName = data[i].test_name;
                        var sess_data = TestId + "," + TestName;

                        if (rowcount >= 1) {
                            var getEid = $('#AddPanelTable  tr').last();
                            var actId = getEid.prop('id');
                            var afterSplit = actId.split('row');
                            afterInc = parseInt(afterSplit[1]) + 1;
                            console.log(afterInc);
                            ikey = 'row' + afterInc;
                        }
                        else {
                            ikey = 'row' + tot_row;
                        }
                        sessionStorage.setItem(ikey, sess_data);
                        var value = "<tr id='t_" + ikey + "'><td>" + TestName + "</td><td>-</td></tr>";
                        $('#Add_panel_record').hide();
                        $('#AddPanelTable > tbody:last').append(value);
                        $('#panelTableRowCount').val(tot_row);
                        $('#PanName,#Pantestname').attr("disabled", true);
                        $('#Pantestname').val(0);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    })
}

$('#btnPaneldelete').click(function () {
    paneldel($('#edit_lab_panel').val());
});

function paneldel(val) {
    $('#loaderimg').show();
    var country = {
        Dml_Indicator: "D",
        panel_id: val
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    toastr.success("Panel Deleted Successfully");
                    $('.close').click();
                    count();
                    labpaneltable();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    $('#loaderimg').hide();
}

function loadtestname() {
    var country = {
        Dml_Indicator: "TS",
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            $('#Pantestname').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var Country;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Country = Country + '<option value="' + emp.test_id + '">' + emp.test_name + '</option>';
                    });
                    $('#Pantestname').append(default_opt + Country);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#Add_panel_record').click(function () {
    debugger;
    var TestId = $('#Pantestname').val();
    var TestName = $('#Pantestname option:selected').text();
    if ($.trim((TestId)) == 0) {
        $('#PPantestname').show();
        $('#PPantestname').fadeOut(8000);
        $('#PPantestname').html('Select the test name');
        $('#PPantestname').focus();
        $('#Pantestname').val(0);
        return false;
    }
    var sess_key;
    var rowcount = $.trim($('#panelTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var ikey = '';
    var sess_data = TestId + "," + TestName;
    if (rowcount >= 1) {
        var getEid = $('#panelAddTable_body  tr').last();
        var actId = getEid[0].id;
        var afterSplit = actId.split('row');
        afterInc = parseInt(afterSplit[1]) + 1;
        console.log(afterInc);
        ikey = 'row' + afterInc;
    }
    else {
        ikey = 'row' + tot_row;
    }
    sessionStorage.setItem(ikey, sess_data);
    var value = "<tr id='t_" + ikey + "'><td>" + TestName + "</td><td></button><button class='btn deleteicon-btn btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    $('#AddPanelTable > tbody:last').append(value);
    $('#panelTableRowCount').val(tot_row);
    $('#Pantestname').val(0);
});


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


$('#PanName').change(function () {
    var country = {
        panel_name: $('#PanName').val(),
        Dml_Indicator: "CHPN",
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data1[0].msg == "already") {
                        toastr.warning("Lab Panel Name already exists");
                        $('#PanName').val('');
                    }
                    else {
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
});


$('#btnPanelsave').click(function () {
    var PanName = $('#PanName').val();
    var PanCost = $('#PanCost').val();
    var tot_rowcnt = $('#panelTableRowCount').val();
    if ($.trim((PanName)) == "") {
        $('#PPanName').show();
        $('#PPanName').fadeOut(8000);
        $('#PPanName').html('Enter panel name');
        $('#PanName').focus();
        return false;
    }
    if ($.trim((PanCost)) == "") {
        $('#PPanCost').show();
        $('#PPanCost').fadeOut(8000);
        $('#PPanCost').html('Enter test cost');
        $('#PanCost').focus();
        return false;
    }
    if (parseInt(tot_rowcnt) == "0" || tot_rowcnt == "") {
        $('#PPantestname').show();
        $('#PPantestname').fadeOut(8000);
        $('#PPantestname').html('Select lab test');
        $('#Pantestname').focus();
        return false;
    }
    if ($('#btnPanelsave').html() == 'Update') {
        update_lab_panel();
    }
    else {
        insert_lab_panel();
    }
    $('#PanName').attr("disabled", false);

});


function update_lab_panel() {
    var panel_app_flag, panel_id, Dml_Indicator;
    panel_id = $('#edit_lab_panel').val();
    Dml_Indicator = 'U';
    if ($('#labpanel_flag').prop("checked") == true) {
        panel_app_flag = 1;
    }
    var country = {
        lab_id: $('#lab_id').val(),
        panel_name: $('#PanName').val(),
        panel_cost: $('#PanCost').val(),
        panel_instructions: $('#PanInstructions').val(),
        Dml_Indicator: Dml_Indicator,
        panel_app_flag: panel_app_flag,
        panel_id: panel_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    toastr.success("Panel Added Successfully");
                    count();
                    $('#loaderimg').hide();
                    $('.close').click();
                    labpaneltable();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function insert_lab_panel() {
    $('#loaderimg').show();
    panel_app_flag = 0;
    if ($('#labpanel_flag').prop("checked") == true) {
        panel_app_flag = 1;
    }
    var Dml_Indicator = 'I';
    var panel_id = '';

    var country = {
        lab_id: $('#lab_id').val(),
        panel_name: $('#PanName').val(),
        panel_cost: $('#PanCost').val(),
        panel_instructions: $('#PanInstructions').val(),
        Dml_Indicator: Dml_Indicator,
        panel_app_flag: panel_app_flag,
        panel_id: panel_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labpanel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var panel_id = '';
                    $.each(data1, function (i, emp) {
                        panel_id = emp.Vpanel_id;
                    });
                    var tot_rowM = $.trim($('#panelTableRowCount').val());
                    if (tot_rowM > 0) {
                        var L = 0;
                        for (j = 1; j <= tot_rowM; j++) {
                            var a = $('#panelAddTable_body').children('tr').eq(L);
                            var b = a.prop('id');
                            L = L + 1;
                            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 = {
                                    panel_id: panel_id,
                                    test_id: row_data[0],
                                    Dml_Indicator: 'ID'
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/Template/labpanel',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(sms),
                                    success: function (datas) {
                                        if (jQuery.isEmptyObject((datas))) {

                                        }
                                        else {
                                        }
                                    }
                                });
                            }
                        }
                        //clear
                        $('#PanName').val('');
                        $('#PanCost').val('');
                        $('#PanInstructions').val('');
                        $('#panelAddTable_body').empty();
                        toastr.success("Panel Added Successfully");
                        count();
                        $('#loaderimg').hide();
                        $('.close').click();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

//Add panel end

//clear exsiting values
$('.close').click(function () {
    $("#sType").select2("val", " ");
    $('#panelAddTable_body').empty();
});