$(document).ready(function () {
    $('#btnUpdate').hide();
    //  $('#div_TPA').hide();
    $('#div_TPA').addClass('hidden');

    $('#btnentity_submit').html('Submit');
    CheckCodeTemplate()
  
   // LoadBranch(); //one master concept
    // loadcountry();
    //entity_table(); 
   
});

//$('#branch_id').change(function () {
//    debugger;
//    entity_table();
//});
//$('#entity_type_filter').change(function () {
//    debugger;
//    entity_table();
//});
//$('#status_filter').change(function () {
//    debugger;
//    entity_table();
//});

//Calls the file Upload function 
var PayerDocumentsCount = 0;
$('#fileToUpload').change(function () {
    PayerDocumentsCount = PayerDocumentsCount + 1;
    if (PayerDocumentsCount <= 5) {
        packageimageupload();
    }
    else {
        $('#PPayerDocumentsCount').show();
        $('#PPayerDocumentsCount').fadeOut(8000);
        $('#PPayerDocumentsCount').html('You cannot upload more than 5 documents.');
        $('#fileToUpload').val('');
        $('#fileToUpload').focus();
        return false;
    }
});

//Filter
$('#btnfilter').click(function () {
    debugger;
    entity_table();
})



//Clear filter
$('#btnclear').click(function () {
    debugger;
    // $('#branch_id').val(0) //one master concept
    $('#entity_type_filter').val(0)
    $('#status_filter').val(0)
    entity_table();
    //LoadBranch(); //one master concept
})

//CheckCodeTemplate
function CheckCodeTemplate() {
    debugger;
    var codeData = {
        //Dml_Indicator: "CT",
        Dml_Indicator: "BCT",
        hospital_id: $('#HospitalId').val(),
       // branch_id: $('#pkg_branch_id').val() //one master concept
        //branch_id: $('#HospitalBranchID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            debugger;

            var data1 = JSON.parse(data)
            data1 = data1.data;

            if (data1[0].count1 == 0) {
                //alert('' + $('#SelBranch  option:selected').html() + ' Not Added Code Template. Please Add the Code Template at SetupIds');
                alert('Not Added Code Template. Please Add the Code Template at SetupIds');

                window.location.href = "/Hospitalsetup"
            }
            //else {
            //    LoadBranch()
            //}
            else {
                entity_table()
            }


        }
    });
}

//To Show the list of Entities in a Table
function entity_table() {
    debugger;
    $('#shade_slot').show();

    var branchid = '';
    //one master concept
    //if ($('#branch_id').val() != 0 && $('#branch_id').val()!=null)
    //{
    //    branchid = $('#branch_id').val();
    //}
    //else
    //{
    //    branchid = $('#HospitalBranchID').val();
    //}

    var entity_table_data = {
        Dml_Indicator: "L",
        //branch_id: $('#branch_id').val(),
      //  branch_id: branchid, //one master concept
        entity_type: $('#entity_type_filter').val(),
        billing_type: $('#status_filter').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(entity_table_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var c = data1.data
                    $('#entity_table').empty();
                    $('#enitity').dataTable().fnClearTable();
                    $('#enitity').dataTable().fnDestroy();

                    tr = '';
                    var j = 0;
                    if (c.length > 0) {
                        for (var i = 0; i < c.length; i++) {
                            j++;
                            var entitytype = c[i].entity_type;
                            if (entitytype == 1) {
                                var entity_type_name = "Insurance"
                            }
                            else {
                                var entity_type_name = "Corporate"
                            }
                            var documents_file = c[i].payer_document_file_path;
                            const documentation = [];
                            console.log(documents_file);
                            if (documents_file !== null) {
                                var payer_documentation = c[i].payer_document_file_path;
                                var payer_documentation_split = payer_documentation.split(',');
                                for (var k = 0; k < payer_documentation_split.length; k++) {
                                    //var payer_documentation_file = '<a class="edit link-btn" onclick=id_image_show("' + payer_documentation_split[k] + '","' + c[i].branch_id + '")>Doc' + (k + 1) + '</button>' //one master concept
                                    var payer_documentation_file = '<a class="edit link-btn" onclick=id_image_show("' + payer_documentation_split[k] + '")>Doc' + (k + 1) + '</button>'

                                    documentation.push(payer_documentation_file);
                                }
                            }
                            else {
                                const documentation = "-"
                            }

                            var status = c[i].is_active;
                            var active_inactive = '';
                            if (status == 1) {
                                active_inactive = '<span class="label label-success">Active</span>';
                            }
                            else if (status == 2) {
                                active_inactive = '<span class="label label-warning">Inactive</span>';
                            }

                            if (status == 2) {
                                //del = '<a class="btn btn-delete btn-xs" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'del\')"><i class="fa fa-trash-o"></i></a>'
                                //activeinactive = '<p><a class="btn btn-xs btn-blue" title="Make Active!" data-toggle="tooltip" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'active\')"><i class="fa fa-check-square-o mr-5"></i>Active</a></p>'
                                //managebillinggrade = '<a class="btn btn-xs btn_r btn-blue" data-id="EM_F1" data-type="role_rights_function" data-nav="popup" data-name="manage_billing_grade"  data-toggle="modal"  onclick="manage_billing_grade(\'' + c[i].entity_code + '\',\'' + c[i].entity_name + '\',\'' + c[i].payer_id + '\',\'' + c[i].master_entity_id + '\',\'' + c[i].branch_id + '\',' + c[i].entity_type + ',1,' + c[i].is_schem + ')" href=""><i class="	fa fa-file-text mr-5"></i>Manage Billing Grade</a>'
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots 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">' + activeinactive + '' + managebillinggrade + '</div></div></div></div>'

                                del = '<a class="delete_icon" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'del\')"><i class="fa fa-trash-o"></i></a>'
                                activeinactive = '<a class="active_icon" title="Make Active!" data-toggle="tooltip" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'active\')"><i class="fa fa-check-square-o mr-5"></i></a>'
                                managebillinggrade = '<a class="btn_r3" title="Manage Billing Grade" data-id="EM_F1" data-type="role_rights_function" data-nav="popup" data-name="manage_billing_grade"  data-toggle="modal"  onclick="manage_billing_grade(\'' + c[i].entity_code + '\',\'' + c[i].entity_name + '\',\'' + c[i].payer_id + '\',\'' + c[i].master_entity_id + '\',\'' + c[i].branch_id + '\',' + c[i].entity_type + ',1,' + c[i].is_schem + ')" href=""></i>Manage Billing Grade</a>'
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + del + '</li><li>' + activeinactive + '</li></div><li>' + managebillinggrade + '</li></ul></div>';
                            }
                            else {
                                //edit = '<a class="btn btn-edit btn-xs" data-id="EM_E1" data-type="role_rights_edit" data-nav="" data-name="" onclick="entity_edit(\'' + c[i].master_entity_id + '\',this)"><i class="fa fa-pencil"></i></a>'
                                //del = '<a class="btn btn-delete btn-xs" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'del\')"><i class="fa fa-trash-o"></i></a>'
                                //activeinactive = '<p><a class="btn btn-xs btn-blue" title="Make in Active!" data-toggle="tooltip" data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'inactive\')"><i class="fa fa-minus-square-o mr-5"></i>In Active</a></p>'
                                //managebillinggrade = '<a class="btn btn-xs btn_r btn-blue" data-id="EM_F1" data-type="role_rights_function" data-nav="popup" data-name="manage_billing_grade"  data-toggle="modal"  onclick="manage_billing_grade(\'' + c[i].entity_code + '\',\'' + c[i].entity_name + '\',\'' + c[i].payer_id + '\',\'' + c[i].master_entity_id + '\',\'' + c[i].branch_id + '\',' + c[i].entity_type + ',1,' + c[i].is_schem + ')" href=""><i class="	fa fa-file-text mr-5"></i>Manage Billing Grade</a>'
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if"> ' + edit + '' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots 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">' + activeinactive + '' + managebillinggrade + '</div></div></div></div>'
                                edit = '<a class="edit_icon" data-id="EM_E1" title="Edit" data-type="role_rights_edit" data-nav="" data-name="" onclick="entity_edit(\'' + c[i].master_entity_id + '\',this)"><i class="fa fa-pencil"></i></a>'
                                del = '<a class="delete_icon" data-id="EM_D1" title="Delete" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'del\')"><i class="fa fa-trash-o"></i></a>'
                                activeinactive = '<a class="inactive_icon" title="Make in Active!"  data-id="EM_D1" data-type="role_rights_delete" data-nav="" data-name="" onclick="act_inact_del(\'' + c[i].master_entity_id + '\',this,\'inactive\')"><i class="fa fa-minus-square-o"></i></a>'
                                managebillinggrade = '<a class="btn_r" title="Manage Billing Grade" data-id="EM_F1" data-type="role_rights_function" data-nav="popup" data-name="manage_billing_grade"  data-toggle="modal"  onclick="manage_billing_grade(\'' + c[i].entity_code + '\',\'' + c[i].entity_name + '\',\'' + c[i].payer_id + '\',\'' + c[i].master_entity_id + '\',\'' + c[i].branch_id + '\',' + c[i].entity_type + ',1,' + c[i].is_schem + ')" href="">Manage Billing Grade</a>'
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li><li>' + activeinactive + '</li></div><li>' + managebillinggrade + '</li></ul></div>';
                            }

                            tr = tr + '<tr><td>' + j + '</td><td>' + c[i].entity_code + '</td><td>' + c[i].entity_name + '</td><td>' + c[i].payer_id + '</td><td>' + entity_type_name + '</td><td>' + c[i].email_id + '</td><td>' + documentation + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';
                        }
                        $('#shade_slot').hide();
                        $('#entity_table').append(tr);
                        datatable('enitity', 'Partners', 'Legal');
                    }
                    else {
                      // var tr1 = '<tr><td colspan="7"><div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" ></div></td></tr>';
                        $('#shade_slot').hide();
                        $('#entity_table').append();
                        datatable('enitity', 'Partners');
                     // $('#entity_table').append(tr1);
                    }

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

//Activate the Entity available in the Table
function entity_activate(code, event) {
    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") {
             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 {
                     toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Do you want to activate this Partner?',
                  {
                      closeButton: true,
                      progressBar: true,
                      allowHtml: true,
                      timeOut: 20000000,

                      onShown: function (toast) {
                          $("#confirmationRevertYes").click(function () {
                              activate_entity(code);
                          })
                          $("#confirmationRevertNo").click(function () {

                          })

                      }
                  })
                 }
             }
         }
     })




}

function activate_entity(code) {
    var activate_data = {
        Dml_Indicator: "EA",
        master_entity_id: code
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    //alert(data1.data[0].StringResult)
                    entity_table()
                }
            }
            else {
                console.log(data1)
            }
        }
    });
}
//Deactivate the Entity available in the Table
function entity_deactivate(code, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    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 {
                     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) {
                            debugger;
                            $("#confirmationRevertYes").click(function () {
                                del_entity(code);
                            })
                            $("#confirmationRevertNo").click(function () {

                            })
                        }
                    })
                 }
             }
         }
     });


}

//website link check
function ISValidLink(url) {
    debugger;
    //var Link = url;
    //if (/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(Link)) {
    //    return 1;
    //} else {
    //    return 0;
    //}

    var Link = url;
    if (/^(https|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url)) {
        return 1;
    } else {
        return 0;
    }
}


function del_entity(code) {
    var deactivate_data = {
        Dml_Indicator: "DT",
        master_entity_id: code
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(deactivate_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {

                    if (data1.data[0].StringResult == "EntityActive") {
                        toastr.warning('Selected Partner is already used in IP Management. Unable to Delete the Partner',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    }
                    else {
                        // alert(data1.data[0].StringResult)
                        entity_table();
                    }


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




//Add the billing to the respected entity(Mapping Entity and Billing)
function manage_billing_grade(code, name, payer_code, master_entity_id, branchid, entity_type, id1, is_shcem_val) {
    debugger;
    if (id1 == '1') {
        LoadBillingClass(branchid, is_shcem_val);
    }
    if (entity_type == 1) {
        if (id1 == '1') {
            var load = Loadcorporate(branchid);
            $.when(load)
            .then(function (data) {
                load_billing_table(code, name, payer_code, master_entity_id, branchid, entity_type)
            })
        }
        else {
            load_billing_table(code, name, payer_code, master_entity_id, branchid, entity_type)
        }
        $('#div_corporate').removeClass('hidden');
    }
    else {
        load_billing_table(code, name, payer_code, master_entity_id, branchid, entity_type)
        $('#div_corporate').addClass('hidden');
    }
    $('#btnSubmit1').show();
    $('#btnUpdate').hide();
    debugger;
    $('#entity_name_show').val(name);
    $('#payer_code_show').val(payer_code);
    $('#entity_code').val(code);
    $('#entity_master_id').val(master_entity_id);
    $('#Hentity_type').val(entity_type);
    $('#Hbranch_id').val(branchid);
    $('#entity_type').val(entity_type);
    $('#IS_SCHEM').val(is_shcem_val);

}
function load_billing_table(code, name, payer_code, master_entity_id, branchid, entity_type) {
    var manage_data = {
        Dml_Indicator: "MBL",
        master_entity_id: master_entity_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(manage_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    debugger;
                    var c = data1.data

                    $('#manage_billing_grade_table').empty();
                    tr = '';
                    var j = 0;
                    for (var i = 0; i < c.length; i++) {
                        j++;
                        var billingtype = c[i].billing_type
                        var status = c[i].status;
                        var corporate = '';
                        var arr = [];
                        if (c[i].corporate_id != null) {
                            corporate = c[i].corporate_id;
                            corporate1 = c[i].corporate_id.split(',');

                            for (var k = 0; k < corporate1.length; k++) {
                                arr[k] = $("#Sel_corporate option[value='" + $.trim(corporate1[k]) + "']").text();
                            }
                        }
                        var btnhide = '';
                        if (entity_type == 2) {
                            btnhide = 'style="display:none";';
                            $('#th_corporate').hide();
                        }
                        else {
                            $('#th_corporate').show();
                        }
                        arr = arr.toString();
                        if (status == 1) {
                            tr = tr + '<tr><td>' + j + '</td><td style="display:none;">' + c[i].billing_type + '</td><td>' + c[i].master_service_name + '</td><td>' + payer_code + '</td><td>' + c[i].valid_from + '</td><td>' + c[i].valid_upto + '</td><td ' + btnhide + '>' + arr + '</td><td><a class="btn btn-primaryuse btn-xs" onclick="manage_billing_edit(\'' + c[i].master_entity_billing_id + '\',\'' + c[i].billing_type + '\',\'' + c[i].valid_from + '\',\'' + c[i].valid_upto + '\',\'' + c[i].admitted_entity + '\',\'' + corporate + '\')"><i class="fa fa-edit" aria-hidden="true"></i></a> &nbsp; <a class="btn btn-danger btn-xs" onclick="manage_billing_deactivate(\'' + c[i].master_entity_billing_id + '\')"><i class="far fa-trash-alt" aria-hidden="true"></i></a></td></tr>';
                        }
                        else {
                            tr = tr + '<tr><td>' + j + '</td><td style="display:none;">' + c[i].billing_type + '</td><td>' + c[i].master_service_name + '</td><td>' + payer_code + '</td><td>' + c[i].valid_from + '</td><td>' + c[i].valid_upto + '</td><td ' + btnhide + '>' + arr + '</td><td><a class="btn btn-submit btn-xs"  onclick="manage_billing_activate(\'' + c[i].master_entity_billing_id + '\',\'' + c[i].billing_type + '\',\'' + c[i].valid_from + '\',\'' + c[i].valid_upto + '\',\'' + c[i].admitted_entity + '\',\'' + corporate + '\')">Activate</a></td></tr>';
                        }

                    }
                    $('#manage_billing_grade_table').html(tr);

                }
            }
            else {
                console.log(data1)
            }

        }
    });
}

//For activating the billing class
function manage_billing_activate(billing_id) {
    var activate_data = {
        Dml_Indicator: "MBA",
        entity_billing_id: billing_id,
        entity_code: $('#entity_code').val(),
        master_entity_id: $('#entity_master_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {

                    if (data1.data[0].StringResult == "AdmitActiveEntity") {
                        toastr.warning('Selected Partner is already used in IP Management. Unable to Activate the Billing Grade.',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    }
                    else {
                        //alert(data1.data[0].StringResult)
                        manage_billing_grade($('#entity_code').val(), $('#entity_name_show').val(), $('#payer_code_show').val(), $('#entity_master_id').val(), $('#Hbranch_id').val(), $('#Hentity_type').val(), 2)
                    }
                }
            }
            else {
                console.log(data1)
            }
        }
    });
}

//Deactivates the billing class

function manage_billing_deactivate(billing_id) {
    var activate_data = {
        Dml_Indicator: "MBD",
        entity_billing_id: billing_id,
        entity_code: $('#entity_code').val(),
        master_entity_id: $('#entity_master_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {

                    if (data1.data[0].StringResult == "AdmitActiveEntity") {
                        toastr.warning('Selected Partner is already used in IP Management. Unable to Delete the Billing Grade.',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    }
                    else {
                        //alert(data1.data[0].StringResult)
                        manage_billing_grade($('#entity_code').val(), $('#entity_name_show').val(), $('#payer_code_show').val(), $('#entity_master_id').val(), '', $('#Hentity_type').val(), 2)
                    }


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



//Loads the list of countries
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);
            console.log(data1)
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    $('#txtCountry').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>';
                    });
                    $('#txtCountry').append(Country);
                    //load_state();
                    $("#txtCountry").change();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

//loads the state based on the country
$("#txtCountry").change(function () {
    var state = {
        country_id: $("#txtCountry").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) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var state;
                    $('#txtState').empty();
                    $('#txtCity').empty();
                    //var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtState').append(state);
                    $("#txtState").change();
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});

//load state and defaultly selected to tamil nadu
function load_state() {
    var state = {
        country_id: $("#txtCountry").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) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var state;
                    $('#txtState').empty();
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtState').append(default_opt + state);
                    //$('#txtState').val('35');
                    load_city();
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

//loads the city based on the state
$("#txtState").change(function () {
    var state = {
        state_id: $("#txtState").val(),
        Dml_Indicator: "CI"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

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

                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtCity').append(default_opt + City);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});

//loads the city
function load_city() {
    var state = {
        state_id: $("#txtState").val(),
        Dml_Indicator: "CI"
    }

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

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtCity').append(default_opt + City);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

//checks whether is insert or update
function entity_insert_update() {
    debugger;
    //if ($.trim($('#pkg_branch_id').val()) == "" || $('#pkg_branch_id').val() == '0') { //one master concept
    //    $('#spanpkg_branch_id').show();
    //    $('#spanpkg_branch_id').fadeOut(8000);
    //    $('#spanpkg_branch_id').html('Select Branch');
    //    $('#pkg_branch_id').focus();
    //    $('#pkg_branch_id').val('');
    //    return false;
    //}

    if ($.trim($('#entity_name').val()) == "") {
        $('#Pentity_name').show();
        $('#Pentity_name').fadeOut(8000);
        $('#Pentity_name').html('Enter Entity Name');
        $('#entity_name').focus();
        $('#entity_name').val('');
        return false;
    }
    if ($.trim($('#payer_id').val()) == "") {
        $('#payer_id').show();
        $('#Ppayer_id').fadeOut(8000);
        $('#Ppayer_id').html('Enter the Payer Code');
        $('#payer_id').focus();
        $('#payer_id').val('');
        return false;
    }
    if ($.trim($('#entity_type').val()) == 0) {
        $('#Pentity_type').show();
        $('#Pentity_type').fadeOut(8000);
        $('#Pentity_type').html('Choose an Entity Type');
        $('#entity_type').focus();
        $('#entity_type').val('');
        return false;
    }

    if ($.trim($('#entity_type').val()) == 1) {
        if ($.trim($('#IS_SCHEM').val()) == "") {
            $('#PIS_SCHEM').show();
            $('#PIS_SCHEM').fadeOut(8000);
            $('#PIS_SCHEM').html('Scheme is Mandatory');
            $('#IS_SCHEM').focus();
            $('#IS_SCHEM').val('');
            return false;

        }
    }


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

    //if ($.trim($('#txtarea').val()) == "") {
    //    $('#Ptxtarea').show();
    //    $('#Ptxtarea').fadeOut(8000);
    //    $('#Ptxtarea').html('Enter the Area');
    //    $('#txtarea').focus();
    //    $('#txtarea').val('');
    //    return false;
    //}

    if ($.trim($('#txtCountry').val()) == 0) {
        $('#PtxtCountry').show();
        $('#PtxtCountry').fadeOut(8000);
        $('#PtxtCountry').html('Select Country');
        $('#txtCountry').focus();
        $('#txtCountry').val('');
        return false;
    }
    if ($.trim($('#txtState').val()) == 0) {
        $('#PtxtState').show();
        $('#PtxtState').fadeOut(8000);
        $('#PtxtState').html('Select State');
        $('#txtState').focus();
        $('#txtState').val('');
        return false;
    }
    if ($.trim($('#txtCity').val()) == 0) {
        $('#PtxtCity').show();
        $('#PtxtCity').fadeOut(8000);
        $('#PtxtCity').html('Select City');
        $('#txtCity').focus();
        $('#txtCity').val('');
        return false;
    }

    if ($.trim($('#pin_code').val())=='' || $.trim($('#pin_code').val()) == 0) {
        $('#Ppin_code').show();
        $('#Ppin_code').fadeOut(8000);
        $('#Ppin_code').html('Enter the Pin Code');
        $('#pin_code').focus();
        $('#pin_code').val('');
        return false;
    }

    if ($.trim($('#emailid').val()) == "") {
        $('#Pemailid').show();
        $('#Pemailid').fadeOut(8000);
        $('#Pemailid').html('Enter Email ID');
        $('#emailid').focus();
        $('#emailid').val('');
        return false;
    }

    if ($.trim($('#website').val()) == "") {
        $('#Pwebsite').show();
        $('#Pwebsite').fadeOut(8000);
        $('#Pwebsite').html('Enter Website Details');
        $('#website').focus();
        $('#website').val('');
        return false;
    }

    if ($.trim($('#website').val()) != '') {
        var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
        var regex = new RegExp(expression);
        var urlval = $('#website').val();

        if (!(urlval.match(regex))) {
            $('#Pwebsite').show();
            $('#Pwebsite').fadeOut(8000);
            $('#Pwebsite').html('Enter Valid Website link');
            $('#website').val('');
            $('#website').focus();
            return false;
        }

        //commented by nandhini
        //if (ISValidLink($('#website').val()) == 0) {
        //    $('#Pwebsite').show();
        //    $('#Pwebsite').fadeOut(8000);
        //    $('#Pwebsite').html('Enter Valid Website link');
        //    $('#website').val('');
        //    $('#website').focus();
        //    return false;
        //}
    }

    $('#shade_slot_submit').show();
    $("#entity_type").removeClass('disabled');
    if (($('#btnentity_submit').html()) == 'Submit') {
        entity_insert();
    }
    else {
        entity_update();
    }

}

//Inserts and edit the entity Details
function entity_insert() {
    debugger;

    var entity_data = {
        Dml_Indicator: "I",
        entity_name: $("#entity_name").val(),
        payer_id: $("#payer_id").val(),
        entity_type: $("#entity_type").val(),
        address_line1: $("#address_line1").val(),
        address_line2: $("#address_line2").val(),
        country: $("#txtCountry").val(),
        state: $("#txtState").val(),
        city: $("#txtCity").val(),
        pin_code: $('#pin_code').val(),
        area: $("#txtarea").val(),
        emailid: $("#emailid").val(),
        website: $("#website").val(),
        is_schem: $("#IS_SCHEM").val(),
      //  branch_id: $('#pkg_branch_id').val(), //one master concept
        tpa_id: $('#entity_TPA').val().toString()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(entity_data),
        success: function (data) {
            $('#shade_slot_submit').hide();
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    if (data1.data[0].StringResult == "already") {
                        $('#Pentity_name').show();
                        $('#Pentity_name').fadeOut(8000);
                        $('#Pentity_name').html('Entity Name already exists');
                        $('#entity_name').focus();
                        $('#entity_name').val('');
                        return false;

                    }
                    else {

                        toastr.success('Added Successfully',
                            {
                                closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            })

                        setTimeout(function () {
                            var entitycode = data1.data[0].StringResult
                            var masterentitycode = data1.data[0].master_entity_id;
                            entity_documents_insert(entitycode, masterentitycode);
                        }, 1000);
                    }

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


//Inserts the entity related documents
function entity_documents_insert(entitycode, masterentitycode) {
    debugger;
    if ($('#docpathvalue').val() != '' && $('#docpathvalue').val() != null) {
        var documentpath = $('#docpathvalue').val();
        var documentArray = documentpath.split(',');
        var j = 0;
        console.log(documentArray);
        if (documentArray.length > 0) {
            for (var i = 0; i < documentArray.length; i++) {
                if (documentArray[i] != "" && documentArray[i] != null) {
                    var entity_documents_data = {
                        Dml_Indicator: 'EDI',
                        entity_code: entitycode,
                        payer_documentation: documentArray[i],
                        master_entity_id: masterentitycode
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/BillingMaster/entitymaster_creation_mapping',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(entity_documents_data),
                        success: function (data) {
                            console.log(data);
                            var data1 = JSON.parse(data);
                            if (data1.msg == "Success") {
                                j++;
                                if (j == documentArray.length) {
                                    $("#entity_name").val(''),
                                    $("#payer_id").val(''),
                                    $("#entity_type").val(''),
                                    $("#address_line1").val(''),
                                    $("#address_line2").val(''),
                                    $("#txtCountry").val(''),
                                    $("#txtState").val(''),
                                    $("#txtCity").val(''),
                                    $("#txtarea").val(''),
                                    $("#emailid").val(''),
                                    $("#website").val(''),
                                    $("#IS_SCHEM").val(''),
                                    $("#address_id").val(''),
                                    $("#entity_code").val(''),
                                    $("#photolog").val(''),
                                    $('#btnentity_submit').html('Submit');
                                    //entity_table();
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                            }
                            else {
                                console.log(data1);
                            }
                        }
                    });
                }
            }
        }

        $("#entity_name").val(''),
            $("#payer_id").val(''),
            $("#entity_type").val(''),
            $("#address_line1").val(''),
            $("#address_line2").val(''),
            $("#txtCountry").val(''),
            $("#txtState").val(''),
            $("#txtCity").val(''),
            $("#txtarea").val(''),
            $("#emailid").val(''),
            $("#website").val(''),
            $("#IS_SCHEM").val(''),
            $("#address_id").val(''),
            $("#entity_code").val(''),
            $("#photolog").val(''),
            $('#btnentity_submit').html('Submit');

        setTimeout(function () {
            location.reload();
        }, 2000);
    }
    else {

        setTimeout(function () {
            location.reload();
        }, 2000);
    }

}





//Updates the entity details
function entity_update() {

    debugger;

    var entity_data = {
        Dml_Indicator: "ETU",
        entity_name: $("#entity_name").val(),
        payer_id: $("#payer_id").val(),
        entity_type: $("#entity_type").val(),
        address_line1: $("#address_line1").val(),
        address_line2: $("#address_line2").val(),
        country: $("#txtCountry").val(),
        state: $("#txtState").val(),
        city: $("#txtCity").val(),
        pin_code:$('#pin_code').val(),
        area: $("#txtarea").val(),
        emailid: $("#emailid").val(),
        website: $("#website").val(),
        is_schem: $("#IS_SCHEM").val(),
        address_id: $("#address_id").val(),
        entity_code: $("#entity_code").val(),
        // branch_id: $('#pkg_branch_id').val(),  //one master concept
        master_entity_id: $('#entity_master_id').val(),
        tpa_id: $('#entity_TPA').val().toString()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(entity_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    if (data1.data[0].StringResult == "already") {
                        $('#Pentity_name').show();
                        $('#Pentity_name').fadeOut(8000);
                        $('#Pentity_name').html('Entity Name already exists');
                        $('#entity_name').focus();
                        $('#entity_name').val('');
                        return false;

                    }
                    else {
                        // alert(data1.data[0].StringResult);
                        toastr.success(data1.data[0].StringResult,
                            {
                                closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            })

                        setTimeout(function () {

                            entity_documents_insert($("#entity_code").val(), $('#entity_master_id').val());
                            location.reload();
                        }, 1000);
                    }

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


//To Edit the entity data
function entity_edit(code, event) {
    debugger;
    $('#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");
    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 {
                     var entity_edit_data = {
                         Dml_Indicator: "ET",
                         master_entity_id: code,
                     }
                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/BillingMaster/entitymaster_creation_mapping',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(entity_edit_data),
                         success: function (data) {
                             var data1 = JSON.parse(data);
                             console.log(data1);
                             if (data1.msg == "Success") {
                                 if (jQuery.isEmptyObject((data1.data))) {
                                 }
                                 else {
                                     debugger;
                                     $("#entity_type").attr('disabled', true);
                                     $("#div_SCH").addClass('disabled');
                                     $("#entity_TPA").attr('disabled', false);
                                     //$('#div_TPA').removeClass('hidden');
                                     // alert(data1.data[0].StringResult)
                                     $("#entity_name").val(data1.data[0].entity_name),
                                     $("#payer_id").val(data1.data[0].payer_id),
                                     $("#entity_type").val(data1.data[0].entity_type)

                                     //if (data1.data[0].entity_type == 1) {
                                     //    $("#entity_type").attr('disabled', true);
                                     //    $("#div_SCH").addClass('disabled');
                                     //    $('#div_TPA').removeClass('hidden');

                                     //}
                                     //else {
                                     //    $("#entity_type").attr('disabled', false);

                                     //    //$("#div_SCH").attr('hidden', true);
                                     //    // $('#div_TPA').hide();
                                     //    //  $('#div_TPA').addClass('hidden');
                                     //    // $("#entity_type").change()
                                     //    //$('#IS_SCHEM').change();


                                     //}

                                     $("#address_line1").val(data1.data[0].address_line_1),
                                     $("#address_line2").val(data1.data[0].address_line_2),
                                     $("#pin_code").val(data1.data[0].pincode),
                                     $("#txtarea").val(data1.data[0].town_village),
                                     $("#emailid").val(data1.data[0].email_id),
                                     $("#website").val(data1.data[0].website),
                                     $("#address_id").val(data1.data[0].address_id),
                                     $("#entity_code").val(data1.data[0].entity_code),
                                     $('#entity_master_id').val(data1.data[0].master_entity_id);
                                     //one master concept
                                     //$('#pkg_branch_id').val(data1.data[0].branch_id);
                                     //if ($('#pkg_branch_id').val() == null || $('#pkg_branch_id').val() == 0) {
                                     //    $('#pkg_branch_id').attr('disabled', false);
                                     //}
                                     //else {
                                     //    $('#pkg_branch_id').attr('disabled', true);
                                     //}
                                     if (data1.data[0].admitted_entity > 0) {
                                         $("#entity_type").addClass('disabled');
                                     }
                                     else {
                                         $("#entity_type").removeClass('disabled');

                                     }


                                     $('#HTPA_ID').val(data1.data[0].tpa_id);
                                     load_TPA(data1.data[0].tpa_id); //one master concept
                                     // $('#pkg_branch_id').change();  //one master concept



                                   //  if (data1.data[0].entity_type == 1) {

                                         $('#div_SCH').removeClass('hidden');
                                         if (data1.data[0].is_schem == 1) {

                                             $('a[data-toggle=IS_SCHEM][data-title="1"]').removeClass('not-active');
                                             $('a[data-toggle=IS_SCHEM][data-title="1"]').addClass('active');
                                             $('a[data-toggle=IS_SCHEM][data-title="0"]').removeClass('active');
                                             $('a[data-toggle=IS_SCHEM][data-title="0"]').addClass('not-active');
                                             $('#div_TPA').addClass('hidden');

                                         }
                                         else if (data1.data[0].is_schem == 0) {
                                             $('a[data-toggle=IS_SCHEM][data-title="1"]').removeClass('active');
                                             $('a[data-toggle=IS_SCHEM][data-title="1"]').addClass('not-active');
                                             $('a[data-toggle=IS_SCHEM][data-title="0"]').removeClass('not-active');
                                             $('a[data-toggle=IS_SCHEM][data-title="0"]').addClass('active');
                                             $('#div_TPA').removeClass('hidden');

                                         }
                                         $('#IS_SCHEM').val(data1.data[0].is_schem);

                                     //}
                                     //else {
                                     //    $('#div_TPA').addClass('hidden');
                                     //    $('#div_SCH').addClass('hidden');
                                     //}



                                     //$('#entity_details').click();

                                     $('#entity_address_details').click();
                                     $('#docpathvalue').val(data1.data[0].payer_document_file_path);
                                     country(data1.data[0].country, data1.data[0].state, data1.data[0].city);
                                     var documents_file = data1.data[0].payer_document_file_path;
                                     const documentation = [];
                                     console.log(documents_file);
                                     if (documents_file !== null) {
                                         var payer_documentation = data1.data[0].payer_document_file_path;
                                         var payer_documentation_split = payer_documentation.split(',');
                                         for (var k = 0; k < payer_documentation_split.length; k++) {
                                             //var payer_documentation_file = '<a class="edit link-btn" onclick=id_image_show("' + payer_documentation_split[k] + '","' + data1.data[0].branch_id + '")>Payer_Documents' + (k + 1) + '' + '/' + '</button>' //one master concept
                                             var payer_documentation_file = '<a class="edit link-btn" onclick=id_image_show("' + payer_documentation_split[k] + '")>Payer_Documents' + (k + 1) + '' + '/' + '</button>'

                                             documentation.push(payer_documentation_file);
                                         }
                                     }
                                     else {
                                         const documentation = "-"
                                     }
                                     $('#photolog').html(documentation);
                                     $("#entity_fields").show();
                                     $(".table_view").hide();
                                     $("#LinktoBack").show();
                                     $("#LinktoDashboard").hide();
                                     $('#add_entitymaster').hide();
                                     $('#btnentity_submit').html('Update');
                                 }
                             }
                             else {
                                 console.log(data1)
                             }
                             $('#shade_slot').hide();
                         }
                     });
                 }
             }
         }
     })

}

//Rebinds the data to the text field
function country(country_val, state_val, city_val) {
    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) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {
                debugger;
                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var Country;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        Country = Country + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtCountry').append(default_opt + Country);
                    $('#txtCountry').val(country_val);
                    state(country_val, state_val, city_val);
                }
                else {
                    console.log(data);
                }

            }
        }
    });

}

//Rebinds the data state to the respected field
function state(coval, stateval, city_val) {
    var state = {
        country_id: coval,
        Dml_Indicator: "S"
    }

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

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

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

                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtState').append(default_opt + state);
                    $('#txtState').val(stateval);
                    city(stateval, city_val)
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

//Rebinds the data to the City field
function city(stateval, citval) {
    var state = {
        state_id: stateval,
        Dml_Indicator: "CI"
    }

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

            var data1 = JSON.parse(data);

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

            }
            else {
                // alert(' Sorry, The values you entered are invalid.\n Please try again. ');

                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtCity').append(default_opt + City);
                    $('#txtCity').val(citval);
                }
                else {
                    console.log(data);
                }

            }
        }

    });
}

//$("#btnSubmit1").click(function () {
//    debugger;
//    entity_billing_add()
//})


//$("#btnUpdate").click(function () {
//    debugger;
//    entity_billing_update()
//})



//to add billing to the particular entity
function entity_billing_add() {
    debugger;
    if ($.trim($('#entity_code').val()) == "") {
        $('#Pentity_name').show();
        $('#Pentity_name').fadeOut(8000);
        $('#Pentity_name').html('Choose an Respected Entity');
        $('#entity_name_show').focus();
        $('#entity_name_show').val('');
        return false;
    }
    if ($.trim($('#billing_type').val()) == 0) {
        $('#Pbilling_type').show();
        $('#Pbilling_type').fadeOut(8000);
        $('#Pbilling_type').html('Choose an Billing Type');
        $('#billing_type').focus();
        $('#billing_type').val('');
        return false;
    }
    if ($.trim($('#active_from').val()) == 0) {
        $('#Pactive_from').show();
        $('#Pactive_from').fadeOut(8000);
        $('#Pactive_from').html('Choose an Active From Date');
        $('#active_from').focus();
        $('#active_from').val('');
        return false;
    }
    if ($.trim($('#valid_upto').val()) == 0) {
        $('#Pvalid_upto').show();
        $('#Pvalid_upto').fadeOut(8000);
        $('#Pvalid_upto').html('Choose an Valid To Date');
        $('#valid_upto').focus();
        $('#valid_upto').val('');
        return false;
    }

    var fromdatesplit = $('#active_from').val().split('/');
    fromdatesplit = fromdatesplit[1] + '/' + fromdatesplit[0] + '/' + fromdatesplit[2];
    var fromdateval = new Date(fromdatesplit).getTime();
    var todatevalsplit = $('#valid_upto').val().split('/');
    todatevalsplit = todatevalsplit[1] + '/' + todatevalsplit[0] + '/' + todatevalsplit[2];
    var todateval = new Date(todatevalsplit).getTime();

    if (todateval < fromdateval) {
        $('#Pvalid_upto').show();
        $('#Pvalid_upto').fadeOut(8000);
        $('#Pvalid_upto').html('Choose an Valid To Date');
        $('#valid_upto').focus();
        $('#valid_upto').val('');
        return false;
    }
    var activefrom = '';
    var activeto = '';
    if ($('#active_from').val() != '' && $('#active_from').val() != null) {
        var startdate = $('#active_from').val();
        var splitdate = startdate.split('/');
        var formated_date = splitdate[2] + '-' + splitdate[1] + '-' + splitdate[0];
        activefrom = (formated_date);
    }
    if ($('#valid_upto').val() != '' && $('#valid_upto').val() != null) {
        var startdate = $('#valid_upto').val();
        var splitdate = startdate.split('/');
        var formated_date = splitdate[2] + '-' + splitdate[1] + '-' + splitdate[0];
        activeto = (formated_date);
    }
    var Sel_corporate = 0;
    if ($('#Sel_corporate').val().length != 0) {
        Sel_corporate = $('#Sel_corporate').val().toString();
    }

    var entity_billing_data = {

        Dml_Indicator: "MBI",
        billing_type: $('#billing_type').val(),
        entity_code: $('#entity_code').val(),
        active_from: activefrom,
        active_to: activeto,
        master_entity_id: $('#entity_master_id').val(),
        entity_billing_id: 0,
        address_id: 0,
        entity_type: 0,
        country: 0,
        state: 0,
        city: 0,
        corporate_id: Sel_corporate
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(entity_billing_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            debugger;
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {

                    if (data1.data[0].StringResult == 'Inserted') {
                        toastr.success('Inserted successfully',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                        setTimeout(function () {

                            manage_billing_grade($('#entity_code').val(), $('#entity_name_show').val(), $('#payer_code_show').val(), $('#entity_master_id').val(), $('#Hbranch_id').val(), $('#entity_type').val(), 2)
                            $('#billing_type').val('');
                            $('#active_from').val('');
                            $('#valid_upto').val('');
                            $('#Sel_corporate').val('').change();
                            // location.reload();
                        }, 1000);
                    }
                    else {
                        //alert(data1.data[0].StringResult)
                        toastr.success('Inserted Successfully');
                        manage_billing_grade($('#entity_code').val(), $('#entity_name_show').val(), $('#payer_code_show').val(), $('#entity_master_id').val(), $('#Hbranch_id').val(), $('#entity_type').val(), 2)
                        $('#billing_type').val('');
                        $('#active_from').val('');
                        $('#valid_upto').val('');
                        $('#Sel_corporate').val('').change();
                    }


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

//Edit the entity_creation_mapping
function manage_billing_edit(billing_id, billing_type, valid_from, valid_to, admitted_entity, corporate_id) {

    //if (admitted_entity > 0) {
    //    $('#billing_type').addClass('disabled');

    //}
    //else
    //{
    //    $('#billing_type').removeClass('disabled');
    //}
    debugger;
    $('#btnSubmit1').hide();
    $('#btnUpdate').show();
    $('#entity_billing_id').val(billing_id)
    $('#billing_type').val(billing_type),
    $('#active_from').val(valid_from),
    $('#valid_upto').val(valid_to)
    if (corporate_id != '' && corporate_id != null) {
        var corporate = '';
        var arr = [];
        if (corporate_id != null) {

            corporate1 = corporate_id.split(',');

            for (var i = 0; i < corporate1.length; i++) {
                arr[i] = $.trim(corporate1[i]);
            }
            $('#Sel_corporate').val(arr).change();
        }
    }
}

//Update the billing Class mapped
function entity_billing_update() {
    debugger;
    if ($.trim($('#entity_code').val()) == "") {
        $('#Pentity_name').show();
        $('#Pentity_name').fadeOut(8000);
        $('#Pentity_name').html('Choose an Respected Entity');
        $('#entity_name_show').focus();
        $('#entity_name_show').val('');
        return false;
    }
    if ($.trim($('#billing_type').val()) == 0) {
        $('#Pbilling_type').show();
        $('#Pbilling_type').fadeOut(8000);
        $('#Pbilling_type').html('Choose an Billing Type');
        $('#billing_type').focus();
        $('#billing_type').val('');
        return false;
    }
    if ($.trim($('#active_from').val()) == 0) {
        $('#Pactive_from').show();
        $('#Pactive_from').fadeOut(8000);
        $('#Pactive_from').html('Choose an Active From Date');
        $('#active_from').focus();
        $('#active_from').val('');
        return false;
    }
    if ($.trim($('#valid_upto').val()) == 0) {
        $('#Pvalid_upto').show();
        $('#Pvalid_upto').fadeOut(8000);
        $('#Pvalid_upto').html('Choose an Valid Date');
        $('#valid_upto').focus();
        $('#valid_upto').val('');
        return false;
    }
    var Sel_corporate = 0;
    if ($('#Sel_corporate').val().length != 0) {
        Sel_corporate = $('#Sel_corporate').val().toString();
    }
    var entity_billing_Update_data = {
        Dml_Indicator: "MBU",
        billing_type: $('#billing_type').val(),
        entity_code: $('#entity_code').val(),
        active_from: $('#active_from').val(),
        active_to: $('#valid_upto').val(),
        entity_billing_id: $('#entity_billing_id').val(),
        master_entity_id: $('#entity_master_id').val(),
        corporate_id: Sel_corporate
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(entity_billing_Update_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            debugger;
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {

                    if (data1.data[0].StringResult == "AdmitActiveEntity") {
                        toastr.warning('Selected Partner is already used in IP Management. Unable to Update the Billing Grade',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    }
                    else {
                        toastr.success('Updated Successfully');
                        //4alert(data1.data[0].StringResult)
                        manage_billing_grade($('#entity_code').val(), $('#entity_name_show').val(), $('#payer_code_show').val(), $('#entity_master_id').val(), $('#Hbranch_id').val(), $('#Hentity_type').val(), 2);
                        $('#billing_type').val('');
                        $('#active_from').val('');
                        $('#valid_upto').val('');
                        $('#btnSubmit1').show();
                        $('#btnUpdate').hide();
                        $('#Sel_corporate').val('').change();
                    }

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

//To Upload Image
function packageimageupload() {
    debugger;
    var uploadpath = $('#fileToUpload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (fileExtension == "pdf" || fileExtension == "doc" || fileExtension == "PDF" || fileExtension == "DOC") {
    }
    else {
        $('#PReferraldocuments').show();
        $('#PReferraldocuments').fadeOut(8000);
        $('#PReferraldocuments').html('Please upload file having extensions .pdf/.doc only.');
        $('#fileToUpload').val("");
        $('#fileToUpload').focus();
        return false;
    }
    if (window.FormData !== undefined) {
        debugger;
        var fileUpload = $("#fileToUpload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        fileData.append($('#txtPatientName').val(), '');
        var id;
        if (fileExtension == "pdf" || fileExtension == "PDF") {
            id = "1";
        }
        else {
            id = "2";
        }
        fileData.append(id, '');
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }


        $.ajax({
            //url: '/BillingMaster/UploadIDProof?branch_id=' + $('#pkg_branch_id').val(), //one master concept
            url: '/BillingMaster/UploadIDProof',
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                debugger;
                $.each(result, function (i, emp) {
                    debugger;
                    var pathName = ($.trim($('#docpathvalue').val()));
                    if (pathName !== "") {
                        pathName = pathName + "," + result.img;
                    }
                    else {
                        pathName = result.img;
                    }
                    console.log(pathName);
                    $('#docpathvalue').val(pathName);
                    $('#photolog').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() +  "/Payer_Documents/" + pathName + '" target="_blank">View ' + PayerDocumentsCount + '' + '/' + '</a>');
                    //$('#photolog').append('<a href="' + $('#hdnfilepath1').val() + $('#HospitalId').val() + "/" + $('#pkg_branch_id').val() + "/Payer_Documents/" + pathName + '" target="_blank">View ' + PayerDocumentsCount + '' + '/' + '</a>');
                });
            }
        });
    }
}

//Shows the pdf view  from the table
function id_image_show(id) {
    debugger;
    window.open($('#hdnfilepath1').val() + $('#HospitalId').val() + "/Payer_Documents/" + id, '_blank');

}

//Loads the Billing Class
function LoadBillingClass(branchid, is_schem) {
    debugger;
    var designation = {
        Dml_Indicator: "LB",
        //branch_id: $('#branch_id').val() 
       // branch_id: branchid,
        is_schem: is_schem

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(designation),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#billing_type').html('');
                    $('#billing_type').val('');
                    var BillingClass;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        BillingClass = BillingClass + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#billing_type').append(default_opt + BillingClass);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Load Branch
function LoadBranch() {
    debugger;
    document.getElementById("pkg_branch_id").innerHTML = null;

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

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

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //    $('#branch_id').val($('#HospitalBranchID').val());
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#branch_id').val($('#HospitalBranchID').val());
                        $('#branch_id').attr('disabled', true);
                        $('#pkg_branch_id').change()
                        CheckCodeTemplate();
                        //entity_table();
                    }
                    // $('#pkg_branch_id').val(val);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

//load billing class
function loadtube_container() {
    debugger;
    //var branch_id = 0;
    //if (val == 0) {
    //    branch_id = ($('#branch_id').val() == '' ? 0 : $('#branch_id').val())
    //}
    //else {
    //    branch_id = val;
    //}
    var data = {
        P_Dml_Indicator: 'TC',
        branch_id: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;
            $('#loadctubecontainer').empty();
            var data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {


                    var sampletypetube = '';
                    var default_opt = '<option value="0" data-id="0">--Select--</option>';
                    $.each(data2.data, function (i, emp) {
                        sampletypetube = sampletypetube + '<option value="' + emp.master_servie_type_id + '" data-id="' + emp.master_servie_type_id + '" > ' + emp.master_service_name + '</option>';
                    });
                    if (data2.data.length != 1) {
                        $('#loadctubecontainer').append(default_opt + sampletypetube);
                    }
                    else {
                        $('#loadctubecontainer').append(sampletypetube);
                    }
                    if (id != null && id != 0) {
                        $('#loadctubecontainer').val(id);
                    }
                }
            }
        }
    })
}
$('#btnclear').click(function () {
   // $('#branch_id').val(0); //one master concept
    $('#entity_type_filter').val(0);
    $('#status_filter').val(0);
    //LoadBranch();
    entity_table();
})


function act_inact_del(id, event, flag) {
    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 (flag == 'active') {
                         status = "Are You Sure Do You Want Activate?";
                     }
                     else if (flag == 'inactive') {
                         status = "Are You Sure Do You Want In Activate?";
                     }
                     else if (flag == 'del') {

                         status = "Are You Sure Do You want 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;
                                var status_data = {
                                    master_entity_id: id,
                                    Dml_Indicator: "AC_IAC_DEL",
                                    entity_name: flag
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/BillingMaster/entitymaster_creation_mapping',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(status_data),
                                    success: function (data) {
                                        debugger
                                        var data2 = JSON.parse(data);

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

                                        }
                                        else {

                                            if (data2.msg == "Success") {
                                                debugger;
                                                data1 = data2.data;
                                                if (flag == 'active') {
                                                    toastr.success("Activated Successfully");
                                                    setTimeout(function () {
                                                        //location.reload();
                                                    }, 1000);
                                                }
                                                else if (flag == 'inactive') {
                                                    data1 = data2.data;
                                                    if (data1[0].Message == 'Mapped with Entity') {
                                                        toastr.warning("The selected Entity is Mapped. Unable to In-active.");
                                                        return;
                                                    }
                                                    else {
                                                        toastr.success("In-activated Successfully");
                                                        setTimeout(function () {
                                                            //location.reload();
                                                        }, 1000);
                                                    }
                                                }
                                                else {
                                                    data1 = data2.data;
                                                    if (data1[0].Message == 'Mapped with Entity') {
                                                        toastr.warning("The selected Entity is Mapped. Unable to Delete.");
                                                        return;
                                                    }
                                                    else {
                                                        toastr.success("Deleted Successfully");
                                                        setTimeout(function () {
                                                            //location.reload();
                                                        }, 1000);
                                                    }
                                                }
                                                if (jQuery.isEmptyObject((data1))) {
                                                }
                                                else {
                                                    //location.reload();
                                                    entity_table();
                                                }
                                            }
                                            else {
                                                console.log(data);
                                            }
                                        }
                                    }
                                });
                            });
                        }
                    });


                 }
             }
         }
     });
}
//Corporate Insurance mapping-Added by Tharuni
//Loading corporate
function Loadcorporate(branchid) {
    var activate_data = {
        Dml_Indicator: "CL",
       // branch_id: branchid
    }
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            $('#Sel_corporate').empty();
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var data1 = data1.data;
                    var default_opt = '<option value="0">--Select--</option>';
                    var option = '';
                    $.each(data1, function (i, emp) {
                        option = option + '<option value="' + emp.master_entity_id + '">' + emp.entity_name + '</option>';
                    });
                    $('#Sel_corporate').append(option);
                }
            }
            else {
                console.log(data1)
            }
        }
    });
}

$('#Sel_corporate').on('select2:unselect', function (e) {
    debugger;
    var data = e.params.data.id;
    if ($('#entity_billing_id').val() != '') {
        corporate_delete(data);
    }
    //var arr = $('#external_lab').val();


});

//Remove Corporate
function corporate_delete(id) {
    var activate_data = {
        Dml_Indicator: "CLD",
        corporate_id: id,
        entity_billing_id: $('#entity_billing_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);

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

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

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

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




    if ($('#entity_type').val() == 1) {
        $('#div_SCH').removeClass('hidden');

        $('#div_TPA').addClass('hidden');

        $("#div_SCH").removeClass('disabled');


    }
    else {
       // $('#div_SCH').addClass('hidden');

        $('#div_SCH').removeClass('hidden');  //Medway Requirement changed by Tharuni
        $('#div_TPA').addClass('hidden');


    }

})

$('#IS_SCHEM').change(function () {
    debugger;
    $('#HTPA_ID').val("").change();
    var H_tpa_id = $('#HTPA_ID').val()
    //var branch_id = $('#pkg_branch_id').val(); //one master concept
    // load_TPA(branch_id, H_tpa_id)



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

        $('#div_TPA').addClass('hidden');
        // $('#pkg_branch_id').change(); //one master concept

    }
    else {

        $('#div_TPA').removeClass('hidden');
        //load_TPA(branch_id, H_tpa_id)
        load_TPA(H_tpa_id) //one master concept


    }
})


$('#pkg_branch_id').change(function () {
    debugger;
    var H_tpa_id = $('#HTPA_ID').val()
    var branch_id = $('#pkg_branch_id').val();
    CheckCodeTemplate();
    load_TPA(branch_id, H_tpa_id)
})

function load_TPA(H_tpa_id) {
    debugger;
   // var branchid = branch_id; //one master concept

    var activate_data = {
        Dml_Indicator: "TPA",
        // branch_id: branchid //one master concept
    }
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/entitymaster_creation_mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(activate_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            $('#entity_TPA').empty();
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var data1 = data1.data;
                    var default_opt = '<option value="0">--Select--</option>';
                    var option = '';
                    $.each(data1, function (i, emp) {
                        option = option + '<option value="' + emp.tpa_id + '">' + emp.name + '</option>';
                    });
                    $('#entity_TPA').append(option);
                }

                var H_tpa_id1 = H_tpa_id

                if (H_tpa_id1 != '' && H_tpa_id1 != null) {
                    var tpaid = '';
                    var arr = [];
                    if (H_tpa_id1 != null) {

                        tpaid = H_tpa_id1.split(',');

                        for (var i = 0; i < tpaid.length; i++) {
                            arr[i] = $.trim(tpaid[i]);
                        }
                        $('#entity_TPA').val(arr).change();
                    }
                }
            }
            else {
                console.log(data1)
            }
        }
    });
}

///add new button
$('#add_entitymaster').click(function () {
    debugger;


    var did = $(this).attr("data-id");
    var navigation = $(this).attr("data-nav");
    var name = $(this).attr("data-name");
    var columntype = $(this).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") {
            var data1 = data1.data;
            if (jQuery.isEmptyObject((data1))) {
            }
            else {
                var j = 0;
                debugger;
                var status = data1.Table[0].role_rights_add

                if (status == 0) {

                    return;
                }
                else {
                    $("#entity_fields").show();
                    $(".table_view").hide();
                    $("#add_entitymaster").hide();
                    $("#add_entitymaster_aside").hide();
                    $("#LinktoBack").show();
                    $("#LinktoDashboard").hide();

                    //       if ($('#entity_master_id').val() != "" && $('#entity_master_id').val() != null) {
                    $("#entity_name").val(''),
                $("#payer_id").val(''),
                $("#entity_type").val(''),
                $("#address_line1").val(''),
                $("#address_line2").val(''),
                 loadcountry();
                    //$("#txtCountry").val(''),
                    //$("#txtState").val(''),
                    //$("#txtCity").val(''),
                    $("#txtarea").val(''),
                    $("#pin_code").val(''),
                    $("#emailid").val(''),
                    $("#pin_code").val(''),
                    $("#website").val(''),
                    $('#IS_SCHEM').val('');
                    $("#address_id").val(''),
                    $("#entity_code").val(''),
                    $("#photolog").val(''),
                    $('#btnentity_submit').html('Submit');
                    //one master concept
                    //if ($('#hiddenRole_id').val() == 2)  {
                    //    $('#pkg_branch_id').attr('disabled', false);
                    //    $('#pkg_branch_id').val(0);
                    //}
                    //else if ($('#hiddenRole_id').val() == 1)
                    //{
                    //    $('#pkg_branch_id').attr('disabled', false);
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //}
                    //else
                    //{
                    //    $('#pkg_branch_id').attr('disabled', true);
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //}
                    
                    $("#entity_TPA").attr('disabled', false);

                    $('#photolog').html('');

                    $('#entity_TPA').empty();
                   
                    $('#IS_SCHEM').val('');

                    $('#div_SCH').addClass('hidden');

                    $('#div_TPA').addClass('hidden');

                    //  }
                    //LoadBranch();

                }
            }
        }
    });

});

//backward  button
$('#LinktoBack').click(function () {
    debugger

    $('#HTPA_ID').html('');
    $("#entity_fields").hide();
    $(".table_view").show();
    $("#add_entitymaster").show();
    $("#add_entitymaster_aside").show();

    $("#entity_type").attr('disabled', false)
    $("#div_SCH").removeClass('disabled');

    $('#div_TPA').addClass('hidden');
    $('#IS_SCHEM').val('');

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

    $("#txtCountry").val('');
    $("#txtState").val('');
    $("#txtCity").val('');

    //window.location.reload();
});