$(document).ready(function () {
 
    LoadBranch();
    loadvisit_type()
    $('#selChooseType').change();
});


//CheckCodeTemplate
function CheckCodeTemplate() {
    debugger;
    var codeData = {
        //Dml_Indicator: "CT",
        Dml_Indicator: "BCT",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#selBranchName').val()
        //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('' + $('#selBranchName  option:selected').html() + ' Not Added Code Template. Please Add the Code Template at SetupIds');
                window.location.href = "/Hospitalsetup"
            }
            //else {
            //    LoadBranch()
            //}

        }
    });
}

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

                    if ($('#hiddenRole_id').val() != 2) {
                        $('#selBranchName').val($('#HospitalBranchID').val());
                        $('#selBranchName').attr('disabled', true);

                       
                        $('#selChooseType').change();
                        CheckCodeTemplate();
                    }                   
                }
            }
            else {
                console.log(data1);
            }

            LoadServiceBillingClassHeaders();
           
        }
    });
}

$('#selBranchName').change(function () {
    
    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
       
        
        return false;
    }
    CheckCodeTemplate();
    LoadServiceBillingClassHeaders();
   // $('#selChooseType').change(); //one master concept
});

$('#selChooseType').change(function () {
    debugger;
    if ($('#selChooseType').val() == null || $('#selChooseType').val() == "") {
        return false;
    }
    //if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
    //    $('#PselBranchName').show();
    //    $('#PselBranchName').fadeOut(8000);
    //    $('#PselBranchName').html('Select Branch Name');
    //    $('#selBranchName').val('');
    //    $('#selBranchName').focus();
    //    return false;
    //} //one master concept

    var Dml_Indicator = '';
    if ($('#selChooseType').val() == "1") { // category list
        Dml_Indicator = "CL";
        $('#lblCategoryDept').html('Select Category');
        $('#lblSubCategoryDept').html('Select Sub Category');
    }
    else {                               //department list
        Dml_Indicator = "DL";
        $('#lblCategoryDept').html('Select Department');
        $('#lblSubCategoryDept').html('Select Sub Department');
    }
    var typedata = {       
        Dml_Indicator: Dml_Indicator,
        //branch_id: $('#selBranchName').val() //one master concept
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typedata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {              
               
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#selCategoryorDept').empty();
                    $('#selSubCategoryorDept').empty();
                    if (data.Table.length > 0) {

                        var CategoryDeptList;
                        var default_opt = '<option value="0">--Select--</option>';
                        $.each(data.Table, function (i, emp) {
                            CategoryDeptList = CategoryDeptList + '<option value="' + emp.master_category_department_id + '">' + emp.name + '</option>';
                        });
                        if (data.Table.length == 1) {
                            $('#selCategoryorDept').append(CategoryDeptList);
                        }
                        else {
                            $('#selCategoryorDept').append(default_opt + CategoryDeptList);
                        }
                    }

                        //var tr = ''; var row = '';
                        //for (var i = 0; i < data.Table.length; i++) {
                        //    var row = '';
                        //    tr = '<li id="li_' + data.Table[i].master_category_department_id + '"><a href="#!" id="cdlist_' + data.Table[i].master_category_department_id + '" onclick=GetServiceList("1","' + data.Table[i].master_category_department_id + '","1")><span>' + data.Table[i].name + '</span></a></li>';

                        //    $('#sellistCategoryDept').append(tr);

                        //    if (data.Table1.length > 0) {
                        //        for (var j = 0; j < data.Table1.length; j++) {
                        //            if (data.Table[i].master_category_department_id == data.Table1[j].master_category_department_id) {
                        //                row = row + '<li  id="subli_' + data.Table1[j].sub_category_department_id + '"><a href="#!" onclick=GetServiceList("2","' + data.Table1[j].sub_category_department_id + '","2")><span>' + data.Table1[j].sub_cd_name + '</span></a></li>';
                        //            }
                        //            //else {
                        //            //    j++;
                        //            //}

                        //        }
                        //    }

                        //    if (row != "") {
                        //        $('#li_' + data.Table[i].master_category_department_id).addClass("treeview");
                        //        $('#cdlist_' + data.Table[i].master_category_department_id).append('<span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span>');
                        //        $('#li_' + data.Table[i].master_category_department_id).append('<ul class="treeview-menu">' + row + '</ul>');
                        //    }
                        //}                  
                    //}
                    //else {
                    //    var errormsg = $('#selChooseType').val() == "1" ? "Category list not found" : "Department list not found";
                    //    $('#sellistCategoryDept').append(errormsg);
                    //}
                }
            }
            else {
                console.log(data);
            }
        }
    });

});


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

    var typedata = {       
        Dml_Indicator: 'SCDL',
        branch_id: $('#selBranchName').val(),
        category_dept_id: $('#selCategoryorDept').val()
    }

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

                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#selSubCategoryorDept').empty();
                    if (data.Table.length > 0) {

                        var SubCategoryDeptList;
                        var default_opt = '<option value="0">--Select--</option>';
                        $.each(data.Table, function (i, emp) {
                            SubCategoryDeptList = SubCategoryDeptList + '<option value="' + emp.sub_category_department_id + '">' + emp.sub_cd_name + '</option>';
                        });
                        if (data.Table.length == 1) {
                            $('#selSubCategoryorDept').append(SubCategoryDeptList);
                        }
                        else {
                            $('#selSubCategoryorDept').append(default_opt + SubCategoryDeptList);
                        }
                    }
                }
            }
        }
    });

})


function LoadServiceBillingClassHeaders() {

    $('#selBillingClass').empty();
    $('#selWard').empty();

    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
        return false;
    }

    var typedata = {
        Dml_Indicator: 'B',
        branch_id: $('#selBranchName').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typedata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;               
               
                if (jQuery.isEmptyObject((data))) {
                    
                }
                else {
                    if (data.Table.length > 0) {

                      // Load billing class dropdown
                        var BillingClass = "";
                        var default_opt = '<option value="0">--Select--</option>';
                        $.each(data.Table, function (i, emp) {
                            BillingClass = BillingClass + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                        });
                        if (data.Table.length == 1) {
                            $('#selBillingClass').append(BillingClass);                           
                        }
                        else {
                            $('#selBillingClass').append(default_opt + BillingClass);
                        }

                        


                        //commented by nandhini on 28/09/2023
                        //var tr = "";
                        //var thead = "";
                        //var tSubhead = "";
                        //var optr = "";
                        //var homecaretr = "";
                        //var opward = "";
                        //var homecareward = "";
                        //var isOpExists = 0;
                        //var isIpExists = 0;
                        //var isopwardcolumnexists = 0;
                        
                        //debugger;
                        //for (var i = 0; i < data.Table.length; i++) {
                        //    var wardRow = "";
                        //    var opwardclassid = '';
                            
                        //    var trfirstClass = "";
                        //    var count = data.Table1.length;
                        //    if (data.Table1.length > 0) {
                        //        for (var j = 0; j < data.Table1.length; j++) {

                        //            var color_class_name = '';
                        //            if ((i % 2) == 0) {
                        //                color_class_name = "even-color "
                        //            }
                        //            else {
                        //                color_class_name = "odd-color "
                        //            }

                        //            if (data.Table1[j].ward_name == "OP" && data.Table[i].master_service_name == "OP") {
                        //                opward = '<th scope="col" class="clsward_' + data.Table1[j].wardid + ' clsbill_' + data.Table[i].master_servie_type_id + ' ' + color_class_name + '">' + data.Table1[j].ward_name + ' <a href="javascript:;" onclick=\'GetServicesListonBillingClass(\"' + data.Table[i].master_servie_type_id + '\",\"' + data.Table[i].master_service_name + '\",\"' + data.Table1[j].wardid + '\",\"' + data.Table1[j].ward_name + '\",\"' + ((data.Table[i].is_scheme == 1) ? 1 : 0) + '\")\'><i class="fa fa-edit"></i></a></th>';
                        //                isOpExists = 1;                                        
                        //            }
                        //            else if (data.Table1[j].ward_name == "HOMECARE" && data.Table[i].master_service_name == "HOMECARE") {
                        //                homecareward = '<th scope="col" class="clsward_' + data.Table1[j].wardid + ' clsbill_' + data.Table[i].master_servie_type_id + ' ' + color_class_name + '">' + data.Table1[j].ward_name + ' <a href="javascript:;" onclick=\'GetServicesListonBillingClass(\"' + data.Table[i].master_servie_type_id + '\",\"' + data.Table[i].master_service_name + '\",\"' + data.Table1[j].wardid + '\",\"' + data.Table1[j].ward_name + '\",\"' + ((data.Table[i].is_scheme == 1) ? 1 : 0) + '\")\'><i class="fa fa-edit"></i></a></th>';
                        //                isIpExists = 1;
                        //            }


                        //            if (data.Table1[j].ward_name == "OP" && data.Table[i].master_service_name != "OP" && data.Table[i].master_service_name != "HOMECARE") {
                        //                wardRow = wardRow + '<th scope="col" class="clsward_' + data.Table1[j].wardid + ' clsbill_' + data.Table[i].master_servie_type_id + ' ' + color_class_name + '">OP Insurance<a href="javascript:;" onclick=\'GetServicesListonBillingClass(\"' + data.Table[i].master_servie_type_id + '\",\"' + data.Table[i].master_service_name + '\",\"' + data.Table1[j].wardid + '\",\"' + "OP Insurance" + '\",\"' + ((data.Table[i].is_scheme == 1) ? 1 : 0) + '\")\'><i class="fa fa-edit"></i></a></th>';
                        //                isopwardcolumnexists = 1;
                        //            }
                        //            else if ((data.Table1[j].ward_name != "OP" && data.Table[i].master_service_name != "OP") && (data.Table1[j].ward_name != "HOMECARE" && data.Table[i].master_service_name != "HOMECARE")) {
                        //                //else if ((data.Table1[j].ward_name != "HOMECARE" && data.Table[i].master_service_name != "HOMECARE")) {
                        //                wardRow = wardRow + '<th scope="col" class="clsward_' + data.Table1[j].wardid + ' clsbill_' + data.Table[i].master_servie_type_id + ' ' + color_class_name + '">' + data.Table1[j].ward_name + ' <a href="javascript:;" onclick=\'GetServicesListonBillingClass(\"' + data.Table[i].master_servie_type_id + '\",\"' + data.Table[i].master_service_name + '\",\"' + data.Table1[j].wardid + '\",\"' + data.Table1[j].ward_name + '\",\"' + ((data.Table[i].is_scheme == 1) ? 1 : 0) + '\")\'><i class="fa fa-edit"></i></a></th>';
                                        
                        //            }

                                                                       
                        //        }

                                
                        //    }
                        //    if (i == 0) {
                        //        trfirstClass = 'clsbilling_initial';
                        //    }
                        //    //adding op to every billing class manually
                        //    //if (iswardExists > 0 && isOpExists > 0) {
                        //    //    wardRow = opward + wardRow;
                        //    //}
                           
                        //    tSubhead = tSubhead + wardRow;

                        //    // set odd even color for the headers
                        //    count = (isOpExists > 0 && isIpExists > 0) ? (count - 2) : (isOpExists > 0) ? (count - 1) : (isIpExists > 0) ? (count - 1) : count;

                        //    count = (isopwardcolumnexists > 0) ? (count + 1) : count;

                        //    var color_class_name = '';
                        //    if ((i % 2) == 0) {
                        //        color_class_name = " even-color "
                        //    }
                        //    else {
                        //        color_class_name = " odd-color "
                        //    }

                        //    if (data.Table[i].master_service_name == "OP") {
                        //        optr = '<th colspan="' + 1 + '" scope="colgroup" class="' + trfirstClass + color_class_name + ' clsbilling_' + data.Table[i].master_servie_type_id + ' ">' + data.Table[i].master_service_name + '</th>';
                        //    }
                        //    else if (data.Table[i].master_service_name == "HOMECARE") {
                        //        homecaretr = '<th colspan="' + 1 + '" scope="colgroup" class="' + trfirstClass + color_class_name + ' clsbilling_' + data.Table[i].master_servie_type_id + ' ">' + data.Table[i].master_service_name + '</th>';
                        //    }
                        //    else {
                        //        tr = tr + '<th colspan="' + count + '" scope="colgroup" class="' + trfirstClass + color_class_name  + ' clsbilling_' + data.Table[i].master_servie_type_id + ' ">' + data.Table[i].master_service_name + '</th>';
                        //    }
                           
                            
                        //}

                        //thead = '<th rowspan="2" style="display:none">Service ID</th><th class="s_name_width" rowspan="2">Service Name</th><th rowspan="2">Type</th><th rowspan="2">Base Amount</th>' + optr + homecaretr + tr;
                       
                        //$('#tblServicesHead').append('<tr>' + thead + '</tr><tr>' + opward + homecareward + tSubhead + '</tr>');
                                                

                        //var totalnonwardcount = (isOpExists > 0 && isIpExists > 0) ? 2 : (isOpExists > 0) ? 1 : (isIpExists > 0) ? 1 : 0;
                        //$('#TotalBillingCount').val((data.Table.length - totalnonwardcount));
                        //$('#TotalWardCount').val(((data.Table1.length + (isopwardcolumnexists>0 ? 1 : 0)) - totalnonwardcount));
                        //$('#TotalNonWardCount').val(totalnonwardcount);
                        //$('#servicedivwrap').show();
                    }

                    if (data.Table1.length > 0) {
                        // Load ward dropdown
                        var Ward = ""; var opwardidforInsurance = "";
                        var default_opt = '<option value="0">--Select--</option>';
                        $.each(data.Table1, function (i, emp) {
                            if (emp.ward_name == "OP") {
                                opwardidforInsurance = emp.wardid;
                            }
                            Ward = Ward + '<option value="' + emp.wardid + '" name="'+emp.ward_name+'">' + emp.ward_name + '</option>';
                        });

                        if (opwardidforInsurance != null && opwardidforInsurance != "") {
                            Ward = '<option value="' + opwardidforInsurance + '" name="OP Insurance">' + "OP Insurance" + '</option>' + Ward;
                        }

                        if (data.Table.length == 1) {
                            
                            $('#selWard').append(Ward);
                        }
                        else {
                            $('#selWard').append(default_opt + Ward);
                        }

                        $('#selWard option[name="OP"]').hide();
                        $('#selWard option[name="HOMECARE"]').hide();
                        $('#selWard option[name="Healthcare Professional"]').hide();
                    }
                   
                    if (data.Table.length <= 0 && data.Table1.length <= 0) {
                    
                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'Billing Class and Ward for this branch is Unavailable. Kindly add it.',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000

                      })
                        return false;
                    }
                    else if (data.Table.length <= 0) {
                   
                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'Billing Class for this branch is Unavailable. Kindly add it.',
                    {
                        closeButton: true,
                        progressBar: true,
                        allowHtml: true,
                        timeOut: 20000000

                    })
                        return false;
                    }
                    else if (data.Table1.length <= 0) {
                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'Ward for this branch is Unavailable. Kindly add it.',
                        {
                        closeButton: true,
                        progressBar: true,
                        allowHtml: true,
                        timeOut: 20000000

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

}

$('#selBillingClass').change(function () {
    debugger
    if ($('#selBillingClass :selected').text() == "OP") {
       
        $('#selWard option[name="OP"]').show();        
        $('#selWard option[name="OP"]').prop("selected", true);
        $('#selWard').attr('disabled', true);
    }
    else if ($('#selBillingClass :selected').text() == "HOMECARE") {
        
        $('#selWard option[name="HOMECARE"]').hide();
        $('#selWard').attr('disabled', true);
        $('#selWard option[name="HOMECARE"]').prop("selected", true);
    }
    else if ($('#selBillingClass :selected').text() == "Healthcare Professional") {

        $('#selWard option[name="Healthcare Professional"]').hide();
        $('#selWard').attr('disabled', true);
        $('#selWard option[name="Healthcare Professional"]').prop("selected", true);
    }
    else {
        $('#selWard option[name="OP"]').hide();
        $('#selWard option[name="HOMECARE"]').hide();
        $('#selWard option[name="Healthcare Professional"]').hide();
        $('#selWard').attr('disabled', false);
        $('#selWard').val(0);
    }

    var typedata = {
        Dml_Indicator: 'BD',        
       // branch_id: $('#selBranchName').val(),    //one master concept    
        billing_class: $('#selBillingClass').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typedata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                debugger;
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table.length > 0) {
                        var isscheme = (data.Table[0].is_schem==1) ? 1 : 0;
                        $('#HiddenScheme').val(isscheme);
                    }
                   
                }
            }
        }
    });

})

var isOPHomeCare = false;
var isApplied = false;

function ShowServices(){

    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
        return false;
    }

    if ($('#selCategoryorDept').val() == null || $('#selCategoryorDept').val() == "" || $('#selCategoryorDept').val() == "0") {
        $('#PselCategoryorDept').show();
        $('#PselCategoryorDept').fadeOut(8000);
        $('#PselCategoryorDept').html('Select Category');
        $('#selCategoryorDept').val('');
        $('#selCategoryorDept').focus();
        return false;
    }

    if ($('#selBillingClass').val() == null || $('#selBillingClass').val() == "" || $('#selBillingClass').val() == "0") {
        $('#PselBillingClass').show();
        $('#PselBillingClass').fadeOut(8000);
        $('#PselBillingClass').html('Select Billing Class');
        $('#selBillingClass').val('');
        $('#selBillingClass').focus();
        return false;
    }

    if ($('#selWard').val() == null || $('#selWard').val() == "" || $('#selWard').val() == "0") {
        $('#PselWard').show();
        $('#PselWard').fadeOut(8000);
        $('#PselWard').html('Select Ward');
        $('#selWard').val('');
        $('#selWard').focus();
        return false;
    }

    var billing_class_name = $('#selBillingClass :selected').text();
    var wardname = $('#selWard :selected').text();

    if ((billing_class_name == "OP" || billing_class_name == "HOMECARE" || billing_class_name == "Healthcare Professional") || (wardname == "OP Insurance")) {
        $('#btnApplyToAllWard').attr('disabled', true);
        isOPHomeCare = true;
        $('#divBillingClassSelectOption').hide();
    }    
    else {
        $('#btnApplyToAllWard').attr('disabled', false);
        $('#divBillingClassSelectOption').show();
    }

    if ( $('#HiddenScheme').val() == 1 || $('#HiddenScheme').val() == "1") {
        if ((wardname == "OP Insurance")) {
            $('#btnApplyToAllWard').attr('disabled', true);
        }
        else {
            $('#btnApplyToAllWard').attr('disabled', false);
        }
       
        $('#divBillingClassSelectOption').hide();
    }

    $('#btnSave').attr('disabled', false);
   
   // $('#HiddenScheme').val(isscheme);
    isApplied = false;

    var typedata = {
        Dml_Indicator: 'BSC',
        category_dept_id: $('#selCategoryorDept').val(),
        sub_category_dept_id: $('#selSubCategoryorDept').val(),
        branch_id: $('#selBranchName').val(),
        master_service_type: $('#chooseServiceType').val(),
        billing_class: $('#selBillingClass').val(),
        wardid: $('#selWard').val(),
        scheme: $('#HiddenScheme').val(),
        master_service_id: $('#txtServiceID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typedata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                debugger;
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#tblFromServicesList').empty();
                    $('#tblToServicesList').empty();
                    if (data.Table.length > 0) {

                       
                        var thead = ""; var tr = "";
                        for (var i = 0; i < data.Table.length; i++) {

                            thead = "<thead><tr><th><input type='checkbox' class='chkAllServices'/></th><th style='display:none'>PriceMatrixID</th><th style='display:none'>ServiceMasterID</th><th>S.No</th><th>Service Name</th><th>Base Amount</th><th>Actual Amount </th></tr></thead>";
                            var SerName = data.Table[i].service_name
                            if (data.Table[i].base_amount_type == 5 && data.Table[i].ward_name) {
                                SerName = data.Table[i].service_name + '<span class="red"> (' + data.Table[i].ward_name + ')</span>'
                            }
                            tr = tr + '<tr><td><input type="checkbox" class="chkServices chkrow_' + (i + 1) + '" name="chkrow_' + (i + 1) + '"/></td><td style="display:none">' + ((data.Table[i].price_matrix_id == null || data.Table[i].price_matrix_id == "") ? "" : data.Table[i].price_matrix_id) + '</td><td style="display:none">' + data.Table[i].master_service_id + '</td><td>' + (i + 1) + '</td><td class="tbl-name">' + SerName + '<span class="tbl_pno">' + data.Table[i].service_code + '</span></td><td>' + data.Table[i].base_amount_value + '</td><td>' + ((data.Table[i].actual_amount != null && data.Table[i].actual_amount != "") ? data.Table[i].actual_amount : "") + '</td></tr>';

                        }

                        $('#tblFromServicesList').append(thead + '<tbody>' + tr + '<tbody>');
                        $('#tblToServicesList').append(thead + '<tbody>' + tr + '<tbody>');



                    }
                    else {
                        if ($('#HiddenScheme').val() == 1 || $('#HiddenScheme').val() == "1") {

                            toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'No services mapped with this scheme.',
                          {
                              closeButton: true,
                              progressBar: true,
                              allowHtml: true,
                              timeOut: 20000000

                          })
                            return false;
                        }
                    }
                        
                   

                    if (data.Table1.length > 0) {
                        $('#selOtherBillingClass').empty();
                        var SelOption = '';

                        for (var i = 0; i < data.Table1.length; i++) {
                            if (data.Table1[i].master_service_name != "OP" && data.Table1[i].master_service_name != "HOMECARE") {
                               
                                SelOption = SelOption + '<option value="' + data.Table1[i].master_servie_type_id + '">' + data.Table1[i].master_service_name + '</option>';
                            }
                        }

                        $('#selOtherBillingClass').append(SelOption);
                    }
                }
            }
        }
    });

}

$('#tblFromServicesList').on('change', '.chkAllServices', function () {
   
    var checkstatus = this.checked;
    $('.chkServices').prop('checked', checkstatus);   
});

$('#tblToServicesList').on('change', '.chkAllServices', function () {

    var checkstatus = this.checked;
    $('.chkServices').prop('checked', checkstatus);
});

$('#tblFromServicesList').on('change', '.chkServices', function () {

    var checkstatus = this.checked;
    var name = this.name;
    $('#tblToServicesList tr').find("input:checkbox[name=" + name + "]").prop('checked', checkstatus);
  

});

$('#tblToServicesList').on('change', '.chkServices', function () {

    var checkstatus = this.checked;
    var name = this.name;
    $('#tblFromServicesList tr').find("input:checkbox[name=" + name + "]").prop('checked', checkstatus);


});

$("#tblsearch").on("keyup", function () {
    var value = $(this).val().toLowerCase();
    $("#tblFromServicesList tbody tr").filter(function () {
        if (($(this).text().toLowerCase().indexOf(value)) > -1) {
            $(this).show();
        }
        else {
            $(this).hide();
        }
       
    });

    $("#tblToServicesList tbody tr").filter(function () {
        if (($(this).text().toLowerCase().indexOf(value)) > -1) {
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });
});


function ShowZeroRsServices() {

    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
        return false;
    }

   
    if ($('#selBillingClass').val() == null || $('#selBillingClass').val() == "" || $('#selBillingClass').val() == "0") {
        $('#PselBillingClass').show();
        $('#PselBillingClass').fadeOut(8000);
        $('#PselBillingClass').html('Select Billing Class');
        $('#selBillingClass').val('');
        $('#selBillingClass').focus();
        return false;
    }

    
    var billing_class_name = $('#selBillingClass :selected').text();
    var wardname = $('#selWard :selected').text();

    if ((billing_class_name == "OP" || billing_class_name == "HOMECARE" || billing_class_name == "Healthcare Professional") || (wardname == "OP Insurance")) {
        $('#btnApplyToAllWard').attr('disabled', true);
        isOPHomeCare = true;
        $('#divBillingClassSelectOption').hide();
    }
    else {
        $('#btnApplyToAllWard').attr('disabled', false);
        $('#divBillingClassSelectOption').show();
    }

    if ($('#HiddenScheme').val() == 1 || $('#HiddenScheme').val() == "1") {
        if ((wardname == "OP Insurance")) {
            $('#btnApplyToAllWard').attr('disabled', true);
        }
        else {
            $('#btnApplyToAllWard').attr('disabled', false);
        }

        $('#divBillingClassSelectOption').hide();
    }

    $('#btnSave').attr('disabled', false);

    
    isApplied = false;

    var typedata = {
        Dml_Indicator: 'ZSC',
        category_dept_id: $('#selCategoryorDept').val(),
        sub_category_dept_id: $('#selSubCategoryorDept').val(),
        branch_id: $('#selBranchName').val(),
        master_service_type: $('#chooseServiceType').val(),
        billing_class: $('#selBillingClass').val(),
        wardid: $('#selWard').val(),
        scheme: $('#HiddenScheme').val(),
        master_service_id: $('#txtServiceID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(typedata),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                debugger;
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#tblFromServicesList').empty();
                    $('#tblToServicesList').empty();
                    if (data.Table.length > 0) {


                        var thead = ""; var tr = "";
                        for (var i = 0; i < data.Table.length; i++) {
                            var SerName = data.Table[i].service_name
                            if (data.Table[i].base_amount_type == 5 && data.Table[i].ward_name) {
                                SerName = data.Table[i].service_name + '<span class="red"> (' + data.Table[i].ward_name + ')</span>'
                            }
                            thead = "<thead><tr><th style='display:none'>PriceMatrixID</th><th style='display:none'>ServiceMasterID</th><th style='display:none'></th><th>S.No</th><th>Service Name</th><th>Base Amount</th><th>Actual Amount </th></tr></thead>";
                            tr = tr + '<tr><td style="display:none">' + ((data.Table[i].price_matrix_id == null || data.Table[i].price_matrix_id == "") ? "" : data.Table[i].price_matrix_id) + '</td><td style="display:none">' + data.Table[i].master_service_id + '</td><td style="display:none"><input type="checkbox" id="service_' + (i + 1) + '" name="service_' + (i + 1) + '" value="' + data.Table[i].master_service_id + '"></td><td>' + (i + 1) + '</td><td class="tbl-name">' + SerName + '<span class="tbl_pno">' + data.Table[i].service_code + '</span></td><td>' + data.Table[i].base_amount_value + '</td><td>' + ((data.Table[i].actual_amount != null && data.Table[i].actual_amount != "") ? data.Table[i].actual_amount : "") + '</td></tr>';

                        }

                        $('#tblFromServicesList').append(thead + '<tbody>' + tr + '<tbody>');
                        $('#tblToServicesList').append(thead + '<tbody>' + tr + '<tbody>');

                    }
                    else {
                        if ($('#HiddenScheme').val() == 1 || $('#HiddenScheme').val() == "1") {

                            toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'No services mapped with this scheme.',
                          {
                              closeButton: true,
                              progressBar: true,
                              allowHtml: true,
                              timeOut: 20000000

                          })
                            return false;
                        }
                    }



                    if (data.Table1.length > 0) {
                        $('#selOtherBillingClass').empty();
                        var SelOption = '';

                        for (var i = 0; i < data.Table1.length; i++) {
                            if (data.Table1[i].master_service_name != "OP" && data.Table1[i].master_service_name != "HOMECARE") {
                             
                                SelOption = SelOption + '<option value="' + data.Table1[i].master_servie_type_id + '">' + data.Table1[i].master_service_name + '</option>';
                            }
                        }

                        $('#selOtherBillingClass').append(SelOption);
                    }
                }
            }
        }
    });

}

$('#txtAmount').keyup(function () {
    if ($('#HiddenScheme').val() != "1" && $('#HiddenScheme').val() != 1) {
        numeric_dot(this.id);
    }
    
});



$('#chkBillingClass').change(function () {
    
    if ($('#chkBillingClass').prop('checked')) {
        $('#divselBillingClass').show();
        $('#btnApplyToAllWard').attr('disabled', true);
    }
    else {
        $('#divselBillingClass').hide();
        $('#btnApplyToAllWard').attr('disabled', false);
    }
});


var isFilterApplied = false;


$('#txtAmount').on('change', function () {
    if ($('#txtAmount').val() != null && $('#txtAmount').val() != "" && $('#selAmountType').val()==2) {
        var amount = $('#txtAmount').val();
        if (parseFloat(amount) <= 0 || parseFloat(amount) > 100) {
            $('#PtxtAmount').show();
            $('#PtxtAmount').fadeOut(8000);
            $('#PtxtAmount').html('Invalid Percentage');
            $('#txtAmount').val('');
            $('#txtAmount').focus();
            return false;
        }
    }
});

$('#selAmountType').change(function () {
    if ($('#selAmountType').val() != null && $('#selAmountType').val() != "" && $('#selAmountType').val() == 2)
    if ($('#txtAmount').val() != null && $('#txtAmount').val() != "") {
        var amount = $('#txtAmount').val();
        if (parseFloat(amount) <= 0 || parseFloat(amount) > 100) {
            $('#PtxtAmount').show();
            $('#PtxtAmount').fadeOut(8000);
            $('#PtxtAmount').html('Invalid Percentage');
            $('#txtAmount').val('');
            $('#txtAmount').focus();
            return false;
        }
    }
});


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

    if ($('#deFromDate').val() == '' || $('#deFromDate').val() == null) {
        $('#PdeFromDate').show();
        $('#PdeFromDate').fadeOut(8000);
        $('#PdeFromDate').html('Select From Date');
        $('#deFromDate').val('');
        $('#deFromDate').focus();
        return false;
    }

    if ($('#txtType').val() == '' || $('#txtType').val() == null || $('#txtType').val() == 0) {
        $('#PtxtType').show();
        $('#PtxtType').fadeOut(8000);
        $('#PtxtType').html('Select Type');
        $('#txtType').val('');
        $('#txtType').focus();
        return false;
    }

    if ($('#txtAmount').val() == '' || $('#txtAmount').val() == null) {
        $('#PtxtAmount').show();
        $('#PtxtAmount').fadeOut(8000);
        $('#PtxtAmount').html('Enter Amount');
        $('#txtAmount').val('');
        $('#txtAmount').focus();
        return false;
    }

    if ($('#selAmountType').val() == '' || $('#selAmountType').val() == null || $('#selAmountType').val() == 0) {
        $('#PselAmountType').show();
        $('#PselAmountType').fadeOut(8000);
        $('#PselAmountType').html('Select Amount Type');
        $('#selAmountType').val('');
        $('#selAmountType').focus();
        return false;
    }

    if ($("#tblToServicesList tr").length <= 0) {
        //alert("There is no services available");
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services available',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000,

                      })
        return false;
    }

    if ($("#tblToServicesList tbody tr").find('.chkServices:checked').length <= 0) {
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services selected in the list',
                     {
                         closeButton: true,
                         progressBar: true,
                         allowHtml: true,
                         timeOut: 20000000,

                     })
        return false;
    }

    isApplied = true;

    $("#tblToServicesList tr").each(function () {

        if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {
            var current_amount = 0;
            var actual_calculate_amount = 0;

            if ($('#txtType').val() == "1") {
                current_amount = $(this).find("td").eq(5).html();

            }
            else {
                current_amount = $(this).find("td").eq(6).html();
            }

            if (current_amount == null || current_amount == "") {  //altered by nandhini on 03/11/2023
                $(this).find("td").eq(6).html(current_amount);
                //current_amount = 0;
            }
            else {

                var percentageamount = 0;
                if ($('#selAmountType').val() == 1) {
                    percentageamount = $('#txtAmount').val();
                }
                else {
                    percentageamount = (parseFloat($('#txtAmount').val()) / 100) * parseFloat(current_amount);
                }

                actual_calculate_amount = parseFloat(current_amount) + parseFloat(percentageamount);

                if ($('#RoundOffType').val() == 1) {
                    actual_calculate_amount = Math.round(actual_calculate_amount);
                }
                else {
                    actual_calculate_amount = actual_calculate_amount.toFixed(2);
                }
                $(this).find("td").eq(6).html(actual_calculate_amount);
            }
        }

        });
    

});

$('#btnSave').click(function () {
    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
        return false;
    }
    if ($('#selBillingClass').val() == null || $('#selBillingClass').val() == "" || $('#selBillingClass').val() == "0") {
        $('#PselBillingClass').show();
        $('#PselBillingClass').fadeOut(8000);
        $('#PselBillingClass').html('Select Billing Class');
        $('#selBillingClass').val('');
        $('#selBillingClass').focus();
        return false;
    }

    if ($('#selWard').val() == null || $('#selWard').val() == "" || $('#selWard').val() == "0") {
        $('#PselWard').show();
        $('#PselWard').fadeOut(8000);
        $('#PselWard').html('Select Ward');
        $('#selWard').val('');
        $('#selWard').focus();
        return false;
    }

    if ($('#deFromDate').val() == '' || $('#deFromDate').val() == null) {
        $('#PdeFromDate').show();
        $('#PdeFromDate').fadeOut(8000);
        $('#PdeFromDate').html('Select From Date');
        $('#deFromDate').val('');
        $('#deFromDate').focus();
        return false;
    }

    if ($('#txtType').val() == '' || $('#txtType').val() == null || $('#txtType').val() == 0) {
        $('#PtxtType').show();
        $('#PtxtType').fadeOut(8000);
        $('#PtxtType').html('Select Type');
        $('#txtType').val('');
        $('#txtType').focus();
        return false;
    }

    if ($('#txtAmount').val() == '' || $('#txtAmount').val() == null) {
        $('#PtxtAmount').show();
        $('#PtxtAmount').fadeOut(8000);
        $('#PtxtAmount').html('Enter Amount');
        $('#txtAmount').val('');
        $('#txtAmount').focus();
        return false;
    }

    if ($('#selAmountType').val() == '' || $('#selAmountType').val() == null || $('#selAmountType').val() == 0) {
        $('#PselAmountType').show();
        $('#PselAmountType').fadeOut(8000);
        $('#PselAmountType').html('Select Amount Type');
        $('#selAmountType').val('');
        $('#selAmountType').focus();
        return false;
    }

   

    $('#btnApplyToAllWard').attr('disabled', true);

    if (isApplied == false) {
        toastr.info("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'No changes detected',
                     {
                         closeButton: true,
                         progressBar: true,
                         allowHtml: true,
                         timeOut: 20000000
                     })
       
        if (!isOPHomeCare) {
            $('#btnApplyToAllWard').attr('disabled', false);
        }
        return false;
    }
    
    if ($("#tblToServicesList tr").length <= 0) {
        
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services available',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000,

                          onShown: function (toast) {
                              $("#confirmationRevertYes").click(function () {
                              })
                          }
                      })
        if (!isOPHomeCare) {
            $('#btnApplyToAllWard').attr('disabled', false);
        }
        return false;
    }

    if ($("#tblToServicesList tbody tr").find('.chkServices:checked').length <= 0) {

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services selected in this list',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000,

                          onShown: function (toast) {
                              $("#confirmationRevertYes").click(function () {
                              })
                          }
                      })
        if (!isOPHomeCare) {
            $('#btnApplyToAllWard').attr('disabled', false);
        }
        return false;
    }

    var priceArray = new Array();
    var from_date = $('#deFromDate').val();
    var dates = from_date.split('/');
    from_date = dates[2] + '-' + dates[1] + '-' + dates[0];
   
    var billingClassList = $('#selOtherBillingClass').val().toString();
    debugger;
    if ($('#chkBillingClass').prop('checked') && billingClassList.length > 0) {

        //save price based on selected billing classes
        var billingClassListSplitUp = billingClassList.split(',');
        if (billingClassListSplitUp.length > 0)
        {
            for (i = 0; i < billingClassListSplitUp.length; i++) {

                $("#tblToServicesList tbody tr").each(function () {

                    if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {

                        if ($(this).find("td").eq(6).html() != null && $(this).find("td").eq(6).html() !== "" && $(this).find("td").eq(6).html() != "0.00") {
                            var customer = {};

                            customer.price_matrix_id = $(this).find("td").eq(1).html();
                            customer.master_service_id = $(this).find("td").eq(2).html(),
                            customer.billing_class = billingClassListSplitUp[i],
                             customer.loyalty_class = "",
                             customer.from_date = from_date,
                             customer.base_amount = $(this).find("td").eq(5).html(),
                             customer.actual_amount = $(this).find("td").eq(6).html(),
                            customer.wardid = $('#selWard').val(),
                            customer.created_by = $('#hiddenUser_id').val(),
                            customer.Dml_Indicator = "I",
                            customer.hospital_id = $('#HospitalId').val(),
                            customer.branch_id = $('#selBranchName').val()

                            priceArray.push(customer);
                        }
                    }
                });                

            }

            $("#tblToServicesList tbody tr").each(function () {
                if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {
                    if ($(this).find("td").eq(6).html() != null && $(this).find("td").eq(6).html() !== "" && $(this).find("td").eq(6).html() != "0.00") {
                        var customer = {};

                        customer.price_matrix_id = $(this).find("td").eq(1).html();
                        customer.master_service_id = $(this).find("td").eq(2).html(),
                        customer.billing_class = $('#selBillingClass').val(),
                         customer.loyalty_class = "",
                         customer.from_date = from_date,
                         customer.base_amount = $(this).find("td").eq(5).html(),
                         customer.actual_amount = $(this).find("td").eq(6).html(),
                        customer.wardid = $('#selWard').val(),
                        customer.created_by = $('#hiddenUser_id').val(),
                        customer.Dml_Indicator = "I",
                        customer.hospital_id = $('#HospitalId').val(),
                        customer.branch_id = $('#selBranchName').val()

                        priceArray.push(customer);
                    }
                }
            });
        }
        
       
    }
    else {

        

        $("#tblToServicesList tbody tr").each(function () {
            if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {
                if ($(this).find("td").eq(6).html() != null && $(this).find("td").eq(6).html() !== "" && $(this).find("td").eq(6).html() != "0.00") {
                    var customer = {};

                    customer.price_matrix_id = $(this).find("td").eq(1).html();
                    customer.master_service_id = $(this).find("td").eq(2).html(),
                    customer.billing_class = $('#selBillingClass').val(),
                     customer.loyalty_class = "",
                     customer.from_date = from_date,
                     customer.base_amount = $(this).find("td").eq(5).html(),
                     customer.actual_amount = $(this).find("td").eq(6).html(),
                    customer.wardid = $('#selWard').val(),
                    customer.created_by = $('#hiddenUser_id').val(),
                    customer.Dml_Indicator = "I",
                    customer.hospital_id = $('#HospitalId').val(),
                    customer.branch_id = $('#selBranchName').val()

                    priceArray.push(customer);
                }
            }
        });
    }
   

    console.log(priceArray);

   
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(priceArray),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {             
                toastr.success('Saved Successfully',
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })
                
               
            }
        }
    });
});


function ClearAll() {
    $('#selBillingClass').val(0);
    $('#selWard').val(0);
    $('#selWard').attr('disabled', false);
    $('#selCategoryorDept').val("");
    $('#selSubCategoryorDept').val("")
    $('#chkBillingClass').prop('checked', false);
    $('#chkBillingClass').change();

    $('#RoundOffType').val(2);
    $('#btnSave').attr('disabled', false);
    $('#deFromDate').val("");
    $('#txtType').val(0);
    $('#txtAmount').val("");
    $('#HiddenScheme').val(0);
    isApplied = false;
    $('#tblFromServicesList').empty();
    $('#tblToServicesList').empty();
    $('#txtServiceID').val('');
}



//commented by nandhini on 15/11/23 for medway requirement apply to all ward for selected rows
//$('#btnApplyToAllWard').click(function () {
//    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
//        $('#PselBranchName').show();
//        $('#PselBranchName').fadeOut(8000);
//        $('#PselBranchName').html('Select Branch Name');
//        $('#selBranchName').val('');
//        $('#selBranchName').focus();
//        return false;
//    }
//    if ($('#selBillingClass').val() == null || $('#selBillingClass').val() == "" || $('#selBillingClass').val() == "0") {
//        $('#PselBillingClass').show();
//        $('#PselBillingClass').fadeOut(8000);
//        $('#PselBillingClass').html('Select Billing Class');
//        $('#selBillingClass').val('');
//        $('#selBillingClass').focus();
//        return false;
//    }

//    if ($('#selWard').val() == null || $('#selWard').val() == "" || $('#selWard').val() == "0") {
//        $('#PselWard').show();
//        $('#PselWard').fadeOut(8000);
//        $('#PselWard').html('Select Ward');
//        $('#selWard').val('');
//        $('#selWard').focus();
//        return false;
//    }

//    if ($('#deFromDate').val() == '' || $('#deFromDate').val() == null) {
//        $('#PdeFromDate').show();
//        $('#PdeFromDate').fadeOut(8000);
//        $('#PdeFromDate').html('Select From Date');
//        $('#deFromDate').val('');
//        $('#deFromDate').focus();
//        return false;
//    }

//    if ($('#txtType').val() == '' || $('#txtType').val() == null || $('#txtType').val() == 0) {
//        $('#PtxtType').show();
//        $('#PtxtType').fadeOut(8000);
//        $('#PtxtType').html('Select Type');
//        $('#txtType').val('');
//        $('#txtType').focus();
//        return false;
//    }

//    if ($('#txtAmount').val() == '' || $('#txtAmount').val() == null) {
//        $('#PtxtAmount').show();
//        $('#PtxtAmount').fadeOut(8000);
//        $('#PtxtAmount').html('Enter Amount');
//        $('#txtAmount').val('');
//        $('#txtAmount').focus();
//        return false;
//    }

//    if ($('#selAmountType').val() == '' || $('#selAmountType').val() == null || $('#selAmountType').val() == 0) {
//        $('#PselAmountType').show();
//        $('#PselAmountType').fadeOut(8000);
//        $('#PselAmountType').html('Select Amount Type');
//        $('#selAmountType').val('');
//        $('#selAmountType').focus();
//        return false;
//    }

//    $('#btnSave').attr('disabled', true);

//    if (isApplied == false) {
//        toastr.info("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'No changes detected',
//                     {
//                         closeButton: true,
//                         progressBar: true,
//                         allowHtml: true,
//                         timeOut: 20000000
//                     })
//        $('#btnSave').attr('disabled', false);
//        return false;
//    }
   
//    var Dml_Indicator = "";
//    if (isFilterApplied && ($('#selServiceType').val() != 0 || $('#selServices').val() != 0)) {
//        if ($('#SelectedCategoryType').val() == "1") {  //category and department based
//            Dml_Indicator = (($('#selServices').val() == '' || $('#selServices').val() == null || $('#selServices').val() == 0) && $('#selServiceType').val() != 0) ? "TFC" : "SFC"
//        }
//        else {
//            Dml_Indicator = (($('#selServices').val() == '' || $('#selServices').val() == null || $('#selServices').val() == 0) && $('#selServiceType').val() != 0) ? "TFS" : "SFS"              //sub category and sub department based
//        }
//    }
//    else {

//        if ($('#selSubCategoryorDept').val() == null || $('#selSubCategoryorDept').val() == "" || $('#selSubCategoryorDept').val()==0) {  //category and department and filter based
//            Dml_Indicator = "APC"
//        }
//        else {
//            Dml_Indicator = "APS"              //sub category and sub department and filter based
//        }

        
//    }

//    var from_date = $('#deFromDate').val();
//    var dates = from_date.split('/');
//    from_date = dates[2] + '-' + dates[1] + '-' + dates[0];


//    var typedata = {
//        Dml_Indicator: Dml_Indicator,
//        category_dept_id: $('#selCategoryorDept').val(),
//        sub_category_dept_id: $('#selSubCategoryorDept').val(),
//        amount_type: $('#selAmountType').val(),
//        amount: $('#txtAmount').val(),
//        round_off: $('#RoundOffType').val(),
//        type: $('#txtType').val(),
//        from_date: from_date,
//        created_by: $('#hiddenUser_id').val(),
//        branch_id: $('#selBranchName').val(),
//        //master_service_type: $('#selServiceType').val(),
//        master_service_id: $('#txtServiceID').val(),
//        billing_class: $('#selBillingClass').val(),
//        scheme: $('#HiddenScheme').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/BillingMaster/Price_Matrix_Sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(typedata),
//        success: function (data) {
//            var data = JSON.parse(data);
//            if (data.msg == "Success") {

//                toastr.success('Price applied to all ward successfully for this billing class',
//                       {
//                           closeButton: false,
//                           progressBar: true,
//                           allowHtml: true,
//                           timeOut: 0,
//                       })
               
//            }
//        }
//    });
//});



$('#btnApplyToAllWard').click(function () {
    if ($('#selBranchName').val() == null || $('#selBranchName').val() == "" || $('#selBranchName').val() == "0") {
        $('#PselBranchName').show();
        $('#PselBranchName').fadeOut(8000);
        $('#PselBranchName').html('Select Branch Name');
        $('#selBranchName').val('');
        $('#selBranchName').focus();
        return false;
    }
    if ($('#selBillingClass').val() == null || $('#selBillingClass').val() == "" || $('#selBillingClass').val() == "0") {
        $('#PselBillingClass').show();
        $('#PselBillingClass').fadeOut(8000);
        $('#PselBillingClass').html('Select Billing Class');
        $('#selBillingClass').val('');
        $('#selBillingClass').focus();
        return false;
    }

    if ($('#selWard').val() == null || $('#selWard').val() == "" || $('#selWard').val() == "0") {
        $('#PselWard').show();
        $('#PselWard').fadeOut(8000);
        $('#PselWard').html('Select Ward');
        $('#selWard').val('');
        $('#selWard').focus();
        return false;
    }

    if ($('#deFromDate').val() == '' || $('#deFromDate').val() == null) {
        $('#PdeFromDate').show();
        $('#PdeFromDate').fadeOut(8000);
        $('#PdeFromDate').html('Select From Date');
        $('#deFromDate').val('');
        $('#deFromDate').focus();
        return false;
    }

    if ($('#txtType').val() == '' || $('#txtType').val() == null || $('#txtType').val() == 0) {
        $('#PtxtType').show();
        $('#PtxtType').fadeOut(8000);
        $('#PtxtType').html('Select Type');
        $('#txtType').val('');
        $('#txtType').focus();
        return false;
    }

    if ($('#txtAmount').val() == '' || $('#txtAmount').val() == null) {
        $('#PtxtAmount').show();
        $('#PtxtAmount').fadeOut(8000);
        $('#PtxtAmount').html('Enter Amount');
        $('#txtAmount').val('');
        $('#txtAmount').focus();
        return false;
    }

    if ($('#selAmountType').val() == '' || $('#selAmountType').val() == null || $('#selAmountType').val() == 0) {
        $('#PselAmountType').show();
        $('#PselAmountType').fadeOut(8000);
        $('#PselAmountType').html('Select Amount Type');
        $('#selAmountType').val('');
        $('#selAmountType').focus();
        return false;
    }

    $('#btnSave').attr('disabled', true);

    if (isApplied == false) {
        toastr.info("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'No changes detected',
                     {
                         closeButton: true,
                         progressBar: true,
                         allowHtml: true,
                         timeOut: 20000000
                     })
        $('#btnSave').attr('disabled', false);
        return false;
    }

    if ($("#tblToServicesList tr").length <= 0) {

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services available',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000,

                          onShown: function (toast) {
                              $("#confirmationRevertYes").click(function () {
                              })
                          }
                      })
        $('#btnSave').attr('disabled', false);
        return false;
    }

    if ($("#tblToServicesList tbody tr").find('.chkServices:checked').length <= 0) {

        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services selected in this list',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 20000000,

                          onShown: function (toast) {
                              $("#confirmationRevertYes").click(function () {
                              })
                          }
                      })
        $('#btnSave').attr('disabled', false);
        return false;
    }

    var Dml_Indicator = "MI";
   
    var from_date = $('#deFromDate').val();
    var dates = from_date.split('/');
    from_date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var priceArray = new Array();


    $("#tblToServicesList tbody tr").each(function () {
        if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {
            if ($(this).find("td").eq(6).html() != null && $(this).find("td").eq(6).html() !== "" && $(this).find("td").eq(6).html() != "0.00") {
                var customer = {};

                customer.price_matrix_id = $(this).find("td").eq(1).html();
                customer.master_service_id = $(this).find("td").eq(2).html(),
                customer.billing_class = $('#selBillingClass').val(),
                 customer.loyalty_class = "",
                 customer.from_date = from_date,
                 customer.base_amount = $(this).find("td").eq(5).html(),
                 customer.actual_amount = $(this).find("td").eq(6).html(),
                customer.wardid = $('#selWard').val(),
                customer.created_by = $('#hiddenUser_id').val(),
                customer.Dml_Indicator = "MI",
                customer.hospital_id = $('#HospitalId').val(),
                customer.branch_id = $('#selBranchName').val()

                priceArray.push(customer);
            }
        }
    });

    console.log(priceArray);

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Price_Matrix_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(priceArray),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                toastr.success('Price applied to all ward successfully for this billing class',
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })


            }
        }
    });


});


//load visit type
function loadvisit_type() {
    debugger;
    var data = {
        P_Dml_Indicator: 'PMT'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {
                    $('#chooseServiceType').empty();                    
                    var option = "";
                    var data1 = data2.data;
                    var default_option = '<option value="0">All Service Type</option>';                   
                    $.each(data1, function (i, emp) {
                        option = option + '<option value="' + emp.service_typeid + '">' + emp.visit_type_name + '</option>';
                    })
                    $('#chooseServiceType').append(default_option + option);
                   

                }
            }
        }
    })
}