// Lab Setup JS //
var branch_id = [];
//var dttableremove = $('#maplabusertable').DataTable();
$(document).ready(function () {

    loadlabdata();
    debugger;
    loadcountry();
    HospitalDetails();
    //Load_Commom_Branch()
    var dttableremove = $('#maplabusertable').DataTable();
});

//filter
$('#btnfilter').click(function () {
    debugger;
    loadlabdata('filter')
})

$('#btnclear').click(function () {
    debugger;
    $('#ldblabtype').val('2')
    $('#ldblabstatus').val('3');
    loadlabdata()
})

//load html table Labsetup data 
function loadlabdata(filter_value) {
    debugger;
    $('#shade_slot').show();
    var servicevalues = '';
    if ($('#hiddenRole_id').val() == 2) {
        if (filter_value == 'filter') {
            servicevalues = {
                Dml_Indicator: "SFilter",
                is_externallab: $('#ldblabtype').val(),
                status: $('#ldblabstatus').val()
            }
        }
        else {
            servicevalues = {
                Dml_Indicator: "L"
            }
        }
    }
    else {
        if (filter_value == 'filter') {
            servicevalues = {
                Dml_Indicator: "SFilter",
                is_externallab: $('#ldblabtype').val(),
                status: $('#ldblabstatus').val(),
                branch_id: $('#HospitalBranchID').val()
            }
        }
        else {
            servicevalues = {
                Dml_Indicator: "L",
                branch_id: $('#HospitalBranchID').val()
            }
        }
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var data2 = data1.Table;
                    var status = '', j = 0;
                    var b = data1.Table;

                    $('#labsetuptable_body').empty();
                    $('#lab_table_list').dataTable().fnClearTable();
                    $('#lab_table_list').dataTable().fnDestroy();
                    tr = '';
                    var edit = '', del = '', branches = '', add_pin = '', add_users = '', add_services = '', active_inactive = '', act_inact_status = '', other_info = '', tr = '';
                    $.each(b, function (i, emp) {

                        j++;
                        //edit = '<a class="btn btn-edit btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit" data-id="LS_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labedit(this,"' + emp.labtranid + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        edit = '<a class="edit_icon" title="Edit" data-id="LS_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labedit(this,"' + emp.labtranid + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 6) {

                            //del = ' <a id="labdel_' + emp.labtranid + '" class="btn deleteicon-btn btn-xs" data-toggle="tooltip" data-placement="bottom" title="Delete" href="javascript:void(0);"   data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form"  onclick=labdel(this,"' + emp.labtranid + '","D")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                            del = ' <a id="labdel_' + emp.labtranid + '" class="delete_icon"  data-placement="bottom" title="Delete" href="javascript:void(0);"   data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form"  onclick=labdel(this,"' + emp.labtranid + '","D")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        }
                        else {
                            //del = ' <a id="labdel_' + emp.labtranid + '" class="btn deleteicon-btn btn-xs" data-toggle="tooltip" data-placement="bottom" title="Delete" href="javascript:void(0);"   data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form"  onclick=labdel(this,"' + emp.labtranid + '","UBD")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                            del = ' <a id="labdel_' + emp.labtranid + '" class="delete_icon"  data-placement="bottom" title="Delete" href="javascript:void(0);"   data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form"  onclick=labdel(this,"' + emp.labtranid + '","UBD")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        }

                        if (emp.branch_count == 0 || emp.status == 2) {
                            branches = '<button data-toggle="tooltip" data-placement="bottom" title="View branches" id="btnbranchdetails_' + i + '" onclick=branchdetails(this,"' + emp.labtranid + '");  class="btn addicon-btn btn-xs mr-10 hidden"><span class="fa fa-angle-double-down"></span></button>';
                        }
                        else {
                            branches = '<button data-toggle="tooltip" data-placement="bottom" title="View branches" id="btnbranchdetails_' + i + '" onclick=branchdetails(this,"' + emp.labtranid + '");  class="btn addicon-btn btn-xs mr-10"><span class="fa fa-angle-double-down"></span></button>';
                        }

                        if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 6) {
                            if (emp.status == "2") {
                                //active_inactive = '<p><a class="btn  btn-xs" data-toggle="tooltip" data-placement="bottom" title="Active" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labdel(this,"' + emp.labtranid + '","active")><i class="fa fa-check-square-o" aria-hidden="true"></i> Active</a></p>';
                                active_inactive = '<a class="active_icon" title="Active" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labdel(this,"' + emp.labtranid + '","active")><i class="fa fa-check-square-o" aria-hidden="true"></i></a>';
                            }
                            else {
                                //active_inactive = '<p><a class="btn  btn-xs" data-toggle="tooltip" data-placement="bottom" title="In Active" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labdel(this,"' + emp.labtranid + '","inactive")><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</a></p>';
                                active_inactive = '<a class="inactive_icon" title="In Active" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=labdel(this,"' + emp.labtranid + '","inactive")><i class="fa fa-minus-square-o" aria-hidden="true"></i></a>';
                            }
                        }

                        //add_pin = '<p><a style="cursor:pointer;" data-toggle="modal"  title="Add Pincode" data-id="LS_A1" data-type="role_rights_add" data-nav="popup" data-name="add_pincodes" class="btn btn-xs" onclick=Addpincodepoppup(this,"' + emp.labtranid + '","0","L1")><i class="fa fa-plus-square" aria-hidden="true"></i> Add Pincode</a></p>';
                        //add_users = '<p data-toggle="modal" data-target="#adduser_modal"><a style="cursor:pointer;" data-toggle="modal"  title="Add Users" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_user" class="btn btn-xs" onclick=add_user(this,"' + emp.labtranid + '","0","' + emp.is_lab + '","L1","' + emp.is_externallab_id + '")><i class="fa fa-plus-square" aria-hidden="true"></i> Add Users</a></p>';
                        //add_services = '<p data-toggle="modal" data-target="#addservices_modal"><a style="cursor:pointer;" data-toggle="modal"  title="Add Services" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_service" class="btn btn-xs" onclick=add_service(this,"' + emp.labtranid + '","0","' + emp.is_lab + '","L1","' + emp.is_externallab_id + '")><i class="fa fa-plus-square" aria-hidden="true"></i> Add Services</a></p>';

                        add_pin = '<a style="cursor:pointer;" data-toggle="modal"  title="Add Pincode" data-id="LS_A1" data-type="role_rights_add" data-nav="popup" data-name="add_pincodes" onclick=Addpincodepoppup(this,"' + emp.labtranid + '","0","L1")> Add Pincode</a>';
                        add_users = '<a data-toggle="modal" data-target="#adduser_modal"  title="Add Users" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_user" onclick=add_user(this,"' + emp.labtranid + '","0","' + emp.is_lab + '","L1","' + emp.is_externallab_id + '")> Add Users</a>';
                        add_services = '<a data-toggle="modal" data-target="#addservices_modal"  title="Add Services" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_service" onclick=add_service(this,"' + emp.labtranid + '","0","' + emp.is_lab + '","L1","' + emp.is_externallab_id + '")> Add Services</a>';

                        if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 6) {
                            if (emp.status == "2") {
                                if (emp.is_externallab_id == 1) {
                                    //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active_inactive + '</div></div></div></div>';
                                    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>' + del + '</li><li>' + active_inactive + '</li></div></ul></div>';
                                }
                                else {
                                    //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active_inactive + '</div></div></div></div>';
                                    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>' + del + '</li><li>' + active_inactive + '</li></div></ul></div>';
                                }
                            }
                            else {
                                if (emp.branch_count == 0) {
                                    if (emp.is_externallab_id == 1) {
                                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active_inactive + '</div></div></div></div>';
                                        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>' + active_inactive + '</li></div></ul></div>';
                                    }
                                    else {
                                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active_inactive + '</div></div></div></div>';
                                        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>' + active_inactive + '</li></div></ul></div>';
                                    }
                                }
                                else {
                                    if (emp.is_externallab_id == 1) {
                                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + add_users + '' + add_services + '' + add_pin + '' + active_inactive + '</div></div></div></div>';
                                        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>' + active_inactive + '</li></div><li>' + add_users + '</li><li>' + add_services + '</li><li>' + add_pin + '</li>/ul></div>';
                                    }
                                    else {
                                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + add_users + '' + add_pin + '' + active_inactive + '</div></div></div></div>';
                                        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>' + active_inactive + '</li></div><li>' + add_users + '</li><li>' + add_pin + '</li></ul></div>';
                                    }
                                }
                            }
                        }
                        else {
                            if (emp.status == "2") {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + '</div></div>';
                                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>' + del + '</li></div></ul></div>';
                            }
                            else {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + '</div></div>';
                                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>';
                            }
                        }

                        if (emp.status == '1') {
                            act_inact_status = '<span class="label label-success">Active</span>';
                        }
                        else if (emp.status == '2') {
                            act_inact_status = '<span class="label label-warning">Inactive</span>';
                        }


                        if ($('#hiddenRole_id').val() != 2) {
                            if (emp.branch_count != 0) {
                                tr = tr + '<tr id="t_' + emp.labtranid + '"><td>' + j + '</td><td>' + emp.is_externallab + '</td><td class="tbl-name">' + emp.lab_name + '</td><td>' + emp.lablicenseno + '</td><td>' + emp.contactpersonname + '</td><td>' + emp.phone_number + '</td><td>' + branches + ' <span>' + emp.branch_count + '</span></td><td>' + emp.pin_code + '</td><td>' + act_inact_status + '</td><td>' + other_info + ' </td></tr>';
                            }
                        }
                        else {
                            tr = tr + '<tr id="t_' + emp.labtranid + '"><td>' + j + '</td><td>' + emp.is_externallab + '</td><td class="tbl-name">' + emp.lab_name + '</td><td>' + emp.lablicenseno + '</td><td>' + emp.contactpersonname + '</td><td>' + emp.phone_number + '</td><td>' + branches + ' <span>' + emp.branch_count + '</span></td><td>' + emp.pin_code + '</td><td>' + act_inact_status + '</td><td>' + other_info + ' </td></tr>';
                        }

                    });

                    $('#labsetuptable_body').html(tr);
                    $('#shade_slot').hide();
                    datatable('lab_table_list', 'Lab_Setup', 'Legal');
                }
            }
            else {
                console.log(data);
                $('#shade_slot').hide();
            }
        }
    });
}

//branch details (sub table)
function branchdetails(e, id) {
    debugger;
    var tr = e.closest('tr');
    var row = $('#lab_table_list').DataTable().row(tr);
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getbranchdetails(id)).show();
        tr.addClass('shown');
    }
}
function getbranchdetails(id) {
    debugger;
    div = $('<div/>')
    .addClass('loading')
    .addClass('table_child')
    .addClass('table-responsive');

    if ($('#hiddenRole_id').val() == 2) {
        var branch_details = {
            Dml_Indicator: "BD",
            labtranid: id,
        }
    }
    else {
        var branch_details = {
            Dml_Indicator: "BD",
            labtranid: id,
            branch_id: $('#HospitalBranchID').val()
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(branch_details),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data;
                    tr = $('<table class="table table-condensed body-borderless table_borderless tablecolumnsticky"/>');
                    tr.append('<thead><tr><th>S.No</th><th>Hospital Name</th><th>Branch Name</th><th>Status</th><th>Actions</th></tr></thead><tbody>');
                    $.each(data1.Table, function (i, emp) {
                        var edit = '', del = '', add_users = '', add_services = '', active_inactive_btn = '', act_inact_sts = '';

                        //del = '<button data-toggle="tooltip" data-placement="bottom" title="Delete"  class="btn deleteicon-btn btn-xs" data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","SDLMHB")><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        //add_pincode = '<p><i class="fa fa-plus-square" aria-hidden="true"></i><a style="cursor:pointer;" data-toggle="modal"  title="Add Pincode" data-id="LS_A1" data-type="role_rights_add" data-nav="popup" data-name="add_pincodes" class="btn btn-xs" onclick=Addpincodepoppup(this,"' + emp.labtranid + '","' + emp.branchid + '","L2")>Add Pincode</a></p>';
                        //add_users = '<p data-toggle="modal" data-target="#adduser_modal"><i class="fa fa-plus-square" aria-hidden="true"></i><a style="cursor:pointer;" data-toggle="modal"  title="Add Users" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_user" class="btn btn-xs" onclick=add_user(this,"' + emp.labtranid + '","' + emp.branchid + '","' + emp.is_lab + '","L2","' + emp.is_externallab + '")>Add Users</a></p>';
                        //add_services = '<p data-toggle="modal" data-target="#addservices_modal"><i class="fa fa-plus-square" aria-hidden="true"></i><a style="cursor:pointer;" data-toggle="modal"  title="Add Services" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_service" class="btn btn-xs" onclick=add_service(this,"' + emp.labtranid + '","' + emp.branchid + '","' + emp.is_lab + '","L2","' + emp.is_externallab + '")>Add Services</a></p>';

                        del ='<a title="Delete"  class="delete_icon" data-id="LS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="lab_details_form" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","SDLMHB")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        add_pincode ='<a data-toggle="modal" title="Add Pincode" data-id="LS_A1" data-type="role_rights_add" data-nav="popup" data-name="add_pincodes" onclick=Addpincodepoppup(this,"' + emp.labtranid + '","' + emp.branchid + '","L2")>Add Pincode</a>';
                        add_users = '<a data-toggle="modal" data-target="#adduser_modal"  title="Add Users" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_user" onclick=add_user(this,"' + emp.labtranid + '","' + emp.branchid + '","' + emp.is_lab + '","L2","' + emp.is_externallab + '")>Add Users</a>';
                        add_services = '<a data-toggle="modal" data-target="#addservices_modal"  title="Add Services" data-id="LS_F1" data-type="role_rights_function" data-nav="popup" data-name="add_service" onclick=add_service(this,"' + emp.labtranid + '","' + emp.branchid + '","' + emp.is_lab + '","L2","' + emp.is_externallab + '")>Add Services</a>';

                        if (emp.status == "2") {
                            //active_inactive_btn = '<p><i class="fa fa-check-square-o" aria-hidden="true"></i><a class="btn  btn-xs" data-toggle="tooltip" data-placement="bottom" title="Active Branch" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","B_active")>Active</a></p>';

                            active_inactive_btn = '<a class="active_icon" title="Active Branch" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","B_active")><i class="fa fa-check-square-o" aria-hidden="true"></i></a>';
                            act_inact_sts = '<span class="label label-warning">Inactive</span>';
                        }
                        else if (emp.status == "1") {
                           // active_inactive_btn = '<p><i class="fa fa-minus-square-o" aria-hidden="true"></i><a class="btn  btn-xs" data-toggle="tooltip" data-placement="bottom" title="In Active Branch" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","B_inactive")>In Active</a></p>';
                            active_inactive_btn = '<a title="In Active Branch" class="inactive_icon" data-id="LS_F1" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form"  href="javascript:void(0);" onclick=branch_delete(this,"' + emp.maphpbrtranid + '","' + emp.branchid + '","' + emp.labtranid + '","B_inactive")><i class="fa fa-minus-square-o" aria-hidden="true"></i></a>';
                            act_inact_sts = '<span class="label label-success">Active</span>';
                        }
                        else {
                            console.log(emp.status);
                        }


                        if (emp.is_externallab == 1) {
                            if (emp.status == "1") {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu dropdown-content" id=""> <div class="text-left">' + add_users + '' + add_services + '' + add_pincode + '' + active_inactive_btn + '</div></div></div></div>';
                                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>' + del + '</li><li>' + active_inactive_btn + '</li></div><li>' + add_users + '</li><li>' + add_services + '</li><li>' + add_pincode + '</li></ul></div>';
                            }
                            else {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu dropdown-content" id=""> <div class="text-left">' + active_inactive_btn + '</div></div></div></div>';
                                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>' + del + '</li><li>' + active_inactive_btn + '</li></div></ul></div>';
                            }
                        }
                        else {
                            if (emp.status == "1") {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu dropdown-content" id=""> <div class="text-left">' + add_users + '' + add_pincode + '' + active_inactive_btn + '</div></div></div></div>';
                                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>' + del + '</li><li>' + active_inactive_btn + '</li></div><li>' + add_users + '</li><li>' + add_pincode + '</li></ul></div>';
                            }
                            else {
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' <a href="#" class="dropdown-toggle btn  btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu dropdown-content" id=""> <div class="text-left">' + active_inactive_btn + '</div></div></div></div>';
                                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>' + del + '</li><li>' + active_inactive_btn + '</li></div></ul></div>';
                            }
                        }

                        row_data = '<tr><td>' + j + '</td><td hidden>' + emp.maphpbrtranid + '</td><td>' + emp.hospitalname + '</td><td hidden>' + emp.branchid + '</td><td>' + emp.branchname + '</td><td>' + act_inact_sts + '</td><td>' + other_info + '</td></tr>';
                        j = j + 1;
                        tr.append(row_data);
                    })
                    tr.append("</tbody>");

                    div.append(tr);
                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}

//load branch for user & service mapping
function LoadBranch(labtranid, branch_id) {
    debugger;
    var department = {
        Dml_Indicator: "USB",
        labtranid: labtranid,
        branch_id: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(department),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var branch;
                    var default_opt = '<option value="0">--Select--</option>';
                    $('#branch_adduser').empty();
                    $('#branch_addservice').empty();
                    $('#branch_pincode').empty();
                    $.each(data1.Table, function (i, emp) {
                        branch = branch + '<option value="' + emp.branchid + '">' + emp.branch_name + '</option>';
                    });
                    $('#branch_pincode').val('')
                    if (data1.Table.length == 1) {
                        $('#branch_adduser').append(branch);
                        $('#branch_addservice').append(branch);
                        $('#branch_pincode').append(branch);

                        $('#branch_adduser').addClass('disabled')
                        $('#branch_addservice').addClass('disabled')
                        $('#branch_pincode').addClass('disabled')

                        $('#user_service').removeClass('disabled')
                        $('#req_service').removeClass('disabled')

                        $('#pstate').removeClass('disabled')
                        $('#pcity').removeClass('disabled')
                    }
                    else {
                        $('#branch_adduser').append(default_opt + branch);
                        $('#branch_addservice').append(default_opt + branch);
                        $('#branch_pincode').append(default_opt + branch);

                        $('#branch_adduser').removeClass('disabled')
                        $('#branch_addservice').removeClass('disabled')
                        $('#branch_pincode').removeClass('disabled')

                        $('#user_service').addClass('disabled')
                        $('#req_service').addClass('disabled')

                        $('#pstate').addClass('disabled')
                        $('#pcity').addClass('disabled')
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

//branch delete, active and in-active
function branch_delete(e, branch_labtranid, branch_id, labtranid, indicator) {
    debugger;
    var msg_status = ''
    if (indicator == 'SDLMHB') {
        msg_status = 'Are You Sure, Do you want to Delete the branch?';
    }
    else if (indicator == 'B_active') {
        msg_status = 'Are You Sure, Do you want to Active the branch?';
    }
    else if (indicator == 'B_inactive') {
        msg_status = 'Are You Sure, Do you want to In-active the branch?';
    }
    else {
        console.log(msg_status);
    }

    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>", msg_status,
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 20000000,

          onShown: function (toast) {
              $("#confirmationRevertYes").click(function () {
                  debugger;
                  var br_labtranid = branch_labtranid
                  var lab_branchid = branch_id
                  var labtran_id = labtranid
                  if (labtranid != "") {
                      var servicevalues = {
                          Dml_Indicator: indicator,
                          map_br_tranid: br_labtranid,
                          labtranid: labtran_id,
                          branch_id: lab_branchid
                      }

                      $.ajax({
                          async: true,
                          type: 'POST',
                          url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                          contentType: 'application/json; charset=UTF-8',
                          data: JSON.stringify(servicevalues),
                          success: function (data) {
                              debugger;
                              var data2 = JSON.parse(data);
                              if (jQuery.isEmptyObject((data2.data))) {
                              }
                              else {
                                  if (data2.msg == "Success") {
                                      data1 = data2.data;
                                      if (indicator == 'SDLMHB') {
                                          if (data1.Table[0].status == 'usermapped') {
                                              toastr.warning("Selected Lab Service Provider is mapped with some User. Unable to Delete")
                                              return false;
                                          }
                                          else {
                                              toastr.success("Removed Successfully");
                                              loadlabdata()
                                          }
                                      }
                                      else if (indicator == 'B_active') {
                                          if (data1.Table[0].status == 'Branch Activated') {
                                              toastr.success('' + data1.Table[0].status + ' Successfully');
                                              loadlabdata()
                                          }
                                      }
                                      else if (indicator == 'B_inactive') {
                                          if (data1.Table[0].status == 'B_usermapped') {
                                              var map_lab_branchid = data1.Table[0].maphpbrtranid;
                                              var branch_labtran_id = data1.Table[0].labtranid;
                                              var lab_branch_id = data1.Table[0].branchid;
                                              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>", 'Selected Lab Branch is mapped with some User. Do you want to continue to In-active',
                                                            {
                                                                closeButton: true,
                                                                progressBar: true,
                                                                allowHtml: true,
                                                                timeOut: 20000000,

                                                                onShown: function (toast) {
                                                                    debugger;
                                                                    $("#confirmationRevertYes").click(function () {
                                                                        debugger;
                                                                        var servicevalues = {
                                                                            Dml_Indicator: 'BC_inact',
                                                                            map_br_tranid: map_lab_branchid,
                                                                            labtranid: branch_labtran_id,
                                                                            branch_id: lab_branch_id
                                                                        }

                                                                        $.ajax({
                                                                            async: true,
                                                                            type: 'POST',
                                                                            url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                                                                            contentType: 'application/json; charset=UTF-8',
                                                                            data: JSON.stringify(servicevalues),
                                                                            success: function (data) {
                                                                                debugger;
                                                                                var data1 = JSON.parse(data)
                                                                                if (data1.msg == "Success") {
                                                                                    var data2 = data1.data;
                                                                                    toastr.success('In Activated successfully');
                                                                                    loadlabdata();
                                                                                }
                                                                                else {
                                                                                    console.log(data2)
                                                                                }
                                                                            }
                                                                        })
                                                                    })
                                                                }
                                                            })
                                          }
                                          else if (data1.Table[0].status == 'Branch In-activated') {
                                              toastr.success('' + data1.Table[0].status + ' Successfully');
                                              loadlabdata()
                                          }
                                          else {
                                              console.log(data1.Table[0].status)
                                          }
                                      }
                                      else {
                                          console.log(data1.Table[0].status)
                                      }
                                  }
                              }
                          }
                      });
                  }

                  //else {

                  //    var branchid = $('#tbranchid_' + val).html()
                  //    branch_id = $.grep(branch_id, function (value) {
                  //        return value != branchid;
                  //    });
                  //    $('#hbranchid').val(branch_id.toString());
              });
          }
      });



}
// add user
function add_user(e, labtranid, branch_id, is_lab, val, is_externallab) {
    debugger;
    if (val == 'L1') {
        $('#userbranchname').removeClass('hidden');
    }
    else {
        $('#userbranchname').addClass('hidden');
    }

    $('#maplabusertable >tbody >tr').empty();
    $('#his_lab').val(is_lab);
    $('#His_inernal_user').val(is_externallab);
    $('#labtranid_user_service').val(labtranid);
    var labtranid = labtranid;
    var branch_id = branch_id;
    LoadBranch(labtranid, branch_id)

    load_user(labtranid, branch_id, val)
}

//load user
function load_user(labtranid, branch_id, val) {
    debugger;
    $('#Huserval').val(val)
    var flag_value = val;
    var services = {
        Dml_Indicator: "UDTA",
        labtranid: labtranid,
        branch_id: branch_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(services),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var data2 = data1.data.Table;

            $('#maplabusertable tbody').empty();
            $('#maplabusertable').dataTable().fnClearTable();
            $('#maplabusertable').dataTable().fnDraw();
            $('#maplabusertable').dataTable().fnDestroy();
            var value = "";
            for (var i = 0; i < data2.length; i++) {
                var labservicemapid = data2[i].master_service_id;
                ikey = i + 1;
                if (labservicemapid != null) {
                    if (labservicemapid == "") {
                        value = "";
                    }
                    else {
                        if (flag_value == 'L2') {
                            $('#userbranchname').addClass('hidden')
                            value = value + "<tr class='tr_input number' data-id='" + ikey + "' id='ts_" + ikey + "'><td>" + ikey + "</td><td id='tdoctoruserid_" + ikey + "' hidden>" + data2[i].master_service_id + "</td><td id='tbranch_id_" + ikey + "' hidden>" + data2[i].branch_id + "</td><td id='tbranch_name_" + ikey + "' hidden>" + data2[i].branch_name + "</td><td id='tuser_code_" + ikey + "'>" + data2[i].user_code + "</td><td id='tuser_service_" + ikey + "'>" + data2[i].first_name + "</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='labuserdelete(this,\"" + ikey + "\",\"" + data2[i].master_service_id + "\",\"" + data2[i].branch_id + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
                        }
                        else {
                            $('#userbranchname').removeClass('hidden')
                            value = value + "<tr class='tr_input number' data-id='" + ikey + "' id='ts_" + ikey + "'><td>" + ikey + "</td><td id='tdoctoruserid_" + ikey + "' hidden>" + data2[i].master_service_id + "</td><td id='tbranch_id_" + ikey + "' hidden>" + data2[i].branch_id + "</td><td id='tbranch_name_" + ikey + "'>" + data2[i].branch_name + "</td><td id='tuser_code_" + ikey + "'>" + data2[i].user_code + "</td><td id='tuser_service_" + ikey + "'>" + data2[i].first_name + "</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='labuserdelete(this,\"" + ikey + "\",\"" + data2[i].master_service_id + "\",\"" + data2[i].branch_id + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
                        }
                    }
                    $('#labuserAddTable_body').html(value);
                }
                else {
                }
            }
            datatable('maplabusertable', 'add_user_popup', 'Legal');
        }
    })
}

//add service
function add_service(e, labtranid, branch_id, is_lab, val, is_externallab) {
    debugger;
    $('#btn_service_submit').attr('disabled', false)
    if (val == 'L1') {
        $('#servicebranchname').removeClass('hidden')
    }
    else {
        $('#servicebranchname').addClass('hidden')
    }

    $('#maplabservicetable >tbody >tr').empty();
    $('#his_lab').val(is_lab);
    $('#his_internal').val(is_externallab);
    $('#labtranid_user_service').val(labtranid);
    var labtranid = labtranid;
    var branch_id = branch_id;
    LoadBranch(labtranid, branch_id)
    load_service(labtranid, branch_id, val)
}

//load service data
function load_service(labtranid, branch_id, val) { 
    debugger;
    $('#Hserviceval').val(val);
    var flag_value = val;
    var services = {
        Dml_Indicator: "SDTA",
        labtranid: labtranid,
        branch_id: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(services),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var data2 = data1.data.Table;
            console.log(data1);
            if (data1.msg == "Success") {

                $('#maplabservicetable tbody').empty();
                $('#maplabservicetable').dataTable().fnClearTable();
                $('#maplabservicetable').dataTable().fnDraw();
                $('#maplabservicetable').dataTable().fnDestroy();
                var value = "", service_status = '', active_inactive_serv = '';
                for (var i = 0; i < data2.length; i++) {
                    var labservicemapid = data2[i].labservicemapid;
                    if (labservicemapid != null) {
                        if (labservicemapid == '') {
                            value = ''
                        }
                        else {
                            ikey = i + 1;

                            if (data2[i].status == '2') {
                                active_inactive_serv = '<a type="button" class="btn btn-xs" data-id="SCD_F1"  data-toggle="tooltip" data-placement="bottom" title="Active Service" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form" onclick=labservicedelete(this,\'' + ikey + '\',"act_ser");><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></a>';
                            }
                            else if (data2[i].status == '1') {
                                active_inactive_serv = '<a type="button" class="btn  btn-xs" data-id="SCD_F1"  data-toggle="tooltip" data-placement="bottom" title="In Active Service" data-type="role_rights_function" data-nav="sp_div" data-name="lab_details_form" onclick=labservicedelete(this,\'' + ikey + '\',"inact_ser");><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></a>';
                            }
                            else {
                                console.log(data2[i].status);
                            }

                            if (data2[i].status == '2' || data2[i].status == '3') {
                                service_status = '<span class="label label-warning">Inactive</span>';
                            }
                            else if (data2[i].status == '1') {
                                service_status = '<span class="label label-success">Active</span>';
                            }
                            else {
                                console.log(data2[i].status);
                            }
                            debugger;
                            if (flag_value == 'L2') {
                                $('#servicebranchname').addClass('hidden')
                                value = value + "<tr class='tr_input number' data-id='" + ikey + "' id='ts_" + ikey + "'><td>" + ikey + "</td><td id='tmaster_service_id_" + ikey + "' hidden>" + data2[i].master_service_id + "</td><td id='tlabservicemapid_" + ikey + "' hidden>" + data2[i].labservicemapid + "</td><td id='tservicebranch_id_" + ikey + "' hidden>" + data2[i].branch_id + "</td><td id='tservicebranch_name_" + ikey + "' hidden>" + data2[i].branch_name + "</td><td id='tservicecode_" + ikey + "'>" + data2[i].service_code + "</td><td id='treq_service_" + ikey + "'>" + data2[i].service_name + "</td><td>" + data2[i].lab_amount + "</td><td>" + service_status + "</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='labservicedelete(this,\"" + ikey + "\",\"" + 1 + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button>" + active_inactive_serv + "</td></tr>";
                            }
                            else {
                                $('#servicebranchname').removeClass('hidden')
                                value = value + "<tr class='tr_input number' data-id='" + ikey + "' id='ts_" + ikey + "'><td>" + ikey + "</td><td id='tmaster_service_id_" + ikey + "' hidden>" + data2[i].master_service_id + "</td><td id='tlabservicemapid_" + ikey + "' hidden>" + data2[i].labservicemapid + "</td><td id='tservicebranch_id_" + ikey + "' hidden>" + data2[i].branch_id + "</td><td id='tservicebranch_name_" + ikey + "'>" + data2[i].branch_name + "</td><td id='tservicecode_" + ikey + "'>" + data2[i].service_code + "</td><td id='treq_service_" + ikey + "'>" + data2[i].service_name + "</td><td>" + data2[i].lab_amount + "</td><td>" + service_status + "</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='labservicedelete(this,\"" + ikey + "\",\"" + 1 + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button>" + active_inactive_serv + "</td></tr>";
                            }
                        }
                        $('#labserviceAddTable_body').html(value);
                    }
                }
                datatable('maplabservicetable', 'add_service_popup', 'Legal');
            }           
        }
    })
}


$('#branch_adduser').change(function () {
    debugger;

    var labtranid = $('#labtranid_user_service').val()
    var branch_id = $('#branch_adduser').val()
    var val = $('#Huserval').val()
    load_user(labtranid, branch_id, val)

    if ($('#branch_adduser').val() == 0) {
        $('#user_service').addClass('disabled')
    }
    else {
        $('#user_service').removeClass('disabled')
        $('#user_service').val('');
    }
});

$('#branch_addservice').change(function () {
    debugger;
    var labtranid = $('#labtranid_user_service').val()
    var branch_id = $('#branch_addservice').val()
    var val = $('#Hserviceval').val()
    load_service(labtranid, branch_id, val)

    if ($('#branch_addservice').val() == 0) {
        $('#req_service').addClass('disabled')
    }
    else {
        $('#req_service').removeClass('disabled')
        $('#req_service').val('');
    }
});

//$('#POP_filter_Sbranch').change(function () {
//    debugger;
//    if ($('#req_service').val() == '') {
//        var labtranid = $('#labtranid_user_service').val()
//        var branch_id = $('#POP_filter_Sbranch').val()
//        var val = $('#Hserviceval').val()
//        load_service(labtranid, branch_id, val)
//    }
//})


$('#branch_pincode').change(function () {
    debugger;
    if ($('#branch_pincode').val() == 0) {
        $('#pstate').addClass('disabled')
        $('#pcity').addClass('disabled')
    }
    else {
        $('#pstate').removeClass('disabled')
        $('#pcity').removeClass('disabled')
    }
});


//lab diagnostics getsample dropdown
function Addpincodepoppup(event, labtranid, branch_id, val) {
    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 {
                     $('#pincodetable_body').empty();
                     LoadBranch(labtranid, branch_id)
                     //$('#branch_pincode').val(branch_id)
                     loadpstate();
                     load_pincode(labtranid, branch_id, val, 'lpc')
                     $('#Hlabtranid').val(labtranid);
                     $('#labid').val(labtranid);
                     $('#pincode_table_list').dataTable().fnClearTable();
                     $('#pincode_table_list').dataTable().fnDraw();
                     $('#pincode_table_list').dataTable().fnDestroy();
                 }
             }
         }
     });

    //var labvalues = {     
    //    Dml_Indicator: "GPIN"
    //}

    //$.ajax({
    //    async: true,
    //    type: 'POST',
    //    url: '/Master_Lab/Master_Lab_Ins_upd_sel',
    //    contentType: 'application/json; charset=UTF-8',
    //    data: JSON.stringify(labvalues),
    //    success: function (data) {
    //        debugger;
    //        var data = JSON.parse(data);
    //        console.log(data);
    //        if (data.msg == "Success") {
    //            var data1 = data.data;
    //            if (jQuery.isEmptyObject((data1))) {
    //            }
    //            else {
    //                var ck = '', j = 0;
    //                var b = data1.Table;
    //                $.each(b, function (i, emp) 
    //                {
    //                    j++;
    //                    ck = ck + '<div class="col-md-6"><div class="form-group form-field-height"><input type="checkbox" id="" name="" data-pin=' + emp.pincode + ' data-area=' + emp.place + '><label for="vehicle1">' + emp.pincode + ' ,&nbsp;' + emp.place + '.</label></div></div>'
    //                })
    //                $('#pincodediv').html(ck);
    //            }
    //        }

    //    }
    //});

}
//Hospital Detail drop down Function
function HospitalDetails() {

    debugger;
    var HosTbldata = {

        Dml_Indicator: 'HP'
    }

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

            }
            else {

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

                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}

//branch deatils drop down 
$('#hospitalname').change(function () {
    var Hospitalid = $('#hospitalname').val();
    Branchdetails(Hospitalid);
});

function Branchdetails(Hospitalid) {

    debugger;
    var Branch_data = {
        hospitalid: Hospitalid,
        Dml_Indicator: 'HBRNS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Branch_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;


                    $('#branchname').empty();
                    var branchname;
                    var default_opt = '<option value="0" data-id="">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        branchname = branchname + '<option value="' + emp.hospital_branch_id + '" data-id="' + emp.branch_name + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#branchname').html(branchname);
                    }
                    else {
                        $('#branchname').html(default_opt + branchname);
                    }
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#branchname').val($('#HospitalBranchID').val());
                        $('#branchname').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function refereshform() {
    debugger;
    $("#lab_name").val('');
    $("#lablicenseno").val('');
    $("#labimagepath").val('');
    $("#contactpersonname").val('');
    $("#phone_number").val('');
    $("#txtEmailid").val('');
    $("#address1").val('');
    $("#address2").val('');
    $("#area").val('');
    //$("#country").val('');
    //$("#state").val('');
    //$("#city").val('');
    $('a[data-toggle=is_externallab][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_externallab][data-title="0"]').removeClass('active');
    $('a[data-toggle=is_externallab][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_externallab][data-title="0"]').addClass('not-active');


    $('a[data-toggle=is_lab][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_lab][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_lab][data-title="2"]').removeClass('active');
    $('a[data-toggle=is_lab][data-title="2"]').addClass('not-active');
    $('a[data-toggle=is_lab][data-title="3"]').removeClass('active');
    $('a[data-toggle=is_lab][data-title="3"]').addClass('not-active');

    $("#labdescription").val('');
    $("#labtranid").val('');
    $("#labserviceAddTable_body").empty()
    $("#labuserAddTable_body").empty()
    $("#labhospitalAddTable_body").empty()
    $('#Add_hpbr_record').show();
    $('#Update_hpbr_record').hide();
    $('#Add_labservicemap_record').show();
    $('#Update_labservicemap_record').hide();
    $('.lab_div').removeClass('disabled');
    $("#is_lab").val('');
    $('#pin_code').val('');
    //$('#branchname').val(0);
    branch_id = [];

}
//lab edit fuction
function labedit(event, val) {
    $('#shade_slot').show();
    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");
    $('#req_service').removeClass('disabled');
    $('#Add_labservicemap_record').removeClass('disabled')
    $('#user_service').removeClass('disabled');
    $('#Add_usermap_record').removeClass('disabled')
    debugger;
    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 {

                     $('#lab_creation_form').show();
                     $('#labdetailslist').hide();
                     $('#add_new_lab_setup').hide();
                     $('#lab_details_form').show();
                     $('#add_new_lab_setup').hide();
                     $('.progress-container').show();

                     //$(".dtfh-floatingparent.dtfh-floatingparenthead th").click();

                     //$('.box').addClass('box-with-trackbar');
                     $('.table_view').hide();
                     var labvalues = {
                         Dml_Indicator: "E",
                         labtranid: val,
                         branch_id: $('#HospitalBranchID').val()
                     }
                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(labvalues),
                         success: function (data) {
                             debugger;
                             $(".dtfh-floatingparent.dtfh-floatingparenthead th").click();
                             var data1 = JSON.parse(data);

                             if (data1.msg == "Success") {
                                 var data1 = data1.data;
                                 if (jQuery.isEmptyObject((data1))) {
                                 }

                                 else {

                                     var data2 = data1.Table;
                                     refereshform();
                                     if (data2[0].is_externallab == 0) {
                                         $('#service_lab').removeClass('hidden')
                                         $('#lab_license').addClass('hidden')
                                         $('#lab_image').addClass('hidden')
                                         $('#contact_person').removeClass('hidden')
                                         $('#mobile_no').removeClass('hidden')
                                         $('#emailid').removeClass('hidden')
                                         $('#islab').removeClass('hidden')
                                         // $('#pincode').removeClass('hidden')
                                         $('#description').removeClass('hidden')

                                         $('#header_title').html('Lab Details')
                                         $('#Details').html('Lab Details')
                                         $('#spln').html('Lab Name');
                                         $('#sldescription').html('Lab Description');
                                         $('#address_detail').html('Lab Address Details')
                                     }
                                     else {
                                         $('#service_lab').removeClass('hidden')
                                         $('#lab_license').removeClass('hidden')
                                         $('#lab_image').removeClass('hidden')
                                         $('#contact_person').removeClass('hidden')
                                         $('#mobile_no').removeClass('hidden')
                                         $('#emailid').removeClass('hidden')
                                         $('#islab').removeClass('hidden')
                                         //$('#pincode').removeClass('hidden')
                                         $('#description').removeClass('hidden')

                                         $('#header_title').html('Service Provider Details')
                                         $('#Details').html('Service Provider Details')
                                         $('#spln').html('Service Provider Name');
                                         $('#sldescription').html('Service Provider Description');
                                         $('#address_detail').html('Service Provider address Details')
                                     }

                                     $('.lab_div').addClass('disabled');
                                     $("#lab_name").val(data2[0].lab_name);
                                     $("#labtranid").val(data2[0].labtranid);
                                     $("#lablicenseno").val(data2[0].lablicenseno);
                                     $("#imagefile").val(data2[0].labimagepath);
                                     $("#contactpersonname").val(data2[0].contactpersonname);
                                     $("#phone_number").val(data2[0].phone_number);
                                     $("#txtEmailid").val(data2[0].email_id);
                                     $("#address1").val(data2[0].address1);
                                     $("#address2").val(data2[0].address2);
                                     $("#area").val(data2[0].area);
                                     $("#country").val(data2[0].country);
                                     getstate(data2[0].state);
                                     // $("#state").val(data2[0].state);
                                     getcity(data2[0].city, data2[0].state);
                                     // $("#city").val(data2[0].city);
                                     $("#is_externallab").val(data2[0].is_externallab)
                                     $("#is_lab").val(data2[0].is_lab)
                                     $('a[data-toggle=is_externallab][data-title="' + data2[0].is_externallab + '"]').removeClass('not-active');
                                     $('a[data-toggle=is_externallab][data-title="' + data2[0].is_externallab + '"]').addClass('active');

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

                                     $('#pin_code').val(data2[0].pin_code)

                                     $("#labdescription").val(data2[0].labdescription);
                                     $('#labhospitalAddTable_body').val('');
                                     $('#labhospitalAddTable_body').empty('');
                                     $('#labhospitalAddTable_body').append('');
                                     $('#maphbtable >tbody >tr').empty('');
                                     var ikey;
                                     var j = 0;
                                     for (var i = 0; i < data2.length; i++) {
                                         var maphpbrtranid = data2[i].maphpbrtranid;
                                         ikey = i;
                                         j = j + 1;
                                         if (maphpbrtranid != null) {
                                             if (maphpbrtranid == "") {
                                                 var value = "";
                                             }
                                             else {
                                                 var branchid = data2[i].branchid;
                                                 branch_id.push(branchid);
                                                 console.log(branch_id)
                                                 $('#hbranchid').val(branch_id.toString());

                                                 var br_status = '';
                                                 if (data2[i].branch_status == 1) {
                                                     br_status = '<span class="label label-success">Active</span>';
                                                 }
                                                 else {
                                                     br_status = '<span class="label label-warning">Inactive</span>';
                                                 }

                                                 //var value = "<tr class='tr_input number' data-id='" + ikey + "' id='t_" + ikey + "'><td>" + j + "</td><td id='tmaphpbrtranid_" + ikey + "' hidden>" + data2[i].maphpbrtranid + "</td><td id='thospitalid_" + ikey + "' hidden>" + data2[i].hospitalid + "</td><td id='tbranchid_" + ikey + "' hidden>" + data2[i].branchid + "</td><td id='thospitalname_" + ikey + "'>" + data2[i].hospitalname + "</td><td id='tbranchname_" + ikey + "'>" + data2[i].branchname + "</td><td><button class='btn btn-edit  btn-xs btn-add' onclick='maphbedit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-delete  btn-sm btn-add' onclick='maphbdelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
                                                 var value = "<tr class='tr_input number' data-id='" + ikey + "' id='t_" + ikey + "'><td>" + j + "</td><td id='tmaphpbrtranid_" + ikey + "' hidden>" + data2[i].maphpbrtranid + "</td><td id='thospitalid_" + ikey + "' hidden>" + data2[i].hospitalid + "</td><td id='tbranchid_" + ikey + "' hidden>" + data2[i].branchid + "</td><td id='thospitalname_" + ikey + "'>" + data2[i].hospitalname + "</td><td id='tbranchname_" + ikey + "'>" + data2[i].branchname + "</td><td id='tbranstatus_" + ikey + "'>" + br_status + "</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='maphbdelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";

                                             }
                                             $('#maphbtable > tbody:last').append(value);
                                         }
                                         else {

                                         }
                                     }
                                 }
                             }
                             else {
                                 console.log(data);
                             }
                             $('#shade_slot').hide();
                         }
                     });


                     $("html, body").animate({ scrollTop: 0 }, 2000);
                 }
             }
         }
     });
}
// delete lab data
function labdel(event, val, Dml_Indicator) {
    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");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             debugger;
             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 status = "";
                     if (Dml_Indicator == 'active') {
                         status = "Are You Sure, Do you Want to Active the Lab?";
                     }
                     else if (Dml_Indicator == 'inactive') {
                         status = "Are You Sure, Do you Want to In-active the Lab?";
                     }
                     else if (val != '') {

                         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 () {
                       debugger;
                       if ($('#hiddenRole_id').val() == 2) {
                           var servicevalues = {
                               labtranid: val,
                               Dml_Indicator: Dml_Indicator
                           }
                       }
                       else {
                           var servicevalues = {
                               labtranid: val,
                               Dml_Indicator: Dml_Indicator,
                               branch_id: $('#HospitalBranchID').val()
                           }
                       }

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

                               var data2 = JSON.parse(data);


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

                               }
                               else {

                                   if (data2.msg == "Success") {
                                       debugger;
                                       data1 = data2.data;
                                       if (Dml_Indicator == 'D' || Dml_Indicator == 'UBD') {

                                           if (data1.Table[0].status == 'usermapped') {
                                               toastr.warning("Selected Lab Service Provider is mapped with some User. Unable to Delete")
                                               return false;
                                           }
                                           else {
                                               toastr.success("Lab Deleted Successfully ");
                                               $('#t_' + val).remove();
                                               setTimeout(function () {
                                                   location.reload();
                                               }, 1000)
                                           }
                                       }
                                       else if (Dml_Indicator == 'active') {
                                           toastr.success("Activated Successfully");
                                           loadlabdata()
                                       }
                                       else if (Dml_Indicator == 'inactive') {

                                           //toastr.success("In-activated Successfully");
                                           //loadlabdata()
                                           if (data1.Table[0].status == 'usermapped') {
                                               toastr.warning("Selected Lab Service Provider is mapped with some User. Unable to Delete")
                                               return false;
                                           }
                                           else {
                                               toastr.success("In-activated Successfully");
                                               loadlabdata()
                                           }
                                       }
                                       else {
                                           toastr.warning("Somthing Went Wrong");
                                           return false;
                                       }
                                   }
                               }
                           }
                       });
                   });
               }
           });
                 }
             }
         }
     });
}

//insert and update function
$("#btnsubmit").click(function () {
    debugger;
    insertupdatelabmaphb();
})

function insertupdatelabmaphb() {
    debugger;
    var lab_name = $("#lab_name").val();
    var lablicenseno = $("#lablicenseno").val();
    var labimagepath = $("#labimagepath").val();
    var contactpersonname = $("#contactpersonname").val();
    var phone_number = $("#phone_number").val();
    var email_id = $("#txtEmailid").val();
    var address1 = $("#address1").val();
    var address2 = $("#address2").val();
    var area = $("#area").val();
    var country = $("#country").val();
    var state = $("#state").val();
    var city = $('#city').val();
    var labdescription = $("#labdescription").val();
    var is_externallab = $("#is_externallab").val();
    var is_lab = $("#is_lab").val();
    var pincode = $('#pin_code').val();


    if ($.trim((is_externallab)) == "") {
        $('#Pis_externallab').show();
        $('#Pis_externallab').fadeOut(8000);
        $('#Pis_externallab').html('Kindly Select Is Internal');
        $('#is_externallab').focus();
        return false;
    }

    if ($('#is_externallab').val() == 0) {

        if ($.trim((lab_name)) == "") {
            $('#Plab_name').show();
            $('#Plab_name').fadeOut(8000);
            $('#Plab_name').html('Kindly enter the Lab Name');
            $('#lab_name').focus();
            return false;
        }

        if ($.trim((phone_number)) == "") {
            $('#Pphone_number').show();
            $('#Pphone_number').fadeOut(8000);
            $('#Pphone_number').html('Kindly enter the Phone Number.');
            $('#phone_number').focus();
            return false;
        }

        if ($.trim((is_lab)) == "") {
            $('#Pis_lab').show();
            $('#Pis_lab').fadeOut(8000);
            $('#Pis_lab').html('Kindly Select Is lab');
            $('#Pis_lab')[0].scrollIntoView(true);
            return false;
        }

        //if ($.trim((pincode)) == "") {
        //    $('#Ppin_code').show();
        //    $('#Ppin_code').fadeOut(8000);
        //    $('#Ppin_code').html('Kindly enter the Pin Code.');
        //    $('#pin_code').focus();
        //    return false;
        //}
    }

    if ($('#is_externallab').val() == 1) {

        if ($.trim((lab_name)) == "") {
            $('#Plab_name').show();
            $('#Plab_name').fadeOut(8000);
            $('#Plab_name').html('Kindly enter the Service Provider Name');
            $('#lab_name').focus();
            return false;
        }

        if ($.trim((lablicenseno)) == "") {
            if ($.trim((is_lab)) == "1") {
                $('#Plablicenseno').show();
                $('#Plablicenseno').fadeOut(8000);
                $('#Plablicenseno').html('If Lab is Yes,Kindly enter the License No.');
                $('#lablicenseno').focus();
                return false;
            }
        }

        if ($.trim((phone_number)) == "") {
            $('#Pphone_number').show();
            $('#Pphone_number').fadeOut(8000);
            $('#Pphone_number').html('Kindly enter the Phone Number.');
            $('#phone_number').focus();
            return false;
        }

        if ($.trim((is_lab)) == "") {
            $('#Pis_lab').show();
            $('#Pis_lab').fadeOut(8000);
            $('#Pis_lab').html('Kindly Select Is lab');
            $('#Pis_lab')[0].scrollIntoView(true);
            return false;
        }

        //if ($.trim((pincode)) == "") {
        //    $('#Ppin_code').show();
        //    $('#Ppin_code').fadeOut(8000);
        //    $('#Ppin_code').html('Kindly enter the Pin Code.');
        //    $('#pin_code').focus();
        //    return false;
        //}
    }

    if ($.trim((address1)) == "") {
        $('#Paddress1').show();
        $('#Paddress1').fadeOut(8000);
        $('#Paddress1').html('Please Enter Line1 Address');
        $('#address1').focus();
        return false;
    }

    if ($.trim((country)) == "" || $.trim((country)) == 0) {
        $('#Pcountry').show();
        $('#Pcountry').fadeOut(8000);
        $('#Pcountry').html('Select the Country');
        $('#country').focus();
        return false;
    }

    if ($.trim((state)) == "" || $.trim((state)) == 0) {
        $('#Pcountry').show();
        $('#Pcountry').fadeOut(8000);
        $('#Pcountry').html('Select the State');
        $('#state').focus();
        return false;
    }

    if ($.trim((city)) == "" || $.trim((city)) == 0) {
        $('#Pcity').show();
        $('#Pcity').fadeOut(8000);
        $('#Pcity').html('Select the City');
        $('#city').focus();
        return false;
    }

    if ($.trim((pincode)) == "") {
        $('#Ppin_code').show();
        $('#Ppin_code').fadeOut(8000);
        $('#Ppin_code').html('Kindly enter the Pin Code.');
        $('#pin_code').focus();
        return false;
    }

    var tot_rowM = $('#maphbtable >tbody >tr').length;
    if (tot_rowM == 0) {

        toastr.warning('Please Add Hospital Details');
        $('#Pbranchname').show();
        $('#Pbranchname').fadeOut(8000);
        $('#Pbranchname').html('Please Add Hospital Details');
        $('#Pbranchname')[0].scrollIntoView(true);
        return false;
    }

    $('#shade_slot_submit').show();
    var Dml_Indicator;
    var labtranid = $("#labtranid").val()
    if (labtranid != '') {
        Dml_Indicator = 'U'
        Dml_Indicator_P = 'UMHB'
    }
    else {

        Dml_Indicator = 'I'
        Dml_Indicator_P = 'IMHB'
    }
    var labtranid = 0;
    var servicevalues = {

        Dml_Indicator: Dml_Indicator
      , labtranid: $("#labtranid").val()
      , lab_name: $("#lab_name").val()
      , lablicenseno: $("#lablicenseno").val()
      , labimagepath: $("#imagefile").val()
      , contactpersonname: $("#contactpersonname").val()
      , phone_number: $("#phone_number").val()
      , email_id: $("#txtEmailid").val()
      , address1: $("#address1").val()
      , address2: $("#address2").val()
      , area: $("#area").val()
      , country: $("#country").val()
      , state: $("#state").val()
      , city: $("#city").val()
      , labdescription: $("#labdescription").val()
      , is_externallab: $("#is_externallab").val()
      , is_lab: $("#is_lab").val()
      , pin_code: $('#pin_code').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var data2 = data1.Table;
                    labtranid = data2[0].labtranid;
                    if (data2[0].labtranid == 'duplicate') {
                        if ($('#hiddenRole_id').val() == 2) {
                            toastr.warning("This lab/service provider name already exists.");
                        }
                        else {
                            toastr.warning("This lab/service provider name already exists. Please contact admin");
                        }

                        $('#lab_name').val('')
                        $('#phone_number').val('')
                        $('#shade_slot_submit').hide()
                        //setTimeout(function () {
                        //    location.reload();
                        //}, 3000);
                        return false;

                    }
                    debugger;
                    var customers = new Array();
                    var tot_rowM = $('#maphbtable >tbody >tr').length;
                    if (tot_rowM > 0) {
                        var L = 0;

                        for (j = 0; j <= tot_rowM; j++) {
                            var customer = {};

                            customer.labtranid = data2[0].labtranid;
                            customer.hospitalid = $('#thospitalid_' + j).html();
                            hospitalid = $('#thospitalid_' + j).html();
                            customer.maphpbrtranid = $('#tmaphpbrtranid_' + j).html();
                            customer.branchid = $('#tbranchid_' + j).html();
                            customer.Dml_Indicator = Dml_Indicator_P
                            customer.created_by = $('#hiddenUser_id').val()
                            if (hospitalid != undefined) {
                                customers.push(customer);
                            }
                        }

                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Master_Lab/Master_Lab_Ins_upd_sel_MHB',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(customers),
                            success: function (data) {
                                $('#shade_slot_submit').hide();
                                debugger
                                var data1 = JSON.parse(data);
                                console.log(data1);
                                if (data1.msg == "Success") {
                                    if (Dml_Indicator == 'I') {
                                        toastr.success("Lab Created Successfully");
                                        setTimeout(function () {
                                            location.reload();
                                        }, 1000);
                                    }
                                    else {
                                        toastr.success("Lab Updated Successfully");
                                        setTimeout(function () {
                                            location.reload();
                                        }, 1000);
                                    }
                                }
                            }
                        });
                    }
                    else {

                        if (Dml_Indicator == 'U') {
                            toastr.success("Lab Updated Successfully");
                            // location.reload();
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                        else if (Dml_Indicator == 'I') {
                            toastr.success("Lab Created Successfully");
                            //location.reload();
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    }
                }
            }
        },
        error: function (data) {
            toastr.warning("Error Occured");
        }
    });
}

// Lab image upload
$('#labdocuments').change(function () {
    labimageUpload();
});

function labimageUpload() {
    debugger;
    var uploadpath = $('#labdocuments').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#labdocuments").get(0);
        var files = fileUpload.files;
        if (files[0].size > 5e+6) {
            //alert("up to 5 MB per file!");
            toastr.warning('Upto 5 MB Per File!');
            return false;
        };
        var filePath = fileUpload.value;

        // Allowing file type
        var allowedExtensions =
                /(\.jpg|\.jpeg)$/i;

        if (!allowedExtensions.exec(filePath)) {
            toastr.warning('Invalid File Type');
            fileInput.value = '';
            return false;
        }

        $.when(checkimagedimensionvalidation(fileUpload.files[0], 512, 512)).
          done(function (Results) {
              if (Results == 'Success') {

                  var fileData = new FormData();
                  for (var i = 0; i < files.length; i++) {
                      fileData.append(files[i].name, files[i]);
                  }
                  fileData.append('username', 'Manas');
                  $.ajax({
                      url: '/Master_Lab/UploadPhotoFiles',
                      type: "POST",
                      contentType: false, // Not to set any content header
                      processData: false, // Not to process data
                      data: fileData,
                      success: function (result) {
                          console.log(result);
                          $.each(result, function (i, emp) {
                              $('#Hdn_lab_image').val(emp);
                              $('#imagefile').val(emp);

                              var filepath = $('#hdnfilepath1').val();
                              var profilephoto = $('#Hdn_lab_image').val();
                              var Doctor_Id = $('#myHiddenVar').val();
                              var d, n, drloimage;
                              d = new Date();
                              n = d.getTime();
                              drinimage = filepath + Doctor_Id + '/labimage/' + profilephoto + '?' + n;
                              $('#photolog').empty();

                              $('#photolog').append('<a href="' + drinimage + '" target="_blank">Lab Image</a>');
                          });
                      }
                  });
              }
              else {
                  $('#Hdn_lab_image').val('');
                  $('#imagefile').val('');
                  $('#photolog').empty();
              }
              // this code is executed when all ajax calls are done
          });
    }
}

//add   lab hospital and branch mapping table
$('#Add_hpbr_record').click(function () {
    debugger;
    var hospitalname = $('#hospitalname option:selected').data('id');
    var branchname = $('#branchname option:selected').data('id');
    var hospitalid = $('#hospitalname').val();
    var branchid = $('#branchname').val();
    var maphpbrtranid = $('#maphpbrtranid').val();
    if ($.trim((hospitalname)) == "") {
        $('#Phospitalname').show();
        $('#Phospitalname').fadeOut(8000);
        $('#Phospitalname').html('Select Hospital Name');
        $('#hospitalname').focus();
        return false;
    }
    if ($.trim((branchname)) == "") {
        $('#Pbranchname').show();
        $('#Pbranchname').fadeOut(8000);
        $('#Pbranchname').html('Select Branch Name');
        $('#branchname').focus();
        return false;
    }

    var val1 = 0;
    var ikey = "0";
    var rowcount = $('#maphbtable >tbody >tr').length;
    if (rowcount == 0) {
        var ikey = 1
    }
    else {

        var max = 0;

        $('.number').each(function () {

            var value = parseInt($(this).data('id'));

            max = (value > max) ? value : max;
            var brname = $('#tbranchid_' + value).html();
            if (branchid == brname) {
                val1 = 1;
            }
        });
        var ikey = Number(max) + 1;
    }
    if (val1 == 1) {
        toastr.warning('Branch name is already Exist');
        $('#branchname').val(0);
        return false;
    }

    var branchid = $('#branchname').val();
    branch_id.push(branchid);
    console.log(branch_id)
    $('#hbranchid').val(branch_id.toString());

    var value = "<tr class='tr_input number' data-id='" + ikey + "' id='t_" + ikey + "'><td>" + ikey + "</td><td id='tmaphpbrtranid_" + ikey + "' hidden>" + maphpbrtranid + "</td><td id='thospitalid_" + ikey + "' hidden>" + hospitalid + "</td><td id='tbranchid_" + ikey + "' hidden>" + branchid + "</td><td id='thospitalname_" + ikey + "'>" + hospitalname + "</td><td id='tbranchname_" + ikey + "'>" + branchname + "</td><td>-</td><td><button class='btn btn-delete  btn-sm btn-add' onclick='maphbdelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";

    $('#maphbtable > tbody:last').append(value);
    if ($('#hiddenRole_id').val() == 2) {
        if ($('#branchname > option').length != 1) {
            $('#branchname').val('0');
        }
        if (branchid != '') {
            $('#Add_labservicemap_record').removeClass('disabled')
            $('#user_service').removeClass('disabled');
            $('#Add_usermap_record').removeClass('disabled')
        }
    }
    else {
        if ($('#branchname > option').length != 1) {
            $('#branchname').val(branchid);
        }
        if (branchid != '') {
            $('#Add_labservicemap_record').removeClass('disabled')
            $('#user_service').removeClass('disabled');
            $('#Add_usermap_record').removeClass('disabled')
        }
    }
});

// update lab hospital and branch mapping table
$('#Update_hpbr_record').click(function () {
    debugger;

    var hospitalname = $('#hospitalname option:selected').data('id');
    var branchname = $('#branchname option:selected').data('id');
    var hospitalid = $('#hospitalname').val();
    var branchid = $('#branchname').val();
    var rowid = $('#rowid').val();
    var val1 = 0;
    $('.number').each(function () {

        var value = parseInt($(this).data('id'));
        var brname = $('#tbranchid_' + value).html();
        if (branchid == brname) {
            val1 = 1;
        }
    });
    if (val1 == 1) {
        toastr.warning('Branch name is already Exist');
        return false;
    }
    $('#tbranchname_' + rowid).html(branchname);
    $('#thospitalname_' + rowid).html(hospitalname);
    $('#thospitalid_' + rowid).html(hospitalid);
    $('#tbranchid_' + rowid).html(branchid);
    $('#branchname').val('0');
    // $('#hospitalname').val('0');
    $('#Add_hpbr_record').show();
    $('#Update_hpbr_record').hide();
});

//function maphbedit(val) {

//    debugger;

//    var thospitalid = $('#thospitalid_' + val).html();
//    var tbranchid = $('#tbranchid_' + val).html();

//    $("#branchname").val(tbranchid);
//    $("#rowid").val(val);

//    $('#Add_hpbr_record').hide();
//    $('#Update_hpbr_record').show();
//}


// delete hospital and branch mapping in lab
function maphbdelete(val) {
    debugger;
    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>", 'Are You Sure, You want to Delete?',
       {

           closeButton: true,
           progressBar: true,
           allowHtml: true,
           timeOut: 20000000,

           onShown: function (toast) {
               $("#confirmationRevertYes").click(function () {
                   debugger;
                   var paraid = $("#tmaphpbrtranid_" + val + "").html();
                   if (paraid != "") {

                       var servicevalues = {
                           Dml_Indicator: "DLMHB",
                           labtranid: paraid

                       }
                       $.ajax({
                           async: true,
                           type: 'POST',
                           url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                           contentType: 'application/json; charset=UTF-8',
                           data: JSON.stringify(servicevalues),
                           success: function (data) {
                               debugger;

                               var data2 = JSON.parse(data);

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

                               }
                               else {

                                   if (data2.msg == "Success") {
                                       data1 = data2.data;
                                       if (data1.Table[0].status == 'usermapped') {
                                           toastr.warning("Selected Service/Lab Service Provider is mapped with some User. Unable to Delete")
                                           return false;
                                       }

                                       var branchid = $('#tbranchid_' + val).html()
                                       branch_id = $.grep(branch_id, function (value) {
                                           return value != branchid;
                                       });
                                       $('#hbranchid').val(branch_id.toString());

                                       sessionStorage.removeItem(val);
                                       $('#t_' + val).remove();
                                       toastr.success("Removed Successfully");
                                       loadlabdata()
                                   }
                               }
                           }
                       });
                   }
                   else {
                       var branchid = $('#tbranchid_' + val).html()
                       branch_id = $.grep(branch_id, function (value) {
                           return value != branchid;
                       });
                       $('#hbranchid').val(branch_id.toString());

                       sessionStorage.removeItem(val);
                       $('#t_' + val).remove();
                       toastr.success("Removed Successfully");

                   }
               });
           }
       });
}

// update lab hospital and branch mapping table
$('#Update_labservicemap_record').click(function () {
    debugger;

    var req_service = $('#req_service').val();
    var master_service_id = $('#Hmaster_service_id').val();
    var Servicecode = $('#Servicecode').val();
    var labservicemapid = $('#labservicemapid').val();
    if ($.trim((req_service)) == "") {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('#req_service').focus();
        return false;
    }
    var rowid = $('#rowidls').val();
    var val1 = 0;
    $('.number').each(function () {

        var value = parseInt($(this).data('id'));
        var master_service_id1 = $('#tmaster_service_id_' + value).html();
        if (master_service_id == master_service_id1) {
            val1 = 1;
        }
    });
    if (val1 == 1) {
        toastr.warning('Service Name already Exist');
        return false;
    }
    $('#treq_service_' + rowid).html(req_service);
    $('#tmaster_service_id_' + rowid).html(master_service_id);
    $('#tservicecode_' + rowid).html(Servicecode);
    $('#tlabservicemapid_' + rowid).val(labservicemapid);
    $('#req_service').val('');
    $('#Add_labservicemap_record').show();
    $('#Update_labservicemap_record').hide();


});

$("#Add_labservicemap_record").click(function () {
    debugger;
    var req_service = $('#req_service').val();
    var master_service_id = $('#Hmaster_service_id').val();
    var Servicecode = $('#Servicecode').val();
    var labservicemapid = $('#labservicemapid').val();
    var branch_service = $('#branch_addservice').val();
    var service_amount = $('#service_amt').val();

    if ($.trim((branch_service)) == "" || $.trim((branch_service)) == 0) {
        $('#Pbranch_addservice').show();
        $('#Pbranch_addservice').fadeOut(8000);
        $('#Pbranch_addservice').html('Select Service Name');
        $('#branch_addservice').focus();
        return false;
    }

    if ($.trim((req_service)) == "") {
        $('#Preq_service').show();
        $('#Preq_service').fadeOut(8000);
        $('#Preq_service').html('Select Service Name');
        $('#req_service').focus();
        return false;
    }

    if ($.trim((service_amount)) == "") {
        $('#Pservice_amt').show();
        $('#Pservice_amt').fadeOut(8000);
        $('#Pservice_amt').html('Enter Service Amount');
        $('#service_amt').focus();
        return false;
    }

    var labtranid = $('#labtranid_user_service').val();
    var Hservice_val = $('#Hserviceval').val();

    var service = {
        Dml_Indicator: 'ILS',
        master_user_service_id: master_service_id,
        labtranid: labtranid,
        created_by: $('#hiddenUser_id').val(),
        service_amount: service_amount,
        branch_id: $('#branch_addservice').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Master_Lab/Master_Lab_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (data1.data.Table[0].status == 'Already') {
                    toastr.warning("Service Already Mapped")
                    $('#req_service').val('');
                    return;
                }
                else if (data1.data.Table[0].status == 'Exceed') {
                    toastr.warning("Service amount exceed base service amount")
                    $('#service_amt').val('');
                    return;
                }
                else if (data1.data.Table[0].status == 'Success') {
                    toastr.success("Service Mapped Successfully")
                    return;
                }
                else {
                    console.log(data1.data.Table[0].status);
                }
                load_service(labtranid, $('#branch_addservice').val(), Hservice_val);
                $('#req_service').val('');
                $('#service_amt').val('');
            }
        }
    })
})

// delete hospital and branch mapping in lab
function labservicedelete(e, val, indicatorid) {
    debugger;
    var msg = '';
    var dttableremove = $('#maplabservicetable').DataTable();
    if (indicatorid == 1) {
        msg = 'Are You Sure, Do you want to Delete?'
    }
    else if (indicatorid == 'act_ser') {
        msg = 'Are You Sure, Do you want to Activate the service?'
    }
    else if (indicatorid == 'inact_ser') {
        msg = 'Are You Sure, Do you want to In-activate the service?'
    }
    else {
        console.log(indicatorid);
    }

    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>", msg,
       {

           closeButton: true,
           progressBar: true,
           allowHtml: true,
           timeOut: 20000000,

           onShown: function (toast) {
               $("#confirmationRevertYes").click(function () {
                   debugger;
                   var paraid = $("#tlabservicemapid_" + val + "").html();
                   var master_service_id = $("#tmaster_service_id_" + val + "").html();
                   var indicator_id = '';
                   if (indicatorid == 1) {
                       indicator_id = 'DLLS'
                   }
                   else {
                       indicator_id = indicatorid
                   }
                   if (paraid != "") {
                       var servicevalues = {
                           Dml_Indicator: indicator_id,
                           labtranid: paraid,
                           product_code: master_service_id
                       }
                       $.ajax({
                           async: true,
                           type: 'POST',
                           url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                           contentType: 'application/json; charset=UTF-8',
                           data: JSON.stringify(servicevalues),
                           success: function (data) {
                               debugger;
                               var data2 = JSON.parse(data);
                               if (jQuery.isEmptyObject((data2.data))) {

                               }
                               else {

                                   if (data2.msg == "Success") {
                                       data1 = data2.data;
                                       if (indicator_id == 'DLLS') {
                                           if (data1.Table[0].status == 'usermapped') {
                                               toastr.warning("Selected Service/Lab Service Provider is mapped with Some User. Unable to Delete")
                                               return false;
                                           }
                                           else {
                                               sessionStorage.removeItem(val);
                                               toastr.success("Removed Successfully");
                                               var removingRow = e.closest('tr');
                                               dttableremove.row(removingRow).remove().draw();
                                           }
                                       }
                                       else if (indicator_id == 'act_ser') {
                                           if (data1.Table[0].status == 'ser_activated') {
                                               toastr.success("Service Activated successfully")
                                               var labtranid = $('#labtranid_user_service').val()
                                               var val = $('#Hserviceval').val()
                                               // load_service(labtranid, '0', val)
                                               load_service(labtranid, $('#branch_addservice').val(), val)
                                               return false;
                                           }
                                           else {
                                               console.log(data1.Table[0].status);
                                           }
                                       }
                                       else if (indicator_id == 'inact_ser') {
                                           if (data1.Table[0].status == 'ser_inactivated') {
                                               toastr.success("Service In-activated successfully")
                                               var labtranid = $('#labtranid_user_service').val()
                                               var val = $('#Hserviceval').val()
                                               // load_service(labtranid, '0', val)
                                               load_service(labtranid, $('#branch_addservice').val(), val)
                                               return false;
                                           }
                                           else {
                                               var labservice_map_id = data1.Table[0].lab_service_mapid

                                               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>", 'Selected Service/Lab Service Provider is mapped with Some User. Do you want to continue to In-active the service?',
                                               {
                                                   closeButton: true,
                                                   progressBar: true,
                                                   allowHtml: true,
                                                   timeOut: 20000000,

                                                   onShown: function (toast) {
                                                       $("#confirmationRevertYes").click(function () {
                                                           debugger;
                                                           var servicevalues = {
                                                               Dml_Indicator: 'inc_ser',
                                                               labtranid: labservice_map_id,
                                                           }
                                                           $.ajax({
                                                               async: true,
                                                               type: 'POST',
                                                               url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                                                               contentType: 'application/json; charset=UTF-8',
                                                               data: JSON.stringify(servicevalues),
                                                               success: function (data) {
                                                                   var data1 = JSON.parse(data);
                                                                   if (jQuery.isEmptyObject((data1.data))) {

                                                                   }
                                                                   else {
                                                                       if (data1.msg == "Success") {
                                                                           data2 = data1.data;
                                                                           toastr.success("Service In-activated successfully")
                                                                           var labtranid = $('#labtranid_user_service').val()
                                                                           var val = $('#Hserviceval').val()
                                                                           load_service(labtranid, '0', val)
                                                                           return false;
                                                                       }
                                                                       else {
                                                                           console.log(data1.msg);
                                                                       }
                                                                   }
                                                               }
                                                           })
                                                       })
                                                   }
                                               });
                                           }
                                       }
                                       else {
                                           console.log(data1.Table[0].status);
                                       }
                                   }
                               }
                           }
                       });
                   }
                   else {
                       sessionStorage.removeItem(val);
                       var removingRow = e.closest('tr');
                       dttableremove.row(removingRow).remove().draw();
                       toastr.success("Removed Successfully");
                   }
               });
           }
       });
}

//load country
function loadcountry() {
    debugger;
    var country = {
        Dml_Indicator: "C"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#country').empty();
                    var Country;
                    //var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Country = Country + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#country').append(Country);
                    $('#country').change();
                }

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




//get state 
$('#country').on('change', function () {
    debugger;
    getstate();
});

function getstate(stateid) {
    debugger;
    var state = {
        country_id: $("#country").val(),
        Dml_Indicator: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var state;
                    $('#state').empty();
                    $('#city').empty();
                    //var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#state').append(state);
                    $('#state').change();
                    if (stateid != '' && stateid != undefined) {
                        $('#state').val(stateid);
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
$('#state').on('change', function () {
    getcity(0, 0);
})

function getcity(cityid, stateid1) {
    debugger;
    var stateid;
    if (stateid1 != 0) {
        stateid = stateid1;
    }
    else {
        stateid = $("#state").val();
    }
    var state = {
        state_id: stateid,
        Dml_Indicator: "CI"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var City;
                    $('#city').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#city').append(default_opt + City);
                    $('#city').val(cityid);

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

//load pin state
function loadpstate() {

    debugger;
    var state = {
        Dml_Indicator: "GS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/GetPincode/GetPincode',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var State;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        State = State + '<option value="' + emp.statename + '">' + emp.statename + '</option>';
                    });
                    $('#pstate').append(default_opt + State);
                }

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

$('#pstate').on('change', function () {
    getpincity();
})
function getpincity(cityid) {
    debugger;
    var City = {
        statename: $("#pstate").val(),
        Dml_Indicator: "GC"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/GetPincode/GetPincode',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(City),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var City;
                    $('#pcity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        City = City + '<option value="' + emp.Districtname + '">' + emp.Districtname + '</option>';
                    });
                    $('#pcity').append(default_opt + City);
                    $('#pcity').val(cityid);

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

// get pincode based on city
$('#pcity').on('change', function () {
    var val1 = $('#Hlistvalue').val();
    var labtranid = $('#Hlabtranid').val();
    load_pincode(labtranid, branch_id, val1, 'GP');
    debugger;
    ////$('#pincodebranch').hide();
    //var City = {
    //    statename: $("#pstate").val(),
    //    Districtname: $("#pcity").val(),
    //    Dml_Indicator: "GP"
    //}
    //$.ajax({
    //    async: true,
    //    type: 'POST',
    //    url: '/GetPincode/GetPincode',
    //    contentType: 'application/json; charset=UTF-8',
    //    data: JSON.stringify(City),
    //    success: function (data) {
    //        debugger;
    //        var data1 = JSON.parse(data);
    //        if (data1.msg == "Success") {
    //            var data1 = data1.data;
    //            if (jQuery.isEmptyObject((data1))) {
    //            }
    //            else {
    //                var tr1 = '', j = 0;
    //                $('#pincodetable_body').empty();
    //                $('#pincode_table_list').dataTable().fnClearTable();
    //                $('#pincode_table_list').dataTable().fnDraw();
    //                $('#pincode_table_list').dataTable().fnDestroy();
    //                $.each(data1.Table, function (i, emp) {

    //                    j++;

    //                    //tr1 = tr1 + '<tr id="t_' + emp.tranid + '"><td>' + j + '</td><td id="tranid_' + j + '"  hidden>' + emp.tranid + '</td><td id="branchid_pincode_' + j + '" hidden>' + emp.branchid + '</td><td id="branch_name_pincode_' + j + '" hidden>' + emp.branch_name + '</td><td><input type="checkbox" name="name_' + j + '" id="chk_' + j + '"  value=' + emp.pincode_id + ' data-id=' + emp.status + ' /></td><td id="officename_' + j + '">' + emp.officename + '</td><td id="pincode_' + j + '">' + emp.pincode + '</td></tr>';
    //                    tr1 = tr1 + '<tr id="t_' + emp.tranid + '"><td>' + j + '</td><td id="tranid_' + j + '"  hidden>' + emp.tranid + '</td><td><input type="checkbox" name="name_' + j + '" id="chk_' + j + '"  value=' + emp.pincode_id + ' data-id=' + emp.status + ' /></td><td id="officename_' + j + '">' + emp.officename + '</td><td id="pincode_' + j + '">' + emp.pincode + '</td></tr>';

    //                    //if (emp.pincode_id != null) {
    //                    //    //var d = $("#chk_1").val();
    //                    //    alert(emp.pincode_id);
    //                    //    //$("#chk_" + j + "").prop("checked", true);

    //                    //    //$("input[type=checkbox][value=6]").prop("checked",true);​
    //                    //    $("input[type=checkbox][value=113]").prop("checked", true);
    //                    //}
    //                });

    //                $('#pincodetable_body').html(tr1);
    //                // $('#pincode_table_list').DataTable();

    //                var tot_rowM = $('#pincode_table_list').DataTable().rows().count();
    //                var myTable = $('#pincode_table_list').dataTable();
    //                if (tot_rowM > 0) {

    //                    for (j = 1; j <= tot_rowM - 1; j++) {


    //                        var rowcollection = myTable.$("#chk_" + j + "", { "page": "all" });
    //                        var d = myTable.$("#chk_" + j + "", { "page": "all" }).val();
    //                        var status = myTable.$("#chk_" + j + "", { "page": "all" }).data('id');
    //                        if (d != null && status == 1) {
    //                            myTable.$("#chk_" + j + "", { "page": "all" }).prop("checked", true);
    //                        }

    //                    }
    //                }

    //                //$("input[type=checkbox][value="+emp.pincode_id+"]").prop("checked",true);​
    //            }
    //        }
    //        else {
    //            console.log(data1);
    //        }
    //    }
    //});
})

// load pin code
function load_pincode(labtranid, branch_id, val, indicator) {
    debugger;
    //var val1=$('#Hlistvalue').val(val);
    var flag_value = val;
    var City = {
        statename: $("#pstate").val(),
        Districtname: $("#pcity").val(),
        Dml_Indicator: indicator,
        lab_id: labtranid,
        branchid: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/GetPincode/GetPincode',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(City),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var tr1 = '', j = 0;
                    $('#pincodetable_body').empty();
                    $('#pincode_table_list').dataTable().fnClearTable();
                    $('#pincode_table_list').dataTable().fnDraw();
                    $('#pincode_table_list').dataTable().fnDestroy();
                    var checked = '', branch_name = '', state = '', district = '';
                    $.each(data1.Table, function (i, emp) {

                        if (emp.pincode_id != null && emp.status != 0) {
                            checked = 'Checked';
                        }
                        else {
                            checked = '';
                        }
                        if (emp.branch_name != null) {
                            state = emp.statename
                            district = emp.Districtname
                            branch_name = emp.branch_name
                        }
                        else {
                            state = $('#pstate').val();
                            district = $('#pcity').val();
                            branch_name = $('#branch_pincode option:selected').html();
                        }
                        j++;
                        if (flag_value == 'L2') {
                            $('#pincodebranch').addClass('hidden');
                            tr1 = tr1 + '<tr id="t_' + emp.tranid + '"><td>' + j + '</td><td id="tranid_' + j + '"  class="hidden">' + emp.tranid + '</td><td id="branchid_pincode_' + j + '" class="hidden">' + emp.branchid + '</td><td id="branch_name_pincode_' + j + '" class="hidden">' + branch_name + '</td><td><input type="checkbox"    ' + checked + '  name="name_' + j + '" id="chk_' + j + '"  value=' + emp.pincode_id + ' data-id=' + emp.status + ' /></td><td>' + state + '</td><td>' + district + '</td><td id="officename_' + j + '">' + emp.officename + '</td><td id="pincode_' + j + '">' + emp.pincode + '</td></tr>';
                        }
                        else {
                            $('#pincodebranch').removeClass('hidden');
                            tr1 = tr1 + '<tr id="t_' + emp.tranid + '"><td>' + j + '</td><td id="tranid_' + j + '"  class="hidden">' + emp.tranid + '</td><td id="branchid_pincode_' + j + '" class="hidden">' + emp.branchid + '</td><td id="branch_name_pincode_' + j + '">' + branch_name + '</td><td><input type="checkbox"    ' + checked + '  name="name_' + j + '" id="chk_' + j + '"  value=' + emp.pincode_id + ' data-id=' + emp.status + ' /></td><td>' + state + '</td><td>' + district + '</td><td id="officename_' + j + '">' + emp.officename + '</td><td id="pincode_' + j + '">' + emp.pincode + '</td></tr>';
                        }
                    });

                    $('#pincodetable_body').html(tr1);
                    var tot_rowM = $('#pincode_table_list').DataTable().rows().count();
                    var myTable = $('#pincode_table_list').dataTable();
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#btnsubmitpincode').click(function () {
    debugger;
    var branchpincode = $('#branch_pincode').val();

    if ($.trim((branchpincode)) == "" || $.trim((branchpincode)) == 0) {
        $('#Pbranch_pincode').show();
        $('#Pbranch_pincode').fadeOut(8000);
        $('#Pbranch_pincode').html('Select Service Name');
        $('#branch_pincode').focus();
        return false;
    }
    insertupdatelabpincode();
})

function insertupdatelabpincode() {

    debugger;
    var customers = new Array();
    var tot_rowM = $('#pincode_table_list').DataTable().rows().count();
    var myTable = $('#pincode_table_list').dataTable();
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var customer = {};
            var rowcollection = myTable.$("#chk_" + j + "", { "page": "all" });
            //if ($('#chk_' + j + ' .select :checked') == true)
            // var checkBox = document.getElementById("chk_"+j+"",{ "page": "all" });
            if (rowcollection[0].checked == true) {

                customer.pincode_id = (myTable.$("#chk_" + j + "", { "page": "all" }).val() == 'null') ? 0 : myTable.$("#chk_" + j + "", { "page": "all" }).val();
                customer.tranid = myTable.$("#tranid_" + j + "", { "page": "all" }).html();
                customer.pincode = myTable.$('#pincode_' + j + '', { "page": "all" }).html();
                customer.place = myTable.$('#officename_' + j + '', { "page": "all" }).html();
                customer.status = 1
                // branchid: myTable.$('#branchid_pincode_' + j + '', { "page": "all" }).html();
                customers.push(customer);
            }
            if (rowcollection[0].checked == false && myTable.$("#chk_" + j + "", { "page": "all" }).val() != 'null') {

                customer.pincode_id = (myTable.$("#chk_" + j + "", { "page": "all" }).val() == 'null') ? 0 : myTable.$("#chk_" + j + "", { "page": "all" }).val();
                customer.tranid = myTable.$("#tranid_" + j + "", { "page": "all" }).html();
                customer.pincode = myTable.$('#pincode_' + j + '', { "page": "all" }).html();
                customer.place = myTable.$('#officename_' + j + '', { "page": "all" }).html();
                customer.status = 0
                // branchid: myTable.$('#branchid_pincode_' + j + '', { "page": "all" }).html();
                customers.push(customer);
            }
        }
        values = {
            xmldata: customers,
            created_by: $('#hiddenUser_id').val(),
            Dml_Indicator: 'IPIN',
            labid: $('#labid').val(),
            branchid: $('#branch_pincode').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Master_Lab/Master_Lab_Ins_upd_sel_Pincode',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(values),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {

                    toastr.success('Pincode Added Successfully');
                }
            }
        });
    }
}

$('#is_externallab').change(function () {
    debugger;
    refereshform()
    if ($('#hiddenRole_id').val() != 2) {
        $('#branchname').val($('#HospitalBranchID').val());
    }

    if ($('#is_externallab').val() == 0) {

        $('#service_lab').removeClass('hidden')
        $('#lab_license').addClass('hidden')
        $('#lab_image').addClass('hidden')
        $('#contact_person').removeClass('hidden')
        $('#mobile_no').removeClass('hidden')
        $('#emailid').removeClass('hidden')
        $('#islab').removeClass('hidden')
        // $('#pincode').removeClass('hidden')
        $('#description').removeClass('hidden')

        $('#header_title').html('Lab Details')
        $('#Details').html('Lab Details')
        $('#spln').html('Lab Name');
        $('#sldescription').html('Lab Description');
        $('#address_detail').html('Lab Address Details')
    }
    else {

        $('#service_lab').removeClass('hidden')
        $('#lab_license').removeClass('hidden')
        $('#lab_image').removeClass('hidden')
        $('#contact_person').removeClass('hidden')
        $('#mobile_no').removeClass('hidden')
        $('#emailid').removeClass('hidden')
        $('#islab').removeClass('hidden')
        //$('#pincode').removeClass('hidden')
        $('#description').removeClass('hidden')

        $('#header_title').html('Service Provider Details')
        $('#Details').html('Service Provider Details')
        $('#spln').html('Service Provider Name');
        $('#sldescription').html('Service Provider Description');
        $('#address_detail').html('Service Provider address Details')
    }
})

//update user mapping
$('#Update_usermap_record').click(function () {
    debugger;

    var user_service = $('#user_service').val();
    var doctor_user_id = $('#user_id').val();
    var user_code = $('#usercode').val();
    if ($.trim((user_service)) == "") {
        $('#Preq_user').show();
        $('#Preq_user').fadeOut(8000);
        $('#Preq_user').html('Select User Name');
        $('#req_user').focus();
        return false;
    }
    var rowid = $('#rowidls').val();
    var val1 = 0;
    $('.number').each(function () {

        var value = parseInt($(this).data('id'));
        var doctor_user_id1 = $('#tdoctoruserid_' + value).html();
        if (doctor_user_id == doctor_user_id1) {
            val1 = 1;
        }
    });
    if (val1 == 1) {
        toastr.warning('User Name already Exist');
        return false;
    }
    $('#tuser_service_' + rowid).html(user_service);
    $('#tuser_code_' + rowid).html(user_code);
    $('#tdoctoruserid_' + rowid).html(doctor_user_id);
    $('#user_service').val('');
    $('#user_id').val('');
    $('#usercode').val('');
    $('#Add_usermap_record').show();
    $('#Update_usermap_record').hide();
});

//insert user
$("#Add_usermap_record").click(function () {
    debugger;

    var user_service = $('#user_service').val();
    var doctor_user_id = $('#user_id').val();
    var user_code = $('#usercode').val();
    var branch_user = $('#branch_adduser').val();

    if ($.trim((branch_user)) == "" || $.trim((branch_user)) == 0) {
        $('#Pbranch_adduser').show();
        $('#Pbranch_adduser').fadeOut(8000);
        $('#Pbranch_adduser').html('Select User Name');
        $('#Pbranch_adduser').focus();
        return false;
    }

    if ($.trim((user_service)) == "") {
        $('#Preq_user').show();
        $('#Preq_user').fadeOut(8000);
        $('#Preq_user').html('Select User Name');
        $('#user_service').focus();
        return false;
    }
    var labtranid = $('#labtranid_user_service').val();
    var Huser_val = $('#Huserval').val()
    var users = {
        Dml_Indicator: 'ILU',
        labtranid: labtranid,
        service_name: user_service,
        service_code: user_code,
        master_user_service_id: doctor_user_id,
        created_by: $('#hiddenUser_id').val(),
        branch_id: branch_user
    }

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

                if (data1.data.Table[0].status == 'mapped') {
                    toastr.warning("User already mapped. Unable to Add");
                    $('#user_service').val('');
                    return;
                }
                else if (data1.data.Table[0].status == 'updated') {
                    toastr.success("User Mapped successfully");
                    $('#user_service').val('');
                    $('#user_id').val('');
                    $('#usercode').val('');
                    load_user(labtranid, $('#branch_adduser').val(), Huser_val)
                    return;
                }
                else if (data1.data.Table[0].status == 'exists') {
                    toastr.warning("User already exists");
                    $('#user_service').val('');
                    return;
                }
                else {
                    console.log(data1.data.Table[0].status)
                }
            }
        }
    });
})

//lab user delete
function labuserdelete(e, val, doctor_user_id, branch_id) {
    debugger;
    var dttableremove = $('#maplabusertable').DataTable();
    var doctor_userid = doctor_user_id;
    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>", 'Are You Sure, You Want to Delete this User?',
   {
       closeButton: true,
       progressBar: true,
       allowHtml: true,
       timeOut: 20000000,

       onShown: function (toast) {

           $("#confirmationRevertYes").click(function () {
               debugger;
               var line_delete = {
                   Dml_Indicator: "DLU",
                   lab_id: doctor_user_id,
                   branch_id: branch_id
               }
               if (doctor_userid != 'doctor_user_id') {
                   $.ajax({
                       async: true,
                       type: 'POST',
                       url: '/Master_Lab/Master_Lab_Ins_upd_sel',
                       contentType: 'application/json; charset=UTF-8',
                       data: JSON.stringify(line_delete),
                       success: function (data) {
                           debugger;
                           var data1 = JSON.parse(data);
                           if (jQuery.isEmptyObject((data1.data))) {
                           }
                           else {
                               //if (data.msg == "Success") {
                               var status = data1.data.Table[0].status
                               if (status == 'usermapped') {
                                   toastr.warning("User Mapped Already. Unable to Delete");
                                   return;
                               }
                               else {
                                   toastr.success("Deleted successfully");
                                   var removingRow = e.closest('tr');
                                   dttableremove.row(removingRow).remove().draw();
                               }
                               //}
                           }
                       }
                   });
               }
               else {
                   var removingRow = e.closest('tr');
                   dttableremove.row(removingRow).remove().draw();
                   //$('#ts_' + val).remove();
                   toastr.success("Removed Successfully");
               }
           })
       }
   });
}