var billing_type = "";   //op 1, ip 2
var billing_no = "";
var sym_rupee = '<span class="sym_rupee">₹</span>'
var sym_per = '<span class="sym_rupee">%</span>'
var Service_Org_Arr = [];
var toastStatus = 0;
$(document).ready(function () {
    debugger
    Hideshow();
    var value_op = '';
    if ($('#HEstimateId').val() != '0' && $('#HEstimateId').val()) {
        billing_type = 4;
       
    }
   
        var op_val = $('#op_daycare_val').val()


        //LoadVisitType();
        $('#divSelDoctor').hide();
        $('#divSelDoctorth').hide();
        debugger;
        var visit_report_id = $('#hdnvisit_report_id').val();
        billing_no = $('#hndbilling_no').val();
        var request_id = $('#hdnrequest_id').val();
        if ((visit_report_id == "" || visit_report_id == null) && billing_no == "" && !$('#HEstimateId').val()) {
            billing_type = 1;
        }
        else if ($('#hndType').val() != null && $('#hndType').val() != '' && $('#hndType').val() == '1' && !$('#HEstimateId').val()) {  // added by nandhini for dashboard quick bill redirect
            billing_type = 3;
            LoadVisitType('', 1);
        }
        else if ($('#hndType').val() != null && $('#hndType').val() != '' && $('#hndType').val() == '2' && !$('#HEstimateId').val()) {  // added by nandhini for audiologists raise bill redirect
            billing_type = 6;
            LoadVisitType('', 11);
        }
        else {
            if(!$('#HEstimateId').val())
            billing_type = 2;
        }
        if (op_val != '') {

            value_op = op_val
            LoadVisitType(value_op);
        }
        else {
            if (billing_type != 2 && ($('#hdnvisit_report_id').val() == null || $('#hdnvisit_report_id').val() == '') && ($('#hndbilling_no').val() == null || $('#hndbilling_no').val() == '') && !$('#HEstimateId').val()) {
                LoadVisitType();
            }
        }
        if (billing_type == 1) {
            $('.ip-strip').hide();
            $('.pat-stripe-bgop').hide();
            $('.patient-details-wrap').show();
        }
        else {
            $('.op-strip').hide();
            $('.pat-stripe-bgop').hide();
            if (!$('#HEstimateId').val()){
         
            $('.patient-details-wrap').hide();
            $('#billingDetailsWrap').hide();
                }
        }
        // //LoadDoctor();

        LoadBranch();

        debugger;
        //Added by Antony
        var ipop_patient_id = $('#op_daycare_patientid').val()
        var En_pat_id = $('#H_En_patient_id').val()
        $('#txtPaitentSearch_bill').val(ipop_patient_id);
        $('#hdnpatientapp').val(En_pat_id)

        var reg_branchid = $('#register_branchid').val();
        if ($('#op_daycare_val').val() != '' && ($('#hndbilling_no').val() == 0 || $('#hndbilling_no').val() == '')) {
            authorized_person(0, reg_branchid)
            //LoadPayment_Type(reg_branchid)
        }
        LoadPayment_Type();//one master concept
        $('#approve_date').val(moment(new Date()).format('DD/MM/YYYY'))

    $('#opd_number').on('change', function () {
        // Get selected value
        var opdNumberWithDate = $(this).val();
        // Extract the part before the hyphen
        var opdNumber = opdNumberWithDate ? opdNumberWithDate.split('-')[0] : '';
        // Update hidden input field
        $('#selected_opd_number').val(opdNumber);
    });

    // Optionally, initialize hidden input field if dropdown has a pre-selected value
    var initialOpdNumberWithDate = $('#opd_number').val();
    if (initialOpdNumberWithDate) {
        var initialOpdNumber = initialOpdNumberWithDate.split('-')[0];
        $('#selected_opd_number').val(initialOpdNumber);
    }

});
function LoadOpdnumber() {
    var Opdnumber = {
        Dml_Indicator: "OPD",
        patient_id: $('#hdnpatientapp').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_visit_report_creation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Opdnumber),
        success: function (data) {
            var data1 = JSON.parse(data);

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

                if (!jQuery.isEmptyObject(data1) && data1.Table.length > 0) {
                    // Populate options if data is available
                    OpdnumberOptions = '<option>--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        var formattedOpdNumber = formatOpdNumber(emp.opd_number, emp.created_on);
                        OpdnumberOptions += '<option value="' + formattedOpdNumber + '">' + formattedOpdNumber + '</option>';
                    });
                } else {
                    OpdnumberOptions = '<option disabled>No OPD numbers for this patient</option>';
                }

                $('#opd_number').html(OpdnumberOptions);
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX error:', status, error);
        }
    });
}


function formatOpdNumber(opd_number, created_on) {
    var date = new Date(created_on);
    var day = String(date.getDate()).padStart(2, '0');
    var month = String(date.getMonth() + 1).padStart(2, '0'); // Month is zero-based
    var year = date.getFullYear();

    return opd_number + '-' + day + '/' + month + '/' + year;
}


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;
                    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) {
                        $('#pkg_branch_id').append(SubDepartment);
                        $('#pkg_branch_id').change();
                    }
                    else {
                        $('#pkg_branch_id').append(default_opt + SubDepartment);
                    }
                    if ($('#FPatientid').val() != '' && $('#FBranchid').val() != '') {
                        $('#pkg_branch_id').val($('#FBranchid').val());
                        $('#pkg_branch_id').change();
                        loadPatient($('#FPatientid').val());
                    }

                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //    $('#pkg_branch_id').change();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#pkg_branch_id').change();
                    }
                    debugger;

                    if ($('#hndbranch').val() != null && $('#hndbranch').val() != '') {
                        $('#pkg_branch_id').val($('#hndbranch').val());
                        $('#pkg_branch_id').change();
                    }

                    //Added by Antony
                    if ($('#register_branchid').val() != '' && $('#register_branchid').val() != 0) {
                        $('#pkg_branch_id').val($('#register_branchid').val());
                        $('#pkg_branch_id').prop('disabled', true)
                       //- LoadDoctor();
                    }

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

            debugger;
            if ($('#hndbilling_copy_no').val() != '' && $("#hndbilling_copy_no").val() != 0) {
                bill_copy_edit();
            }
            if (billing_type == 2) {
                if (billing_no != "" && billing_no != null) {
                    billing_edit();
                }
                else {
                    request_details();
                }
            }
            else if (billing_type == 3) {  // added by nandhini on 09/08/2022 for dashboard quick bill
                LoadVisitType('', 1);
                $('#hdnpatientapp').val($('#hndpatientid').val());
                $("input[name='optradio'][value='1']").prop('checked', true);
               var docid = $('#Hd_doctorid').val()
               $('#HdnSelDoctor').val(docid)
               
                var bill = VisitReport_Creation()//PatientSearch($('#hdnpatientapp').val(), '1', $('#pkg_branch_id').val(), $('#hdnvisit_report_id').val());
                $.when(bill)
            .then(function (data3) {
                var da1 = JSON.parse(data3);
                if (da1.msg == "Success") {
                    console.log(data1);
                    da1 = da1.data;
                    $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                    $('#hdn_entity').val(da1[0].entity_id);
                    $('#hdn_is_scheme').val(da1[0].is_scheme);
                }

            });


                $('.pat-stripe-bgop').show();
                $('#billingDetailsWrap').hide();

                if ($('#hndentity').val() == 1 || $('#hndentity').val() == '1') {
                    $('#div_claim').removeClass('hidden');
                    if ($('#hndis_insurance').val() == 2 && $('#hndmultipay').val() == 1) {
                        $('#divclaimType').removeClass('hidden');
                    }
                    else {
                        $('#divclaimType').addClass('hidden');
                    }
                }
                else {
                    $('#div_claim').addClass('hidden');
                }
                $('#His_insurance').val($('#hndentity').val());
            }
            else if (billing_type == 6) {  // added by nandhini on 02/07/2024 for audiologists raise bill

                $('#hdnpatientapp').val($('#hndpatientid').val());
                $("input[name='optradio'][value='11']").prop('checked', true);
                var docid = $('#Hd_doctorid').val()
                $('#HdnSelDoctor').val(docid)
                var dmo = $('#Hd_DMO').val()
                $('#SelAudiologist').val(dmo)
                LoadVisitType('', 11);
                var bill = VisitReport_Creation()//PatientSearch($('#hdnpatientapp').val(), '1', $('#pkg_branch_id').val(), $('#hdnvisit_report_id').val());
                $.when(bill)
            .then(function (data3) {
                var da1 = JSON.parse(data3);
                if (da1.msg == "Success") {
                    console.log(data1);
                    da1 = da1.data;
                    $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                    $('#hdn_entity').val(da1[0].entity_id);
                    $('#hdn_is_scheme').val(da1[0].is_scheme);
                }

            });


                $('.pat-stripe-bgop').show();
                $('#billingDetailsWrap').hide();

                if ($('#hndentity').val() == 1 || $('#hndentity').val() == '1') {
                    $('#div_claim').removeClass('hidden');
                    if ($('#hndis_insurance').val() == 2 && $('#hndmultipay').val() == 1) {
                        $('#divclaimType').removeClass('hidden');
                    }
                    else {
                        $('#divclaimType').addClass('hidden');
                    }
                }
                else {
                    $('#div_claim').addClass('hidden');
                }
                $('#His_insurance').val($('#hndentity').val());
            }
            else if (billing_type == 4) {
                LoadEstimateDetails();
            }
        }
    });
}

function loadPatient(pid) {
    debugger
    var DoctorData = {
        dml_indicator: 'LP',
        patientid: pid,
        billing_details_id: $('#FDMO').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $('#hdnpatientapp').val(data1.Table[0].patient_id);
                    $('#txtPaitentSearch_bill').val(data1.Table[0].search_option);
                    if ($('#FDMO').val() != "" && $('#FDMO').val() != null) {                       
                        
                        $('#SelDoctor').val(data1.Table[0].doctorname).attr('disabled',true);
                        $('#HdnSelDoctor_userid').val($('#FDMO').val());
                        $('#HdnSelDoctor').val('');
                    }
                    //$('#SelDoctor').val(data1.Table[0].last_docname);
                    //$('#HdnSelDoctor').val(data1.Table[0].last_visit_doctor_id_var);
                }
            }
        }
    });
}

//Branch Change
$('#pkg_branch_id').change(function () {
    debugger;
    if ($('#op_daycare_patientid').val() != '') {
        $('#txtPaitentSearch_bill').val($('#op_daycare_patientid').val());
    }
    else {
        $('#txtPaitentSearch_bill').val('');
    }
    // $('#txtPaitentSearch_bill').val('');
    if ($('#pkg_branch_id').val() == 0) {
        $('#txtPaitentSearch_bill').prop('disabled', true);

    }
    else {
        $('#txtPaitentSearch_bill').prop('disabled', false);
    }
   //- LoadDoctor();
    if ($('#hndbilling_no').val() == 0 || $('#hndbilling_no').val() == '') {
        authorized_person();
    }

    LoadUsersList();
   // LoadPayment_Type(); //one master concept
})
function LoadDoctor() {
   // LoadDoctor_Hospital()
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        //Hide DL indicator for Not need referal doctor only show hospital type and visit type doctors
        //Dml_Indicator: "DL",
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('.txt_doctor_name').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('.txt_doctor_name').html(default_opt + SelRole);
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
function LoadDoctor_Hospital() {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#SelDoctor').html(default_opt + SelRole);
                    }

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

function authorized_person(val, reg_branchid) {
    debugger;

    var val_branchid = '';

    if (reg_branchid == '' || reg_branchid == undefined) {
        val_branchid = $('#pkg_branch_id').val()
    }
    else {
        val_branchid = reg_branchid
    }

    if ($('#hdisc_edit_val').val() == 1) {
        var DoctorData = {
            dml_indicator: 'AUE',
            hospital_id: $('#HospitalId').val(),
            branch_id: val_branchid
        }
    }
    else {
        var DoctorData = {
            dml_indicator: 'AU',
            hospital_id: $('#HospitalId').val(),
            branch_id: val_branchid
        }
    }

    //var DoctorData = {
    //    dml_indicator: 'AU',
    //    hospital_id: $('#HospitalId').val(),
    //    branch_id:$('#pkg_branch_id').val()
    //        }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    console.log('data1---------->' + data1.Table);
                    if (data1.Table.length > 0) {
                        debugger;
                        for (var i = 0; i < data1.Table.length; i++) {
                            //SelRole = SelRole + '<option value="' + data1.Table[i].maximum_Discount_authorization + '" data-id="'+ data1.Table[i].maximum_discount_authorization_Type+'">' + data1.Table[i].first_name + '</option>';
                            SelRole = SelRole + '<option value="' + data1.Table[i].doctor_user_id + '" data-id="' + data1.Table[i].maximum_discount_authorization_Type + '" data-id1="' + data1.Table[i].maximum_Discount_authorization + '">' + data1.Table[i].first_name + '</option>';
                        }
                        $('#sel_authorized_person').html(default_opt + SelRole);
                        if (val != null && val != 0) {
                            $('#sel_authorized_person').val(val);
                            if ($('#hdn_wo_otp').val() != 1) {
                                $('#sel_authorized_person').attr('disabled', 'disabled');
                            }
                        }
                    }
                }
            }
        }
    });
}

// Authorized Person dropdrop change function
$('#sel_authorized_person').change(function () {
    debugger;
   
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    var sel_discount_type = "";
    if ($('#sel_authorized_person option:selected').data('id') == 1) {
        sel_discount_type = '₹';
    }
    else {
        sel_discount_type = '%';
    }
    $('#max_percentage').html($('#sel_authorized_person option:selected').data('id1'));
    $('#max_type').html(sel_discount_type);
    $('#txt_tot_discount_amt').val($('#sel_authorized_person option:selected').data('id1'));

    $('#authorized_discount').val($('#sel_authorized_person option:selected').data('id'));
    $('#txt_tot_discount_amt').change();
    if ($('#sel_authorized_person').val() != 0) {
        $('#max_percentage_div').show();
    }
    else {
        $('#max_percentage_div').hide();
    }
})
});


// Authorized Person calculation
$('#txt_tot_discount_amt').change(function () {
    debugger;
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    Authorized_Person_cal();
})

});

//Visit Creation

function VisitReport_Creation() {
    debugger;
    $('#btn_create_visit').prop('disabled', true);
    var visit_type = $("input[name='optradio']:checked").val();
    var patient_id = $('#hdnpatientapp').val();

    var DoctorData = {
        doctor_id: $('#HdnSelDoctor').val(),
        hospital_id: $('#HospitalId').val(),
        patient_id: $('#hdnpatientapp').val(),
        branch_id: $('#pkg_branch_id').val(),
        visit_type: visit_type,
        dml_indicator: 'I',
        is_entity: $('#Entity').val(),
        is_insurance: $('#EntityType').val(),
        insurance_id: $('#HdnEntityid').val(),
        is_pay: $('#CMultiPay').val(),
        corporate_insuranceid: $('#MPCIName').val(),
        employee_name: $('#txt_emp_name').val(),
        employee_code: $('#txt_emp_code').val(),
        referral_doctor: $('#SelReferredDoctor').val(),
        opd_numbers: $('#selected_opd_number').val(),
        user_id: $('#HdnSelDoctor_userid').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_visit_report_creation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            $('#Claim_Details').modal('hide');
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table[0].StrMsg == "visit created") {
                        $('#hdnvisit_report_id').val(data1.Table[0].visit_report_id);
                        if (visit_type == 1 && ($('#selected_opd_number').val() == null || $('#selected_opd_number').val() == "" || $('#selected_opd_number').val()==0)) {
                            $('#selected_opd_number').val(data1.Table[0].opd_number);
                        }
                        var bill = PatientSearch(patient_id, visit_type, $('#pkg_branch_id').val(), data1.Table[0].visit_report_id);
                        $.when(bill)
                    .then(function (data3) {
                        var da1 = JSON.parse(data3);
                        if (da1.msg == "Success") {
                            console.log(data1);
                            da1 = da1.data;
                            $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                            $('#hdn_entity').val(da1[0].entity_id);
                            $('#hdn_is_scheme').val(da1[0].is_scheme);
                            if ($('#HEstimateId').val() != '0' && $('#HEstimateId').val()) {
                                $('#Hwardid').val($('#hndward_id').val());
                                $('#Hbilling_class').val($('#hndbilling_class').val());
                            }
                        }

                    });

                        $('.pat-stripe-bgop').show();
                        $('#billingDetailsWrap').hide();
                        if (data1.Table[0].is_entity == 1) {
                            $('#div_claim').removeClass('hidden');
                            if (data1.Table[0].is_insurance == 2 && data1.Table[0].is_MultiPay == 1) {
                                $('#divclaimType').removeClass('hidden');
                            }
                            else {
                                $('#divclaimType').addClass('hidden');
                            }
                        }
                        else {
                            $('#div_claim').addClass('hidden');
                        }
                        $('#His_insurance').val(data1.Table[0].is_entity);

                    }
                    else {
                        toastr.warning(data1.Table[0].StrMsg);
                        $('#txtPaitentSearch_bill').val('');
                    }

                    if (data1.Table1.length > 0 && !$('#HEstimateId').val()) {
                        var netamount = 0;
                        for (var i = 0; i < data1.Table1.length; i++) {
                            $('#hdnpatientapp').val(patient_id);
                            netamount += data1.Table1[i].total_amount;

                            var rowCount = $('#service_tbl tbody tr').length;
                            if (rowCount == 0) {
                                rowCount = 1
                            }
                            else {
                                var id = $('#service_tbl tbody tr:last').attr('id');
                                id = id.split('_');
                                rowCount = parseInt(id[1]) + (1);
                            }

                            var sel_discount_type = $('.sel_discount_type').val();
                            if (sel_discount_type == 1) {
                                sel_discount_type = '₹';
                            }
                            else {
                                sel_discount_type = '%';
                            }

                            //if (data1.Table1[i].hasOwnProperty('DMO')) {
                            //    if (data1.Table1[i].DMO != null && data1.Table1[i].DMO == null) {
                            //        $('#SelAudiologist').val(data1.Table1[i].DMO);
                            //    }
                            //}

                            var date = new Date();
                            date = moment(date).format('DD/MM/YYYY hh:mm A')
                            var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour(data1.Table1[i].base_amount_type) + '"><td>' + data1.Table1[i].service_name + '</td><td>' + data1.Table1[i].quantity + '</td><td>' + parseFloat(data1.Table1[i].base_amount).toFixed(2) + '</td>'
                            tr += '<td>' + parseFloat(data1.Table1[i].total_amount).toFixed(2) + '</td><td>0' + ' ' + '₹</td><td>0</td><td>0</td><td>' + (parseFloat(data1.Table1[i].total_amount).toFixed(2)) + '</td><td>' + date + '</td><td>' + data1.Table1[i].first_name + '</td><td></td><td class="hide">' + data1.Table1[i].doctor_id + '</td><td class="hide">' + data1.Table1[i].master_service_id + '</td><td class="hide">' + data1.Table1[i].package_id + '</td><td class="hide">' + data1.Table1[i].price_matrix_id + '</td><td class="hide">' + data1.Table1[i].request_id + '</td><td class="hide">' + data1.Table1[i].request_details_id + '</td><td class="hide">' + data1.Table1[i].base_amount_type + '</td><td class="hide">' + data1.Table1[i].range_min + '</td><td class="hide">' + data1.Table1[i].range_max + '</td><td class="hide">0</td><td class="hide">0</td><td class="hide">' + data1.Table1[i].percentage + '</td><td class="hide">' + data1.Table1[i].base_amount + '</td><td class="hide">' + data1.Table1[i].is_workorder + '</td><td class="hide">' + data1.Table1[i].is_doctor + '</td><td class="hide">' + data1.Table1[i].is_description + '</td><td class="hide">' + data1.Table1[i].CRMService + '</td><td class="hide">0</td><td class="hide">0</td><td class="hide">0</td>'




                            tr += '<td><span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
                            $('#service_tbl tbody').append(tr);
                            var ObjArr = {
                                rowCount: rowCount,
                                id: 'tr_' + rowCount,
                                base_amount_type: data1.Table1[i].base_amount_type,
                                service_name: data1.Table1[i].service_name,
                                quantity: data1.Table1[i].quantity,
                                Rate: data1.Table1[i].base_amount,
                                base_amount_value: data1.Table1[i].base_amount,
                                TotalAmt: data1.Table1[i].total_amount,
                                discount: 0,
                                sel_discount_type: 0,
                                discount_amount: 0,
                                tax_percentage: 0,
                                tax_amount: 0,
                                tot_net_amt: data1.Table1[i].total_amount,
                                ser_date: date,
                                doc_name: data1.Table1[i].first_name,
                                remarks: '-',
                                doctor_id: data1.Table1[i].doctor_id,
                                master_service_id: data1.Table1[i].master_service_id,
                                package_id: data1.Table1[i].package_id,
                                price_matrix_id: data1.Table1[i].price_matrix_id,
                                request_id: data1.Table1[i].request_id,
                                request_details_id: data1.Table1[i].request_details_id,
                                range_min: data1.Table1[i].range_min,
                                range_max: data1.Table1[i].range_max,
                                billing_details_id: 0,
                                is_workorder: data1.Table1[i].is_workorder,
                                is_doctor: data1.Table1[i].is_doctor,
                                is_description: data1.Table1[i].is_description,
                                charge_percentage: data1.Table1[i].percentage,
                                CRMservice: data1.Table1[i].CRMService,
                                PharmacyBillNo: 0,
                                estimation_details_id: 0,
                                estimation_no:0,
                                editDelete: '<span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span>'

                            }
                            Service_Org_Arr.push(ObjArr);
                        }

                        $('#net_amount').html(parseFloat(netamount).toFixed(2));
                        $('#total_net_amount').html(Math.round(netamount - parseFloat(data1.Table1[0].advance_amount)).toFixed(2));
                        $('#advance_amount').html(Math.round(data1.Table1[0].advance_amount).toFixed(2));
                        $('#balance_amount').html(Math.round(netamount).toFixed(2));
                        $('#txt_received_amt').val(Math.round(netamount));
                        $('#sms_amount,#txt_received_amt').val(Math.round(netamount));
                        automated_charge_cal(0);
                    }
                }
            }
        }
    });
}

//op, Home care, Diagnostics visit report creation
$('#btn_create_visit').click(function () {
    var visit_type = $("input[name='optradio']:checked").val();
    if ($.trim($('#pkg_branch_id').val()) == "0") {
        $('#Ppkg_branch_id').show();
        $('#Ppkg_branch_id').fadeOut(8000);
        $('#Ppkg_branch_id').html('Please select the branch');
        $('#pkg_branch_id').focus();
        return false;
    }
    if ($.trim($('#txtPaitentSearch_bill').val()) == "") {
        $('#PtxtPaitentSearch_bill').show();
        $('#PtxtPaitentSearch_bill').fadeOut(8000);
        $('#PtxtPaitentSearch_bill').html('Please Select The Patient Name');
        $('#txtPaitentSearch_bill').focus();
        $('#txtPaitentSearch_bill').val('');
        return false;
    }

    if (visit_type != 11) {
        if (($.trim($('#SelDoctor').val()) == '' || $('#HdnSelDoctor').val() == 0) && $('#HdnSelDoctor_userid').val() == "") {
            $('#PSelDoctor').show();
            $('#PSelDoctor').fadeOut(8000);
            $('#PSelDoctor').html('Please select the doctor/user');
            $('#SelDoctor').focus();
            $('#PSelDoctor').val(0);
            return false;
        }
        
    }
    if ($.trim($('#Entity').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select Entity Name');
            $('#ddInsuranceName').focus();
            return false;
        }
        if ($('#CMultiPay').prop('checked') == true) {
            if ($.trim($('#MPCIName').val()) == '') {
                $('#PMPCIName').show();
                $('#PMPCIName').fadeOut(8000);
                $('#PMPCIName').html('Select the field');
                $('#PMPCIName').focus();
                return false;
            }
        }
        //if ($.trim($('#txt_emp_name').val()) == '') {
        //    $('#Ptxt_emp_name').show();
        //    $('#Ptxt_emp_name').fadeOut(8000);
        //    $('#Ptxt_emp_name').html('Enter Employee Name');
        //    $('#txt_emp_name').focus();
        //    return false;
        //}
        //if ($.trim($('#txt_emp_code').val()) == '') {
        //    $('#Ptxt_emp_code').show();
        //    $('#Ptxt_emp_code').fadeOut(8000);
        //    $('#Ptxt_emp_code').html('Enter Employee Code');
        //    $('#txt_emp_code').focus();
        //    return false;
        //}
    }

    if (visit_type == 11) {
        if ($.trim($('#SelAudiologist').val()) == '' || $('#SelAudiologist').val() == 0) {
            $('#PSelAudiologist').show();
            $('#PSelAudiologist').fadeOut(8000);
            $('#PSelAudiologist').html('Please Select Audiologist');
            $('#SelAudiologist').focus();
            $('#PSelAudiologist').val(0);
            return false;
        }
    }
    if (visit_type == 11) {
        debugger;
        if ($.trim($('#SelReferredDoctor').val()) == '' || $('#SelReferredDoctor').val() == 0) {
            $('#SelReferredDoctor').show();
            $('#SelReferredDoctor').fadeOut(8000);
            $('#SelReferredDoctor').html('Please Select referred doctor');
            $('#SelReferredDoctor').focus();
            $('#SelReferredDoctor').val(0);
            return false;
        }
    }

    if (visit_type == "" || visit_type == 0 || visit_type == undefined) {
        $('#Poptradio').show();
        $('#Poptradio').fadeOut(8000);
        $('#Poptradio').html('Please select type of appointment');
        $('#optradio').focus();
        return false;
    }


    var patient_id = $('#hdnpatientapp').val();
    VisitReport_Creation();
    //var DoctorData = {
    //    doctor_id:$('#SelDoctor').val(),
    //    hospital_id: $('#HospitalId').val(),
    //    patient_id: $('#hdnpatientapp').val(),
    //    branch_id:$('#pkg_branch_id').val(),
    //    visit_type:visit_type,
    //    dml_indicator: 'AB'
    //}
    //$.ajax({
    //    async: true,
    //    type: 'POST',
    //    url: '/Billing/Billing_visit_report_creation',
    //    contentType: 'application/json; charset=UTF-8',
    //    data: JSON.stringify(DoctorData),
    //    success: function (data) {
    //        debugger;
    //        var data2 = JSON.parse(data);
    //        console.log(data2);
    //        if (jQuery.isEmptyObject((data2.data))) {
    //        }
    //        else {
    //            if (data2.msg == "Success") {
    //                var data1 = data2.data;
    //                if (data1.Table[0].is_AppointmentBooked == 1) {
    //                    VisitReport_Creation();
    //                }
    //                else {

    //                    $('#Claim_Details').modal('toggle');
    //                }
    //            }
    //        }
    //    }
    //});
});

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

    if ($.trim($('#Entity').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
    }
    debugger;
   

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select Entity Name');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    VisitReport_Creation();

});
function ReferralDoctor(value) {
    //$('#txtPatientName').val($('.PatientName').html());
    debugger;
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        //branch_id: b_id
        //branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            $('#ddReferraldoctor').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#ddReferraldoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#ddReferraldoctor').html(default_opt + SelRole);
                        if (parseInt($('#hiddenRole_id').val()) == 1) {
                            $("#ddReferraldoctor option[value='" + $('#doctorId').val() + "']").remove();
                        }
                        if (value != 0) {
                            $('#ddReferraldoctor').val(value);
                        }
                    }
                }
            }
        }
    });
}
function loadreferby(refby) {
    debugger
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            //$('#directappointment').modal('toggle');
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var SelRole = '';
                    $('#SelReferredDoctor').empty();
                    debugger;
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;

                            SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';

                        }
                        $('#SelReferredDoctor').append(default_opt + SelRole);

                        if ($('#hiddenRole_id').val() == 1) {
                            $('#SelReferredDoctor').val($('#HiddenDoctorID').val());
                            $('#SelReferredDoctor').attr('disabled', true);
                        }
                        if (refby != '' || refby != null) {
                            $('#SelReferredDoctor').val(refby)
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

//Convert To Bill call method from Request Page
function request_details() {
    $('#shade_slot').show();
    $('#btn_submit').attr('disabled', true);
    var DoctorData = {
        visit_report_id: $('#hdnvisit_report_id').val(),
        request_id: $('#hdnrequest_id').val(),
        dml_indicator: 'RS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    console.log(data1);
                    debugger;
                    var total_tax = 0.0;
                    if (data1.Table.length > 0) {
                        //$('.pat-stripe-bgop').show();
                        var patient_id = data1.Table[0].patient_id;
                        var bill = PatientSearch(patient_id, data1.Table[0].is_ip, $('#hndbranch').val(), $('#hdnvisit_report_id').val());
                        $.when(bill)
                    .then(function (data3) {
                        var da1 = JSON.parse(data3);
                        if (da1.msg == "Success") {
                            console.log(data1);
                            da1 = da1.data;
                            $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                            $('#hdn_entity').val(da1[0].entity_id);
                            $('#hdn_is_scheme').val(da1[0].is_scheme);
                            $('#HdnEntityid').val(da1[0].insuranceid);
                            $('#EntityType').val(da1[0].is_insurance);
                            $('#Entity').val(da1[0].is_entity);
                            $('#CMultiPay').val(da1[0].is_MultiPay);
                            Corporate_Insurance($('#HdnEntityid').val(), da1[0].Corporate_Insuranceid);
                        }

                    });

                        $('#pkg_branch_id').val($('#hndbranch').val());
                        $('.pat-stripe-bgop').show();

                        $('#hndbilling_class').val(data1.Table[0].billing_class);
                        $('#hndward_id').val(data1.Table[0].ward_id);
                        //$('#hndward_id').val(data1.Table[0].is_ip);
                        LoadVisitType('',data1.Table[0].is_ip);
                        $("input[name='optradio'][value='" + data1.Table[0].is_ip + "']").prop('checked', true);
                        //if (data1.Table[0].is_ip == 1) {
                        //    $("#op").prop("checked", true);
                        //}
                        //else if (data1.Table[0].is_ip == 2)
                        //{ $("#ip").prop("checked", true); }
                        //else if (data1.Table[0].is_ip == 3)
                        //{ $("#home_care").prop("checked", true); }
                        //else if (data1.Table[0].is_ip == 4)
                        //{ $("#diagnostics").prop("checked", true); }

                        if (data1.Table[0].is_entity == 1) {
                            $('#div_claim').removeClass('hidden');
                            if (data1.Table[0].is_insurance == 2 && data1.Table[0].is_MultiPay == 1) {
                                $('#divclaimType').removeClass('hidden');
                            }
                            else {
                                $('#divclaimType').addClass('hidden');
                            }
                        }
                        else {
                            $('#div_claim').addClass('hidden');
                        }
                        $('#His_insurance').val(data1.Table[0].is_entity);
                        var netamount = 0;
                        for (var i = 0; i < data1.Table.length; i++) {
                            $('#hdnpatientapp').val(patient_id);
                            if (data1.Table[i].charge_percentage == '0') {
                                netamount += data1.Table[i].total_amount;
                            }

                            var rowCount = $('#service_tbl tbody tr').length;
                            if (rowCount == 0) {
                                rowCount = 1
                            }
                            else {
                                var id = $('#service_tbl tbody tr:last').attr('id');
                                id = id.split('_');
                                rowCount = parseInt(id[1]) + (1);
                            }

                            var sel_discount_type = $('.sel_discount_type').val();
                            if (sel_discount_type == 1) {
                                sel_discount_type = '₹';
                            }
                            else {
                                sel_discount_type = '%';
                            }
                            var tax_amount = 0.0;
                            if (data1.Table[i].is_tax == 1 && data1.Table[i].charge_percentage == '0') {
                                tax_amount = (parseFloat(data1.Table[i].total_amount)) * (parseFloat(data1.Table[i].tax_percentage) / 100);
                            }
                            total_tax = total_tax + parseFloat(tax_amount);

                            var date_time
                            if (data1.Table[i].base_amount_type == 4)
                                date_time = data1.Table[i].service_date + " " + data1.Table[i].service_time + " - " + data1.Table[i].service_end_date + " " + data1.Table[i].service_end_time;
                            else
                                date_time = data1.Table[i].service_date + " " + data1.Table[i].service_time
                            var Rate = parseFloat(data1.Table[i].base_amount).toFixed(2) + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat(data1.Table[i].base_amount) + ')</span>';

                            var tr = '<tr  id="tr_' + rowCount + '" tabindex=' + (rowCount - 1) + ' class="del_chk ' + bill_row_colour(data1.Table[i].base_amount_type) + '"><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].quantity + '</td><td>' + Rate + '</td>'
                            tr += '<td>' + parseFloat(data1.Table[i].total_amount).toFixed(2) + '</td><td>0' + ' ' + '₹</td><td>0</td><td>' + data1.Table[i].tax_percentage + '%</td><td>' + parseFloat(parseFloat(tax_amount) + parseFloat(data1.Table[i].total_amount)).toFixed(2) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td><td class="hide">' + data1.Table[i].request_details_id + '</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">0</td><td class="hide">' + parseFloat(tax_amount).toFixed(2) + '</td><td class="hide">' + data1.Table[i].charge_percentage + '</td><td class="hide">' + parseFloat(data1.Table[i].base_amount) + '</td><td class="hide">' + data1.Table[i].is_workorder + '</td><td class="hide">' + data1.Table[i].is_doctor + '</td><td class="hide">' + data1.Table[i].is_description + '</td><td class="hide">' + data1.Table[i].CRMService + '</td><td class="hide">' + data1.Table[i].PharmacyBillNo + '</td><td class="hide">0</td><td class="hide">0</td>'
                            //tr += '<td></td><td>' + data1.Table[i].total_amount + '</td><td></td><td>' + data1.Table[i].first_name + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td>'
                            tr += '<td><span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
                            $('#service_tbl tbody').append(tr);
                            var ObjArr = {
                                rowCount: rowCount,
                                id: 'tr_' + rowCount,
                                base_amount_type: data1.Table[i].base_amount_type,
                                service_name: data1.Table[i].service_name,
                                quantity: data1.Table[i].quantity,
                                Rate: data1.Table[i].base_amount,
                                base_amount_value: data1.Table[i].base_amount,
                                TotalAmt: data1.Table[i].total_amount,
                                discount: 0,
                                sel_discount_type: 0,
                                discount_amount: 0,
                                tax_percentage: data1.Table[i].tax_percentage,
                                tax_amount: tax_amount,
                                tot_net_amt: parseFloat(parseFloat(tax_amount) + parseFloat(data1.Table[i].total_amount)),
                                ser_date: date_time,
                                doc_name: data1.Table[i].first_name,
                                remarks: (data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks,
                                doctor_id: data1.Table[i].doctor_id,
                                master_service_id: data1.Table[i].master_service_id,
                                package_id: data1.Table[i].package_id,
                                price_matrix_id: data1.Table[i].price_matrix_id,
                                request_id: data1.Table[i].request_id,
                                request_details_id: data1.Table[i].request_details_id,
                                range_min: data1.Table[i].range_min,
                                range_max: data1.Table[i].range_max,
                                billing_details_id: 0,
                                charge_percentage: data1.Table[i].charge_percentage,
                                is_workorder: data1.Table[i].is_workorder,
                                is_doctor: data1.Table[i].is_doctor,
                                is_description: data1.Table[i].is_description,
                                CRMservice: data1.Table[i].CRMService,
                                PharmacyBillNo: data1.Table[i].PharmacyBillNo,
                                estimation_details_id: 0,
                                estimation_no:0,
                                editDelete: '<span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span>'

                            }
                            Service_Org_Arr.push(ObjArr);
                           //- LoadDoctor();
                            authorized_person();
                            //LoadPayment_Type();
                        }
                        LoadPayment_Type(); //changed by tharuni because inside the loop LoadPayment_Type called
                        $('#net_amount').html((parseFloat(parseFloat(netamount) + parseFloat(total_tax)).toFixed(2)));
                        $('#total_net_amount').html(Math.round((netamount + total_tax)).toFixed(2));
                        $('#advance_amount').html(Math.round((data1.Table[0].advance_amount)).toFixed(2));
                        $('#total_tax_amount').html((total_tax));
                        footer_binding_calc();
                        if (data1.Table[0].advance_amount > netamount) {


                            //$('#collect_payment').html((netamount+total_tax).toFixed(2));
                            $('#balance_amount').html(parseFloat(0).toFixed(2));
                            $('#sms_payment,#txt_received_amt').val(0);
                            $('#refund_amount').html(Math.round((data1.Table[0].advance_amount - (netamount + total_tax))).toFixed(2));

                        }
                        else {

                           
                            $('#balance_amount').html(Math.round(parseFloat(netamount) + parseFloat(total_tax) - parseFloat(data1.Table[0].advance_amount)).toFixed(2));
                            $('#txt_received_amt').val(Math.round((netamount + total_tax - data1.Table[0].advance_amount ).toFixed(2)));
                            $('#sms_payment').val(Math.round((netamount - data1.Table[0].advance_amount + total_tax).toFixed(2)));
                            $('#refund_amount').html(parseFloat(0).toFixed(2));

                        }
                        //if (data1.Table[0].is_ip == 2) {
                            automated_charge_cal(0)
                        //}

                    }
                    if (data1.Table1.length > 0) {
                        $('#tbl_payment_history').empty();
                        var tr1 = '';
                        for (var i = 0; i < data1.Table1.length; i++) {
                            var h_rowCount = $('#tbl_payment_history tr').length;
                            if (h_rowCount == 0) {
                                h_rowCount = 1
                            }
                            else {
                                var id = $('#tbl_payment_history tr:last').attr('id');
                                id = id.split('_');
                                h_rowCount = parseInt(id[1]) + (1);
                            }

                            var tr1 = '<tr id="tr_' + h_rowCount + '"><td>' + data1.Table1[i].receipt_date + '</td><td>' + data1.Table1[i].receipt_code + '</td><td>' + data1.Table1[i].receipt_type + '</td><td>' + data1.Table1[i].master_service_name + '</td><td>' + data1.Table1[i].bank_name + '</td>'
                            tr1 += '<td>' + data1.Table1[i].reference_no + '</td><td>' + data1.Table1[i].amount + '</td><td>' + data1.Table1[i].user_collect_amount + '</td><td>' + data1.Table1[i].user_refund + '</td></tr>'
                            $('#tbl_payment_history').append(tr1);
                        }
                    }

                    $('#shade_slot').hide();
                    $('#btn_submit').attr('disabled', false);
                }
                else {
                }
            }

        }
    });
}
//$("#service_tbl").on('click', '.del_chk', function () {


//    var idx = $(this).closest("tr").prop("tabindex");
//    var id = $(this).closest("tr").prop("id");
//    $("tr[tabindex=0]").focus();
//    //var idx = $("tr:focus").attr("tabindex");
//    //$(this).closest("tr").focus();
//    var idx = $("tr:focus").attr("tabindex");
//    idx++;
//    if (idx > 6) {
//        idx = 0;
//    }
//    $("tr[tabindex=" + idx + "]").focus();

//    //document.onkeydown = checkKey;
//    //checkKey(this,id);
//});

//$("#service_tbl").on('keydown', '.del_chk', function (event) {
//    debugger;
//    var id = $(this).closest("tr").prop("id");

//    var event = window.event ? window.event : e;
//    if (event.keyCode == 46) {

//        $('#' + id).remove();
//    }

//    if (event.keyCode == 40) { //down
//        var idx = $("tr:focus").attr("tabindex");
//        idx++;
//        if (idx > 6) {
//            idx = 0;
//        }
//        $("tr[tabindex=" + idx + "]").focus();
//    }
//    if (event.keyCode == 38) { //up
//        var idx = $("tr:focus").attr("tabindex");
//        idx--;
//        if (idx < 0) {
//            idx = 6;
//        }
//        $("tr[tabindex=" + idx + "]").focus();
//    }
//});



//Billing Edit
function billing_edit() {

    $('#shade_slot').show();
    $('#btn_submit').attr('disabled', true);

    var DoctorData = {
        visit_report_id: $('#hdnvisit_report_id').val(),
        request_id: $('#hdnrequest_id').val(),
        billing_no: billing_no,
        dml_indicator: 'BE'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table.length > 0) {


                        //$('#sel_authorized_person').attr('disabled', 'disabled');
                        //$('#txt_tot_discount_amt').attr('disabled', 'disabled');


                        var patient_id = data1.Table[0].patient_id;
                        var bill = PatientSearch(patient_id, data1.Table[0].visit_type, $('#hndbranch').val(), $('#hdnvisit_report_id').val());
                        $.when(bill)
                    .then(function (data3) {
                        var da1 = JSON.parse(data3);
                        if (da1.msg == "Success") {
                            console.log(data1);
                            da1 = da1.data;
                            $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                            if (data1.Table[0].visit_type == 2) {
                                $('#hdn_entity').val(da1[0].entity_id);
                                $('#hdn_is_scheme').val(da1[0].is_scheme);
                            }
                            else {
                                $('#hdn_entity').val(data1.Table[0].entity_id);
                                $('#hdn_is_scheme').val(data1.Table[0].is_scheme);
                                $('.billing_class').html(data1.Table[0].master_service_name);
                                $('#Hwardid').val(data1.Table[0].wardid);
                                $('#Hbilling_class').val(data1.Table[0].billing_class);
                                //$('.ward_id').html(data1.Table[0].ward_code);
                                $('.entity').html(data1.Table[0].insurance_name);
                                data1.Table[0].is_entity == 1 ? $('#entity').show() : $('#entity').hide();
                                if ((data1.Table[0].is_insurance == 1 || data1.Table[0].is_insurance == 2) && data1.Table[0].is_MultiPay == 1) {
                                    $('#div_tpa').show();
                                    var h1 = (data1[0].is_insurance == 1) ? 'TPA : ' : 'Insurance Name : '
                                    $('#tpa_insurance').html(h1 + '<span>' + data1[0].TPA_Insurance_Name + '</span>');
                                }
                                $('#HdnEntityid').val(data1.Table[0].insurance_id);
                                $('#EntityType').val(data1.Table[0].is_insurance);
                                $('#Entity').val(data1.Table[0].is_entity);
                                $('#CMultiPay').val(data1.Table[0].is_MultiPay);
                                $('#MPCIName').val(data1.Table[0].Corporate_Insuranceid)
                            }
                        }

                    });

                        $('#pkg_branch_id').val($('#hndbranch').val());
                        $('.pat-stripe-bgop').show();
                        $('#net_amount').html(parseFloat(data1.Table[0].total_amount).toFixed(2));
                        $('#hdn_wo_otp').val(data1.Table[0].OTP_Status);
                        //if (parseFloat(data1.Table[0].advance_amount) > parseFloat(data1.Table[0].total_net_amount)) {
                        //    $('#total_net_amount').html(parseFloat(data1.Table[0].total_net_amount));
                        //}
                        //else {
                        //    $('#total_net_amount').html(parseFloat(data1.Table[0].total_net_amount) - parseFloat(data1.Table[0].advance_amount));
                        //}
                        authorized_person(data1.Table[0].discount_authorization_by);
                        $('#txt_billing_remarks').val(data1.Table[0].billing_remarks);
                        $('#total_net_amount').html(Math.round(parseFloat(data1.Table[0].total_net_amount)).toFixed(2));
                        $('#advance_amount').html(Math.round(data1.Table[0].advance_amount).toFixed(2));
                        $('#hndbilling_class').val(data1.Table[0].billing_class);
                        $('#hndward_id').val(data1.Table[0].ward_id);
                        $('#txt_tot_discount_amt').val((data1.Table[0].discount));
                        if ($('#txt_tot_discount_amt').val() != '' && $('#hdn_wo_otp').val()!=1) {
                            $('#txt_tot_discount_amt').attr('disabled', 'disabled');
                        }
                        $('#txt_due_reason').val(data1.Table[0].due_reason);
                        $('#txt_dis_reason').val(data1.Table[0].discount_reason);
                        $('#authorized_discount').val(data1.Table[0].discount_type);
                        $('#total_discount').html(parseFloat(data1.Table[0].total_discount_amount).toFixed(2));
                        $('#total_tax_amount').html(Math.round(data1.Table[0].tax_amount));
                        $('#refund_amount').html(Math.round(data1.Table[0].billing_refund).toFixed(2));
                        $('.balance_amount_div').show();
                        $('#balance_amount').html(Math.round(data1.Table[0].due_amount).toFixed(2));
                        $('#final_claim_amount').html(Math.round(data1.Table[0].authorized_amount));
                        $('#collect_claim_amount').html(Math.round(data1.Table[0].approved_amount))
                        $('#txt_received_amt').val(Math.round(data1.Table[0].due_amount));
                        $('#sms_payment,#txt_received_amt').val(Math.round(data1.Table[0].due_amount));
                        $('#collect_payment').html(Math.round(data1.Table[0].received_amount).toFixed(2));
                        //$('#hndward_id').val(data1.Table[0].is_ip);
                        LoadVisitType('', data1.Table[0].visit_type);
                       // $("input[name='optradio'][value='" + data1.Table[0].visit_type + "']").prop('checked', true);
                       
                        //if (data1.Table[0].visit_type == 1) {
                        //    $("#op").prop("checked", true);
                        //    $('#op').val(data1.Table[0].visit_type)
                        //}
                        //else if (data1.Table[0].visit_type == 2)
                        //{
                        //    $("#ip").prop("checked", true);
                        //    $('#ip').val(data1.Table[0].is_ip)
                        //}
                        //else if (data1.Table[0].visit_type == 3)
                        //{
                        //    $("#home_care").prop("checked", true);
                        //    $('#home_care').val(data1.Table[0].visit_type)
                        //}
                        //else if (data1.Table[0].visit_type == 4)
                        //{
                        //    $("#diagnostics").prop("checked", true);
                        //    $('#diagnostics').val(data1.Table[0].visit_type)
                        //}
                        //else if (data1.Table[0].visit_type == 7)
                        //{
                        //    $("#daycare").prop("checked", true);
                        //    $('#daycare').val(data1.Table[0].is_ip)
                        //}
                        //else if (data1.Table[0].visit_type == 8)
                        //{
                        //    $("#emergency_reg").prop("checked", true);
                        //    $('#emergency_reg').val(data1.Table[0].is_ip)
                        //}
                  
                       
                        if (data1.Table[0].is_entity == 1) {
                            $('#div_claim').removeClass('hidden');
                            if (data1.Table[0].is_insurance == 2 && data1.Table[0].is_MultiPay == 1) {
                                $('#divclaimType').removeClass('hidden');
                            }
                            else {
                                $('#divclaimType').addClass('hidden');
                            }
                            //$('#claim_no').val(data1.Table[0].claim_no);
                            //$('#auth_amt').val(data1.Table[0].approved_amount);
                            //$('#authorized_amt').val(data1.Table[0].authorized_amount);
                            //$('#mou_discount').val(data1.Table[0].mou_discount);
                            //$('#co_pay').val(data1.Table[0].co_pay);
                            //$('#dis_others').val(data1.Table[0].other_discount)
                            //if (data1.Table[0].claim_no != '' && data1.Table[0].claim_no != null) {
                            //$('#claim_no').attr('disabled', true);
                            //}

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

                            //if (data1.Table[0].approved_amount != 0) {

                            //$('#auth_amt').attr('disabled',true);
                            //$('#mou_discount').attr('disabled',true);
                            //$('#co_pay').attr('disabled',true);
                            //$('#dis_others').attr('disabled',true);
                            //}
                        }
                        $('#His_insurance').val(data1.Table[0].is_entity);

                        for (var i = 0; i < data1.Table.length; i++) {
                            $('#hdnpatientapp').val(patient_id);

                            var rowCount = $('#service_tbl tbody tr').length;
                            if (rowCount == 0) {
                                rowCount = 1
                            }
                            else {
                                var id = $('#service_tbl tbody tr:last').attr('id');
                                id = id.split('_');
                                rowCount = parseInt(id[1]) + (1);
                            }

                            var sel_discount_type = data1.Table[i].service_dis_type;
                            if (sel_discount_type == 1) {
                                sel_discount_type = '₹';
                            }
                            else {
                                sel_discount_type = '%';
                            }
                            var date_time;
                            if (data1.Table[i].base_amount_type == 4) {
                                date_time = data1.Table[i].request_date + " " + data1.Table[i].request_time + " - " + data1.Table[i].end_date + " " + data1.Table[i].end_time;
                            }
                            else {
                                date_time = data1.Table[i].request_date + " " + data1.Table[i].request_time
                            }
                            if (parseFloat(data1.Table[i].due_amount) == 0) {
                                $('#hdn_bill_status').val(1);
                            }
                            var Rate = parseFloat(data1.Table[i].service_quantity_amount).toFixed(2) + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat(data1.Table[i].base_amount) + ')</span>';
                            var editDelete = '';
                            //if (data1.Table[0].is_entity == 1 && data1.Table[0].ip_visit_report_status == 1 && (parseFloat(data1.Table[i].due_amount) != 0)) {
                            if ((data1.Table[0].is_entity == 1 && ((data1.Table[0].visit_type == 1) || data1.Table[0].visit_type == 2) && ((parseFloat(data1.Table[i].claim_final_status) == 0) || ((parseFloat(data1.Table[0].claim_final_status) != 0) && (parseFloat(data1.Table[0].due_amount) != 0)))) || (data1.Table[0].visit_type == 2 && (parseFloat(data1.Table[0].due_amount) != 0)) || (data1.Table[0].visit_type == 1 && data1.Table[0].is_entity != 1 && parseFloat($('#collect_payment').html()) == 0 && (parseFloat(data1.Table[0].due_amount) != 0)) || (data1.Table[0].visit_type == 2 && data1.Table[0].is_entity != 1 && data1.Table[0].ip_visit_report_status==1)) {
                                var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour(data1.Table[i].base_amount_type) + '" ><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].service_quantity + '</td><td>' + Rate + '</td>'
                                tr += '<td>' + parseFloat(data1.Table[i].amount).toFixed(2) + '</td><td>' + data1.Table[i].discount_detail + ' ' + sel_discount_type + '</td><td>' + parseFloat(data1.Table[i].service_discount_amount).toFixed(2) + '</td><td>' + data1.Table[i].service_tax_percentage + '%</td><td>' + (parseFloat(data1.Table[i].service_net_amount).toFixed(2)) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_number + '</td><td class="hide">0</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">' + data1.Table[i].billing_details_id + '</td><td class="hide">' + parseFloat(data1.Table[i].service_tax_amount).toFixed(2) + '</td><td class="hide">' + data1.Table[i].charge_percentage + '</td><td class="hide">' + parseFloat(data1.Table[i].base_amount) + '</td><td class="hide">' + (data1.Table[i].is_workorder) + '</td><td class="hide">' + (data1.Table[i].is_doctor) + '</td><td class="hide">' + (data1.Table[i].is_description) + '</td><td class="hide">' + (data1.Table[i].CRMService) + '</td><td class="hide">' + (data1.Table[i].PharmacyBillNo) + '</td>'
                                tr += '<td class="hide">' + (data1.Table[i].estimation_details_id) + '</td><td class="hide">' + (data1.Table[i].estimation_no) + '</td>'
                                tr += '<td><span class="btn btn-xs  mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
                                editDelete = '<span class="btn btn-xs  mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span>'
                                $('#service_tbl_footer1').show();
                                $('#btn_add').show();
                            }
                            else {
                                var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour(data1.Table[i].base_amount_type) + '" ><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].service_quantity + '</td><td>' + Rate + '</td>'
                                tr += '<td>' + parseFloat(data1.Table[i].amount).toFixed(2) + '</td><td>' + data1.Table[i].discount_detail + ' ' + sel_discount_type + '</td><td>' + parseFloat(data1.Table[i].service_discount_amount).toFixed(2) + '</td><td>' + data1.Table[i].service_tax_percentage + '%</td><td>' + (parseFloat(data1.Table[i].service_net_amount).toFixed(2)) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_number + '</td><td class="hide">0</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">' + data1.Table[i].billing_details_id + '</td><td class="hide">' + parseFloat(data1.Table[i].service_tax_amount).toFixed(2) + '</td><td class="hide">' + data1.Table[i].charge_percentage + '</td><td class="hide">' + parseFloat(data1.Table[i].base_amount) + '</td><td class="hide">' + (data1.Table[i].is_workorder) + '</td><td class="hide">' + (data1.Table[i].is_doctor) + '</td><td class="hide">' + (data1.Table[i].is_description) + '</td><td class="hide">' + (data1.Table[i].CRMService) + '</td><td class="hide">' + (data1.Table[i].PharmacyBillNo) + '</td>'
                                tr += '<td class="hide">' + (data1.Table[i].estimation_details_id) + '</td><td class="hide">' + (data1.Table[i].estimation_no) + '</td>'
                                //tr += '<td>' + data1.Table[i].discount_detail + ' '+sel_discount_type+'</td><td>' + data1.Table[i].amount + '</td><td>'+data1.Table[i].request_date+'</td><td>' + data1.Table[i].first_name + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td>'
                                //tr += '<td><span class="btn btn-xs btn-primary service_edit"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick="service_delete(' + rowCount + ')"><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';
                                tr += '<td> - </td></tr>';
                                editDelete = '<td> - </td>'
                                if (data1.Table[0].visit_type == 1 && data1.Table[0].is_entity != 1 && parseFloat($('#collect_payment').html()) != 0 && (parseFloat(data1.Table[0].due_amount) != 0)) {
                                    $('#btn_add').show();
                                    $('#service_tbl_footer1').show();
                                }
                                else {
                                    $('#service_tbl_footer1').hide();
                                    $('#btn_add').hide();
                                }
                            }
                            $('#service_tbl tbody').append(tr);
                            var ObjArr = {
                                rowCount: rowCount,
                                id: 'tr_' + rowCount,
                                base_amount_type: data1.Table[i].base_amount_type,
                                service_name: data1.Table[i].service_name,
                                quantity: data1.Table[i].service_quantity,
                                Rate: data1.Table[i].service_quantity_amount,
                                base_amount_value: data1.Table[i].base_amount,
                                TotalAmt: data1.Table[i].amount,
                                discount: data1.Table[i].discount_detail,
                                sel_discount_type: sel_discount_type,
                                discount_amount: data1.Table[i].service_discount_amount,
                                tax_percentage: data1.Table[i].service_tax_percentage,
                                tax_amount: data1.Table[i].service_tax_amount,
                                tot_net_amt: data1.Table[i].service_net_amount,
                                ser_date: date_time,
                                doc_name: data1.Table[i].first_name,
                                remarks: (data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks,
                                doctor_id: data1.Table[i].doctor_id,
                                master_service_id: data1.Table[i].master_service_id,
                                package_id: data1.Table[i].package_id,
                                price_matrix_id: data1.Table[i].price_matrix_id,
                                request_id: data1.Table[i].request_number,
                                request_details_id: 0,
                                range_min: data1.Table[i].range_min,
                                range_max: data1.Table[i].range_max,
                                billing_details_id: data1.Table[i].billing_details_id,
                                charge_percentage: data1.Table[i].charge_percentage,
                                is_workorder: data1.Table[i].is_workorder,
                                is_doctor: data1.Table[i].is_doctor,
                                is_description: data1.Table[i].is_description,
                                CRMservice: data1.Table[i].CRMService,
                                PharmacyBillNo: data1.Table[i].PharmacyBillNo,
                                estimation_details_id: data1.Table[i].estimation_details_id,
                                estimation_no:data1.Table[i].estimation_no,
                                editDelete: editDelete


                            }
                            Service_Org_Arr.push(ObjArr);
                          //-  LoadDoctor();

                            //LoadPayment_Type();
                            //Authorized_Person_cal();
                        }
                        //service_tbl_cal();
                        //authorized_person();
                        LoadPayment_Type(); //changed by tharuni because inside the loop LoadPayment_Type called
                        footer_binding_calc();
                    }
                    if (data1.Table1.length > 0) {
                        $('#tbl_payment_history').empty();
                        var tr1 = '', total_amount = 0;
                        for (var i = 0; i < data1.Table1.length; i++) {
                            var h_rowCount = $('#tbl_payment_history tr').length;
                            if (h_rowCount == 0) {
                                h_rowCount = 1
                            }
                            else {
                                var id = $('#tbl_payment_history tr:last').attr('id');
                                id = id.split('_');
                                h_rowCount = parseInt(id[1]) + (1);
                            }
                            var P_rowCount = $('#tbl_payment tr').length;
                            if (P_rowCount == 0) {
                                P_rowCount = 1
                            }
                            else {
                                var id = $('#tbl_payment tr:last').attr('id');
                                id = id.split('_');
                                P_rowCount = parseInt(id[1]) + (1);
                            }

                            var tr1 = '<tr id="tr_' + h_rowCount + '"><td>' + data1.Table1[i].receipt_date + '</td><td>' + data1.Table1[i].receipt_code + '</td><td>' + data1.Table1[i].receipt_type + '</td><td>' + data1.Table1[i].master_service_name + '</td><td>' + data1.Table1[i].bank_name + '</td>'
                            tr1 += '<td>' + data1.Table1[i].reference_no + '</td><td>' + data1.Table1[i].amount + '</td><td>' + data1.Table1[i].user_collect_amount + '</td><td>' + data1.Table1[i].user_refund + '</td></tr>'
                            total_amount = total_amount + data1.Table1[i].amount;
                            $('#tbl_payment_history').append(tr1);

                            //if (data1.Table1[i].receipt_type == 2) {
                            //    var tr2 = '<tr id="tr_' + P_rowCount + '"><td>' + data1.Table1[i].master_service_name + '</td><td>' + data1.Table1[i].amount + '</td><td>' + data1.Table1[i].reference_no + '</td>'
                            //    tr2 += '<td class="hide">' + data1.Table1[i].payment_mode + '</td></tr>'
                            //    total_amount = total_amount + data1.Table1[i].amount;
                            //    $('#tbl_payment').append(tr2);
                            //}
                        }
                        //$('#collect_payment').html(total_amount);
                    }
                    if (data1.Table2.length > 0) {
                        $('#tbl_claim tbody').empty();
                        var tr = '';
                        if (parseFloat(data1.Table[0].claim_final_status) != 0 && parseFloat(data1.Table[0].due_amount)==0) {
                            $('#claim_no').attr('disabled', true);
                            $('#auth_amt').attr('disabled', true);
                            $('#mou_discount').attr('disabled', true);
                            $('#co_pay').attr('disabled', true);
                            $('#dis_others').attr('disabled', true);
                        }
                        if (parseFloat(data1.Table[0].claim_final_status) != 0) {
                            $('#is_final').prop('disabled', true);
                        }
                        for (var i = 0; i < data1.Table2.length; i++) {
                            var row_count = i
                            if (!(data1.Table2[i].approve_date)) {
                                date1='-'
                            }
                            else {
                                var date = data1.Table2[i].approve_date.split('T')[0].split('-');
                                var date1 = date[2] + '/' + date[1] + '/' + date[0];
                            }
                            var c1 = (data1.Table2[i].claim_type==0)?'-':$('#claim_type option[value=' + data1.Table2[i].claim_type + ']').text()
                            if (((parseFloat(data1.Table[0].claim_final_status) == 0) || ((parseFloat(data1.Table[0].claim_final_status) != 0) && (parseFloat(data1.Table[0].due_amount) != 0)))) {
                                tr = tr + '<tr id=tclaim_' + (row_count + 1) + '><td id=td_claimid_' + (row_count + 1) + ' data-id=' + data1.Table2[i].claim_billing_id + '>' + data1.Table2[i].claim_no + '</td><td id=td_claimtype_' + (row_count + 1) + ' data-id="' + data1.Table2[i].claim_type + '">' + c1 + '</td><td id=td_approved_' + (row_count + 1) + '>' + data1.Table2[i].approved_amount + '</td><td id=td_mou_' + (row_count + 1) + '>' + data1.Table2[i].mou_discount + '</td><td id=td_co_' + (row_count + 1) + '>' + data1.Table2[i].co_pay + '</td><td id=td_dis_' + (row_count + 1) + '>' + data1.Table2[i].others + '</td><td id=td_date_' + (row_count + 1) + '>' + date1 + '</td><td id=td_final_'+(row_count+1)+' data-id='+data1.Table2[i].is_final_amount+'>'+(data1.Table2[i].is_final)+'</td><td><span class="btn btn-xs mr-10 btn-edit " onclick=claim_edit(' + (row_count + 1) + ')><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick="claim_delete(' + (row_count + 1) + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>'
                            }
                            else {
                                tr = tr + '<tr id=tclaim_' + (row_count + 1) + '><td id=td_claimid_' + (row_count + 1) + ' data-id=' + data1.Table2[i].claim_billing_id + '>' + data1.Table2[i].claim_no + '</td><td id=td_claimtype_' + (row_count + 1) + ' data-id="' + data1.Table2[i].claim_type + '">' + c1 + '</td><td id=td_approved_' + (row_count + 1) + '>' + data1.Table2[i].approved_amount + '</td><td id=td_mou_' + (row_count + 1) + '>' + data1.Table2[i].mou_discount + '</td><td id=td_co_' + (row_count + 1) + '>' + data1.Table2[i].co_pay + '</td><td id=td_dis_' + (row_count + 1) + '>' + data1.Table2[i].others + '</td><td id=td_date_' + (row_count + 1) + '>' + date1 + '</td><td id=td_final_' + (row_count + 1) + ' data-id=' + data1.Table2[i].is_final_amount + '>' + (data1.Table2[i].is_final) + '</td><td></td></tr>'

                            }
                        }
                        $('#tbl_claim tbody').append(tr);
                    }
                    $('#shade_slot').hide();
                    $('#btn_submit').attr('disabled', false);
                }
                else {
                }
            }

        }
    });
}

function service_tbl_cal() {
    var Net_Amount = 0, Total_Net_Amount = 0, total_discount = 0;
    $("#service_tbl tbody tr").each(function () {
        var discount_type = $(this).find("td").eq(4).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        cur_val = $(this).find("td").eq(3).html();
        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);

        Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(3).html());

        total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
    });
    var advance_amount = 0;
    if ($('#advance_amount').html() == '' || $('#advance_amount').html() == null) {
        advance_amount = 0;
    }
    Total_Net_Amount = parseFloat(Total_Net_Amount)  //- parseFloat(advance_amount);
    $('#net_amount').html(parseFloat(Net_Amount).toFixed(2));
    $('#total_net_amount').html(Math.round(Total_Net_Amount).toFixed(2));
    $('#total_discount').html(parseFloat(total_discount).toFixed(2));
}

function patient_detail(patient_id) {
    $('#hdnpatientapp').val(patient_id);
}

//Service Autocomplete
function service_code(serive_val, id) {
    //console.log(currentRow);
    //var col1 = currentRow.find("td:eq(0)").text(); // get current row 1st TD value
    //var col2 = currentRow.find("td:eq(1)").text(); // get current row 2nd TD
    //var col3 = currentRow.find("td:eq(3)").text(); // get current row 3rd TD
    //var data = col1 + "\n" + col2 + "\n" + col3;
    //alert(data);
    debugger;
    var indicator_id = '';
    if (serive_val == 0) {
        indicator_id = 'SMDD'
    }
    else {
        indicator_id = 'SMD'
    }

    var DoctorData = {
        price_matrix_id: serive_val,
        dml_indicator: indicator_id,
        master_service_id: id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                console.log(data2);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table.length > 0) {
                        if (data1.Table[0].is_description == 1) {
                            $('#txt_remarks').removeClass("hidden");
                        }
                        else {
                            $('#txt_remarks').addClass("hidden");
                        }
                        if (data1.Table[0].base_amount_type == 4) {
                            //$('#div_enddate').removeClass('hide');
                            //$('#div_endhead').removeClass('hide');
                            $('#datetimepicker2').show();
                            $('.txt_quantity').prop('disabled', true);



                        }
                        else {
                            $('.txt_quantity').val(1);
                        }
                        if (data1.Table[0].base_amount_type == 1 || data1.Table[0].base_amount_type == 3) {
                            $('.txt_unitRate').prop('disabled', false);
                            if (data1.Table[0].base_amount_type == 3) {
                                $('#Ptxt_unitRate').html("Enter the amount between " + data1.Table[0].range_min + ' - ' + data1.Table[0].range_max);
                                $('#Hrange_min').val(data1.Table[0].range_min);
                                $('#Hrange_max').val(data1.Table[0].range_max);
                            }
                        }
                        else if (data1.Table[0].base_amount_type == 2 || data1.Table[0].base_amount_type == 5) {   // added by nandhini for medway req to allow fixed type also to edit price
                            $('.txt_unitRate').prop('disabled', false);
                            $('#Hrange_min').val(data1.Table[0].actual_amount);
                        }
                        else {
                            $('#Ptxt_unitRate').html('');
                            $('.txt_unitRate').prop('disabled', true);
                        }
                        $('#hCRMService').val(data1.Table[0].CRMService);
                        $('#His_description').val(data1.Table[0].is_description);
                        $('.txt_unitRate').val(data1.Table[0].actual_amount);
                        $('.txt_totalamt').html(data1.Table[0].actual_amount);
                        $('.master_service_id').val(data1.Table[0].master_service_id);
                        $('.package_id').val(data1.Table[0].package_id);
                        $('.price_matrix_id').val(data1.Table[0].price_matrix_id);
                        $('.is_doctor').val(data1.Table[0].is_doctor);
                        $('.base_amount_type').val(data1.Table[0].base_amount_type);
                        $('.base_amount_value').val(data1.Table[0].base_amount);
                        $('.is_workorder').val(data1.Table[0].is_workorder);
                        if (data1.Table[0].is_workorder == 3 || data1.Table[0].base_amount_type==5) {
                            $('#txt_quantity').attr('onkeyup', 'numeric_dot("txt_quantity")');
                        }
                        else {
                            $('#txt_quantity').attr('onkeyup', 'numeric_only("txt_quantity")');
                        }
                        if ($('#hiddenRole_id').val() == 2 || data1.Table[0].base_amount_type == 4) {
                            $('.txt_date').prop("disabled", false);
                        }
                        $('#His_tax').val(data1.Table[0].is_tax);
                        $('#Htax_percentage').val(data1.Table[0].tax_percentage);
                        if (data1.Table[0].is_doctor == 1) {
                            $('#divSelDoctor').show();
                            $('#divdocFee').show();
                            // $('#divSelDoctorth').show();
                            $('.txt_doctor_name').prop('disabled', false);
                           
                           //- LoadDoctor();
                        }
                        else {
                            $('#divSelDoctor').hide();
                            $('#divdocFee').hide();
                            $('#doc_fee').val('');
                            //  $('#divSelDoctorth').hide();
                          
                            $('.txt_doctor_name').val('');
                            $('#Htxt_doctor_name').val('0');
                            $('.txt_doctor_name').prop('disabled', true);
                        }
                    }
                }
            }
        }
    })
}

//Individual Service Amount On change
$('.txt_unitRate').change(function () {
    debugger;
    if ($('.base_amount_type').val() == 1) {
        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
            $('#Ptxt_unitRate').show();
            $('#Ptxt_unitRate').fadeOut(8000);
            $('#Ptxt_unitRate').html('Enter the amount');
            $('.txt_unitRate').focus();
            $('.txt_unitRate').val('');
            $('.txt_totalamt').html(parseFloat(0).toFixed(2));
            return false;
        }
    }
    if ($('.base_amount_type').val() == 3) {
        debugger;
        var range_min = $('#Hrange_min').val();
        var range_max = $('#Hrange_max').val();

        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0 || (parseInt($('.txt_unitRate').val()) < parseInt(range_min) || parseInt($('.txt_unitRate').val()) > parseInt(range_max))) {

            $('.txt_unitRate').val(range_min)

        }
    }
    if ($('.base_amount_type').val() == 2) {
        debugger;
        var range_min = $('#Hrange_min').val();      

        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0 || parseInt($('.txt_unitRate').val()) < parseInt(range_min)) {

            $('.txt_unitRate').val(range_min);

            alert('Value is Lesser than Base Amount');
        }
    }
    var quantity = $('.txt_quantity').val();
    var unit = $('.txt_unitRate').val();
    var total = parseFloat(unit) * parseFloat(quantity);
    $('.txt_totalamt').html(total.toFixed(2));
})

//Individual Quantity Check ( (from Request Page to Billing)(For IP only/OP iinsurance)- Checks how many quantities are used in work order and based on that edit will happen)
$('.txt_quantity').change(function () {
    debugger;
    var visit_type = $("input[name='optradio']:checked").val()

    //if ($('#hdnvisit_report_id').val() != '' && (visit_type == 2 || (visit_type == 1 && $('#His_insurance').val() == 1 && $('#hndbilling_no').val() != 0 && $('#hndbilling_no').val() != ''))) {
    if ($('#hdnvisit_report_id').val() != '' && (visit_type == 2 || (visit_type == 1 && $('#hndbilling_no').val() != 0 && $('#hndbilling_no').val() != ''))) {
        if ($('#btn_add').html() == 'Update') {
            if ($('#work_quantity').val() > $('.txt_quantity').val()) {
                $('#hupdateCount').val(0);
                debugger;
                if (visit_type == 1) {
                    $('#Ptxt_quantity').show();
                    $('#Ptxt_quantity').fadeOut(8000);
                    $('#Ptxt_quantity').html('Quantity should be atleast ' + $('#work_quantity').val());
                    $('.txt_quantity').focus();
                    $('.txt_quantity').val($('#work_quantity').val());
                    $('.txt_quantity').change();
                    return false;
                }

                //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>", '' + $('#work_quantity').val() + ' quantity used already.Are u sure want to edit?',
                //{
                //    closeButton: true,
                //    progressBar: true,
                //    allowHtml: true,
                //    timeOut: 20000000,

                //    onShown: function (toast) {
                //        $("#confirmationRevertYes").click(function () {
                //            quantity_check();
                //        })
                //        $("#confirmationRevertNo").click(function () {
                //            $('#hupdateCount').val(1)
                //            $('.txt_quantity').val($('#work_quantity').val());
                //            quantity_check();
                            
                //        })
                //    }
                //})
            }
            else {
                quantity_check();
            }
        }
        else {
            quantity_check();
        }
    }
    else {
        quantity_check();
    }

});
function quantity_check() {
    debugger;
    var totval = '';
    var quantity = $('.txt_quantity').val();
    var unitRate = $('.txt_unitRate').val()
    var txt_discount = $('.txt_discount').val();
    var sel_discount_type = $('.sel_discount_type').val();
    totval = quantity * unitRate;
    //if (sel_discount_type==1) {
    //    totval = totval - txt_discount
    //}
    //else if (sel_discount_type == 2) {
    //    totval = totval - ((totval / 100) * txt_discount)
    //}
    //else {
    //    totval = totval;
    //}
    debugger;

    $('.txt_totalamt').html(totval.toFixed(2));
}
//

//Service Add Function Starts
$('#btn_add').click(function () {

    if ($('#btn_add').html() == 'Update') {
        serviceupdate();
    }
    else {
        serviceadd();
    }
    var collectedamount = 0;
    var balanceamount = 0;
    var txt_received_amt = $('.txt_totalamt').html();

    var balance_amount = $('#balance_amount').html();
    var total_net_amount = $('#total_net_amount').html();
    var collect_payment1 = $('#collect_payment').html();


    collectedamount = parseFloat(collect_payment1)
    if (parseFloat($('#refund_amount').html()) != 0) {
        balanceamount = 0;
    }
    else {
        balanceamount = parseFloat(total_net_amount) - parseFloat(collectedamount);
        balanceamount = Math.round(balanceamount).toFixed(2);
    }
    //if (parseFloat($('#advance_amount').html()) > total_net_amount) {
    //    $('#collect_payment').html(parseFloat(total_net_amount));
    //}
    //else {
    //    $('#collect_payment').html(collectedamount.toFixed(2));
    //}
    //balanceamount = balanceamount - parseFloat(($('#auth_amt').val()));
    $('#balance_amount').html(Math.round(balanceamount).toFixed(2));
    $('#txt_received_amt').val(Math.round(balanceamount));
    $('#sms_amount').val(Math.round(balanceamount));
    //$('#auth_amt').change();
    claim_calculation();
});

//Service Add 
function serviceadd() {
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    if ($('.txt_service_name').val() == "") {
        $('#Ptxt_service_name').show();
        $('#Ptxt_service_name').fadeOut(8000);
        $('#Ptxt_service_name').html('Please select The service name');
        $('.txt_service_name').focus();
        $('.txt_service_name').val('');
        return false;
    }
    if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
        $('#Ptxt_unitRate').show();
        $('#Ptxt_unitRate').fadeOut(8000);
        $('#Ptxt_unitRate').html('Enter the amount');
        $('.txt_unitRate').focus();
        $('.txt_unitRate').val('');
        $('.txt_totalamt').html(parseFloat(0).toFixed(2));
        return false;
    }
    if ($('.txt_quantity').val() == "" || $('.txt_quantity').val() == 0) {
        $('#Ptxt_quantity').show();
        $('#Ptxt_quantity').fadeOut(8000);
        $('#Ptxt_quantity').html('Please enter the quantity');
        $('.txt_quantity').focus();
        $('.txt_quantity').val('');
        return false;
    }
    //txt_doctor_name
   // if ($('.is_doctor').val() == 1) {
        //if ($.trim($('.txt_doctor_name').val()) == '' || $('#Htxt_doctor_name').val() == 0) {
        //    $('#Ptxt_doctor_name').show();
        //    $('#Ptxt_doctor_name').fadeOut(8000);
        //    $('#Ptxt_doctor_name').html('Select Doctor Name');
        //    $('.txt_doctor_name').focus();
        //    return false;
        //}
        //if ($('#doc_fee').val() == '' || $('#doc_fee').val() == '-' || $('#doc_fee').val() == '0') {
        //    $('#Pdoc_fee').show();
        //    $('#Pdoc_fee').fadeOut(8000);
        //    $('#Pdoc_fee').html('Please enter doctor fee');
        //    $('#doc_fee').focus();
        //    return false;
        //}
   // }
    //if ($('#txt_remarks').hasClass("hidden") == false) { //commneted by Tharuni -Medway Req
    //    if ($.trim($('#txt_remarks').val()) == "") {
    //        $('#Ptxt_remarks').show();
    //        $('#Ptxt_remarks').fadeOut(8000);
    //        $('#Ptxt_remarks').html('Please Enter the description');
    //        $('#txt_remarks').focus();
    //        return false;
    //    }
    //}

    var rowCount = $('#service_tbl tbody tr').length;
    if (rowCount == 0) {
        rowCount = 1
    }
    else {
        var id = $('#service_tbl tbody tr:last').attr('id');
        id = id.split('_');
        rowCount = parseInt(id[1]) + (1);
    }
    debugger;
    var sel_discount_type = $('.sel_discount_type').val();
    var d_amt = ($('.txt_discount').val() == '') ? 0 : $('.txt_discount').val();
    var discount_amount = 0.0;
    if (sel_discount_type == 1) {
        sel_discount_type = '₹';
        discount_amount = parseFloat(d_amt);
    }
    else {
        sel_discount_type = '%';
        discount_amount = parseFloat($('.txt_totalamt').html()) * (parseFloat(d_amt) / 100);
    }
    debugger;
    var tot_net_amt = parseFloat($('.txt_totalamt').html()) - discount_amount
    var doc_name = '';
    if ($('.txt_doctor_name').val() == 0 || $('.txt_doctor_name').val() == '' || $('.txt_doctor_name').val() == null) {
        doc_name = ''
    }
    else {
        //doc_name = $('.txt_doctor_name option:selected').text() + '/' + $.trim($('#doc_fee').val());
        doc_name = $('.txt_doctor_name').val() + '/' + $.trim($('#doc_fee').val());

    }
    var ser_date = '';
    if ($('.txt_end_date').val() != '') {
        ser_date = $('.txt_date').val() + '-' + $('.txt_end_date').val();
    }
    else {
        ser_date = $('.txt_date').val()
    }
    var tax_amount = 0.0;
    if ($('#Htax_percentage').val() != 0) {
        tax_amount = (parseFloat($('.txt_totalamt').html()) * parseFloat($('#Htax_percentage').val()) / 100)
    }

    var ObjArr = {
        rowCount: rowCount,
        id:'tr_'+rowCount,
        base_amount_type: $('.base_amount_type').val(),
        service_name: $('.txt_service_name').val(),
        quantity: $('.txt_quantity').val(),
        Rate: $('.txt_unitRate').val(),
        base_amount_value: $('.base_amount_value').val(),
        TotalAmt: $('.txt_totalamt').html(),
        discount: $('.txt_discount').val(),
        sel_discount_type: sel_discount_type,
        discount_amount: discount_amount,
        tax_percentage: $('#Htax_percentage').val(),
        tax_amount: tax_amount,
        tot_net_amt: parseFloat(parseFloat(tax_amount) + parseFloat(tot_net_amt)),
        ser_date: ser_date,
        doc_name: doc_name,
        remarks: $('#txt_remarks').val(),
        doctor_id: $('#Htxt_doctor_name').val(),
        master_service_id: $('.master_service_id').val(),
        package_id: $('.package_id').val(),
        price_matrix_id: $('.price_matrix_id').val(),
        request_id: 0,
        request_details_id: 0,
        range_min: $('#Hrange_min').val(),
        range_max: $('#Hrange_max').val(),
        billing_details_id: 0,
        charge_percentage: 0,
        is_workorder: $('.is_workorder').val(),
        is_doctor: $('.is_doctor').val(),
        is_description: $('#His_description').val(),
        CRMService: $('#hCRMService').val(),
        PharmacyBillNo: 0,
        estimation_details_id: 0,
        estimation_no: 0,
        editDelete: '<span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span>'


    }
    Service_Org_Arr.push(ObjArr);

    var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour($('.base_amount_type').val()) + '" ><td>' + $('.txt_service_name').val() + '</td><td>' + $('.txt_quantity').val() + '</td><td>' + parseFloat($('.txt_unitRate').val()).toFixed(2) + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat($('.base_amount_value').val()) + ')</span></td>'
    tr += '<td>' + parseFloat($('.txt_totalamt').html()).toFixed(2) + '</td><td>' + +$('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + parseFloat(discount_amount).toFixed(2) + '</td><td>' + $('#Htax_percentage').val() + '%</td><td>' + parseFloat(parseFloat(tax_amount) + parseFloat(tot_net_amt)).toFixed(2) + '</td><td>' + ser_date + '</td><td>' + doc_name + '</td><td>' + $('#txt_remarks').val() + '</td><td class="hide">' + $('#Htxt_doctor_name').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('.package_id').val() + '</td><td class="hide">' + $('.price_matrix_id').val() + '</td><td class="hide">0</td><td class="hide">0</td><td class="hide">' + $('.base_amount_type').val() + '</td><td class="hide">' + $('#Hrange_min').val() + '</td><td class="hide">' + $('#Hrange_max').val() + '</td><td class="hide">0</td><td class="hide">' + parseFloat(tax_amount).toFixed(2) + '</td><td class="hide">0</td><td class="hide">' + parseFloat($('.base_amount_value').val()) + '</td><td class="hide">' + $('.is_workorder').val() + '</td><td class="hide">' + $('.is_doctor').val() + '</td><td class="hide">' + $('#His_description').val() + '</td><td class="hide">' + $('#hCRMService').val() + '</td><td class="hide">0</td><td class="hide">0</td><td class="hide">0</td>'
    //tr += '<td>' + $('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + $('.txt_totalamt').html() + '</td><td>' + $('.txt_date').val() + '</td><td>' + doc_name + '</td><td class="hide">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('.package_id').val() + '</td><td class="hide">' + $('.price_matrix_id').val() + '</td><td class="hide">0</td>'
    tr += '<td><span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
    $('#service_tbl tbody').append(tr);
    $('#His_description').val(0);
    $('.txt_service_name').val('');
    $('.txt_quantity').val('');
    $('.txt_unitRate').val('');
    $('.txt_discount').val(0.0);
    $('.txt_totalamt').html('');
    $('.txt_doctor_name').val('');
    $('#Htxt_doctor_name').val('0');
    $('.master_service_id').val('');
    $('.package_id').val('');
    $('.price_matrix_id').val('');
    $('.base_amount_type').val('');
    $('.base_amount_value').val(0.0);
    $('.is_workorder').val('');
    $('.is_doctor').val('');
    $('.txt_end_date').val('');
    $('#txt_remarks').val('');
    $('#His_tax').val(0);
    $('#Htax_percentage').val(0);
    $('#hCRMService').val(0);
    $('#txt_remarks').addClass("hidden");
    $('.txt_quantity').prop('disabled', false);
    $('#divSelDoctor').hide();
    var dateNow = new Date();

    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    $('.txt_date').val(new_date);
    $('.txt_date').prop("disabled", true);
    $('#datetimepicker2').hide();
    $('.datetimepicker1').datetimepicker({
        //format: 'DD/MM/YYYY hh:mm A',
        defaultDate: new_date
    });
    $('#Ptxt_unitRate').html('');
    $('.txt_unitRate').prop('disabled', true);
    $('#doc_fee').val(0);
    $('#divdocFee').hide();
    $('.txt_service_name').focus();
    
    discount_percentage_cal();
})
}


//Service Update
function serviceupdate() {
    debugger;
    var visit_type = $("input[name='optradio']:checked").val()
    if ($('.txt_service_name').val() == "") {
        $('#Ptxt_service_name').show();
        $('#PtxtPaitentSearch_bill').fadeOut(8000);
        $('#PtxtPaitentSearch_bill').html('Please select The service name');
        $('.txtPaitentSearch_bill').focus();
        $('.txtPaitentSearch_bill').val('');
        return false;
    }
    if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
        $('#Ptxt_unitRate').show();
        $('#Ptxt_unitRate').fadeOut(8000);
        $('#Ptxt_unitRate').html('Enter the amount');
        $('.txt_unitRate').focus();
        $('.txt_unitRate').val('');
        $('.txt_totalamt').html(0.00);
        return false;
    }
    if ($('.txt_quantity').val() == "" || $('.txt_quantity').val() == 0) {
        $('#Ptxt_quantity').show();
        $('#Ptxt_quantity').fadeOut(8000);
        $('#Ptxt_quantity').html('Please enter the quantity');
        $('.txt_quantity').focus();
        $('.txt_quantity').val('');
        return false;
    }
    if (visit_type == 2) {
        if (parseFloat($('.txt_quantity').val()) < parseFloat($('#work_quantity').val()) && $('#hupdateCount').val()==0) {
            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>", '' + $('#work_quantity').val() + ' quantity used already.Are u sure want to edit?',
           {
               
               progressBar: true,
               allowHtml: true,
               

               onShown: function (toast) {
                   $("#confirmationRevertYes").click(function () {
                       $('#hupdateCount').val(1);
                       quantity_check();
                   })
                   $("#confirmationRevertNo").click(function () {
                       $('#hupdateCount').val(1)
                       $('.txt_quantity').val($('#work_quantity').val());
                       quantity_check();

                   })
               }
           })
            return false;
        }
    }


    var sel_discount_type = $('.sel_discount_type').val();
    var d_amt = ($('.txt_discount').val() == '') ? 0 : $('.txt_discount').val();
    var discount_amount = 0.0;
    if (sel_discount_type == 1) {
        sel_discount_type = '₹';
        discount_amount = parseFloat(d_amt);
    }
    else {
        sel_discount_type = '%';
        discount_amount = parseFloat($('.txt_totalamt').html()) * (parseFloat(d_amt) / 100);
    }
    debugger;
    var tot_net_amt = parseFloat($('.txt_totalamt').html()) - discount_amount

    //if ($('.is_doctor').val() == 1) {
    //    if ($.trim($('.txt_doctor_name').val()) == '' || $('#Htxt_doctor_name').val() == 0) {
    //        $('#Ptxt_doctor_name').show();
    //        $('#Ptxt_doctor_name').fadeOut(8000);
    //        $('#Ptxt_doctor_name').html('Please doctor name is required.');
    //        $('.txt_doctor_name').focus();
    //        return false;
    //    }
    //    if ($('#doc_fee').val() == '' || $('#doc_fee').val() == '-' || $('#doc_fee').val() == '0') {
    //        $('#Pdoc_fee').show();
    //        $('#Pdoc_fee').fadeOut(8000);
    //        $('#Pdoc_fee').html('Please enter doctor fee');
    //        $('#doc_fee').focus();
    //        return false;
    //    }
    //}
    //if ($('#txt_remarks').hasClass("hidden") == false) { //commented by Tharuni for Med REq
    //    if ($.trim($('#txt_remarks').val()) == "") {
    //        $('#Ptxt_remarks').show();
    //        $('#Ptxt_remarks').fadeOut(8000);
    //        $('#Ptxt_remarks').html('Please Enter the description');
    //        $('#txt_remarks').focus();
    //        return false;
    //    }
    //}
    debugger;
    var doc_name = '';
    if (($('.txt_doctor_name').val() == 0 || $('.txt_doctor_name').val() == '' || $('.txt_doctor_name').val() == null)) {
        doc_name = ''
    }
    else {
        //doc_name = $('.txt_doctor_name option:selected').text() + '/' + $.trim($('#doc_fee').val());
        doc_name = $('.txt_doctor_name').val() + '/' + $.trim($('#doc_fee').val());

        
        
       

    }
    var ser_date = '';
    if ($('.txt_end_date').val() != '') {
        ser_date = $('.txt_date').val() + '-' + $('.txt_end_date').val();
    }
    else {
        ser_date = $('.txt_date').val()
    }
    var tax_amount = 0.0;
    if ($('#Htax_percentage').val() != 0) {
        tax_amount = (parseFloat($('.txt_totalamt').html()) * parseFloat($('#Htax_percentage').val()) / 100)
    }
    var tr = '<td>' + $('.txt_service_name').val() + '</td><td>' + $('.txt_quantity').val() + '</td><td>' + $('.txt_unitRate').val() + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat($('.base_amount_value').val()) + ')</span></td>'
    tr += '<td>' + $('.txt_totalamt').html() + '</td><td>' + +$('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + parseFloat(discount_amount).toFixed(2) + '</td><td>' + $('#Htax_percentage').val() + '%</td><td>' + (parseFloat(tax_amount) + parseFloat(tot_net_amt)) + '</td><td>' + ser_date + '</td><td>' + doc_name + '</td><td>' + $('#txt_remarks').val() + '</td><td class="hide">' + $('#Htxt_doctor_name').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('.package_id').val() + '</td><td class="hide">' + $('.price_matrix_id').val() + '</td><td class="hide">' + $('.Hrequestid').val() + '</td><td class="hide">' + $('.request_details_id').val() + '</td><td class="hide">' + $('.base_amount_type').val() + '</td><td class="hide">' + $('#Hrange_min').val() + '</td><td class="hide">' + $('#Hrange_max').val() + '</td><td class="hide">' + $('.billing_details_id').val() + '</td><td class="hide">' + tax_amount + '</td><td class="hide">' + $('#hdn_charge_percentage').val() + '</td><td class="hide">' + parseFloat($('.base_amount_value').val()) + '</td><td class="hide">' + $('.is_workorder').val() + '</td><td class="hide">' + $('.is_doctor').val() + '</td><td class="hide">' + $('#His_description').val() + '</td><td  class="hide">' + $('#hCRMService').val() + '</td>'
    tr += '<td  class="hide">' + $('#HPharmacyBilling').val() + '</td><td  class="hide">' + $('#HEstimationDtlId').val() + '</td><td  class="hide">' + $('#HdnEstimationNo').val() + '</td>'
    //tr += '<td>' + $('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + $('.txt_totalamt').html() + '</td><td>' + $('.txt_date').val() + '</td><td>' + doc_name + '</td><td class="hide">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('.package_id').val() + '</td><td class="hide">' + $('.price_matrix_id').val() + '</td><td class="hide">' + $('.Hrequestid').val() + '</td>'
    tr += '<td><span class="btn btn-xs  mr-10 btn-edit service_edit" onclick=ServiceEdit("' + trid + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("' + trid + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td>';
    $('#' + trid).html(tr);
    Service_Org_Arr.map((item) => {
        if (item.id == trid) {
           
            item.base_amount_type = $('.base_amount_type').val(),
            item.service_name = $('.txt_service_name').val(),
            item.quantity = $('.txt_quantity').val(),
            item.Rate = $('.txt_unitRate').val(),
            item.base_amount_value = $('.base_amount_value').val(),
            item.TotalAmt = $('.txt_totalamt').html(),
            item.discount = $('.txt_discount').val(),
            item.sel_discount_type = sel_discount_type,
            item.discount_amount = discount_amount,
            item.tax_percentage = $('#Htax_percentage').val(),
            item.tax_amount = tax_amount,
            item.tot_net_amt = (parseFloat(tax_amount) + parseFloat(tot_net_amt)),
            item.ser_date = ser_date,
            item.doc_name = doc_name,
            item.remarks = $('#txt_remarks').val(),
            item.doctor_id = $('#Htxt_doctor_name').val(),
            item.master_service_id = $('.master_service_id').val(),
            item.package_id = $('.package_id').val(),
            item.price_matrix_id = $('.price_matrix_id').val(),
            item.request_id = $('.Hrequestid').val(),
            item.request_details_id = $('.request_details_id').val(),
            item.range_min= $('#Hrange_min').val(),
            item.range_max= $('#Hrange_max').val(),
            item.billing_details_id = $('.billing_details_id').val(),
            item.charge_percentage = $('#hdn_charge_percentage').val(),
            item.is_workorder=$('.is_workorder').val(),
            item.is_doctor=$('.is_doctor').val(),
            item.is_description = $('#His_description').val(),
            item.CRMService = $('#hCRMService').val(),
            item.PharmacyBillNo=$('#HPharmacyBilling').val(),
            item.estimation_details_id= $('#HEstimationDtlId').val(),
            item.estimation_no=$('#HdnEstimationNo').val()
        }
        return item;
    })
    $('#His_description').val(0);
    $('.txt_service_name').val('');
    $('.txt_quantity').val('');
    $('.txt_unitRate').val('');
    $('.txt_discount').val(0.0);
    $('.txt_totalamt').html('');
    $('.txt_doctor_name').val('');
    $('.master_service_id').val('');
    $('.package_id').val('');
    $('.price_matrix_id').val('');
    $('.is_doctor').val('');
    $('#btn_add').html('Add');
    $('.base_amount_type').val(0);
    $('.request_details_id').val(0);
    $('.Hrequestid').val(0);
    $('.txt_end_date').val('');
    $('#txt_remarks').val('');
    $('#work_quantity').val('');
    $('#txt_remarks').addClass("hidden");
    $('.txt_quantity').prop('disabled', false);
    $('.is_doctor').val('');
    $('.base_amount_value').val(0.0);
    $('.is_workorder').val('');
    $('#hCRMService').val(0)
    $('#HPharmacyBilling').val(0),
      $('#HEstimationDtlId').val(0)
    $('#HdnEstimationNo').val(0)
    var dateNow = new Date();

    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    $('.txt_date').val(new_date);
    $('.txt_date').prop("disabled", true);
    $('#datetimepicker2').hide();
    $('.datetimepicker1').datetimepicker({
        //format: 'DD/MM/YYYY hh:mm A',
        defaultDate: new_date
    });
    $('#divSelDoctor').hide();
    $('#Ptxt_unitRate').html('');
    $('.txt_unitRate').prop('disabled', true);
    $('#doc_fee').val(0);
    $('#divdocFee').hide();
    discount_percentage_cal();
}




//Service Edit
var trid = "";
//$("#service_tbl").on('click', '.service_edit', function () {
function ServiceEdit(id){
    // get the current row
    debugger;
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    var count = 0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id1 = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id1 = id1.split('_');
        id1 = id1[1]



        var is_final = $('#td_final_' + id1).attr('data-id');

        if (is_final == 1) {
            count++;
        }

    }
    if (count > 0) {
        toastr.warning("Approved amount collected.You can't edit the service");
        return false;
    }

    var visit_type = $("input[name='optradio']:checked").val()
   // var id = $(this).closest("tr").prop("id");
    if ($('#hdnvisit_report_id').val() != '' && (visit_type == 2 || (visit_type == 1 && $('#hndbilling_no').val() != 0 && $('#hndbilling_no').val() != ''))) {

        var master_service_id = $('#' + id).find("td").eq(12).html();
        var request_id = $('#' + id).find("td").eq(15).html();
        var billno = ($('#hndbilling_no').val() == '') ? 0 : $('#hndbilling_no').val()
        var billing_details_id = $('#' + id).find("td").eq(20).html()
        var DoctorData = {
            request_id: request_id,
            master_service_id: master_service_id,
            Dml_Indicator: 'WSE',
            visit_type: visit_type,
            request_code: billno,
            visit_id: billing_details_id
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Request',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                debugger
                console.log(data);
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data;
                    if (data1[0].StringMsg == 'success') {
                        editService(id);
                    }
                    else {
                        if (data1[0].quantity == 0) {
                            toastr.warning('Service already used.You cannot update')
                        }
                        else {

                            $('#work_quantity').val(data1[0].quantity);
                            editService(id);
                        }
                    }
                }
                else {
                    console.log(data1)

                }
            }
        })
    }
    else {
        editService(id);
    }

});


}

//});
function editService(id) {
    debugger;
    $('.txt_service_name').focus();
    trid = $('#' + id).closest('tr').attr('id');
    var currentRow = $('#' + id).closest("tr");
    $('#hupdateCount').val(0)
    var col1 = currentRow.find("td:eq(0)").text(); // service_name
    var col2 = currentRow.find("td:eq(1)").text(); // Quantity
    var col3 = currentRow.find("td:eq(2)").text().split('(')[0]; // Rate
    var col4 = currentRow.find("td:eq(4)").text(); // Discount
    var col5 = currentRow.find("td:eq(3)").text(); // Total amount
    var col6 = currentRow.find("td:eq(8)").text(); // get current row 3rd TD
    var col7 = currentRow.find("td:eq(9)").text(); // get current row 3rd TD
    var col8 = currentRow.find("td:eq(11)").text(); // get current row 3rd TD
    var col9 = currentRow.find("td:eq(12)").text(); // get current row 3rd TD
    var col10 = currentRow.find("td:eq(13)").text(); // get current row 3rd TD
    var col11 = currentRow.find("td:eq(14)").text(); // get current row 3rd TD
    var col12 = currentRow.find("td:eq(15)").text(); // get current row 3rd TD
    var col13 = currentRow.find("td:eq(16)").text(); // get current row 3rd TD
    var col14 = currentRow.find("td:eq(17)").text(); // get current row 3rd TD
    var col15 = currentRow.find("td:eq(18)").text(); // get current row 3rd TD
    var col16 = currentRow.find("td:eq(19)").text(); // get current row 3rd TD
    var col17 = currentRow.find("td:eq(10)").text();
    var col18 = currentRow.find("td:eq(20)").text();
    var col19 = currentRow.find("td:eq(6)").text();//tax_percentage
    var col20 = currentRow.find("td:eq(22)").text();
    var col21 = currentRow.find("td:eq(23)").text();//base amount value
    var col22 = currentRow.find("td:eq(24)").text();//is_workorder
    var col23 = currentRow.find("td:eq(25)").text();//is_doctor
    var col24 = currentRow.find("td:eq(26)").text();//is_description
    var col25 = currentRow.find("td:eq(27)").text();//CRMService
    var col26 = currentRow.find("td:eq(28)").text();//PharmacyBillNo
    var col27 = currentRow.find("td:eq(29)").text();//EstimationDetailsId
    var col28 = currentRow.find("td:eq(30)").text();//EstimationNo
    $('#hdn_charge_percentage').val(col20)
    $('#Htax_percentage').val(col19.split('%')[0]);
    if (col14 == 4) {
        var date1 = col6.split('-')[0];
        var date2 = col6.split('-')[1];
        $('#datetimepicker2').show();
        $('.txt_date').val(date1);
        $('.txt_end_date').val(date2);
        $('.txt_quantity').prop('disabled', true);
    }
    else {
        $('.txt_date').val(col6);
    }
    if (col14 == 1 || col14 == 3) {
        $('.txt_unitRate').prop('disabled', false)
        if (col14 == 3) {
            $('#Ptxt_unitRate').html("Enter the amount between " + col15 + ' - ' + col16);
            $('#Hrange_min').val(col15);
            $('#Hrange_max').val(col16);
        }
    }
    else if (col14 == 2 || col14==5) {   // added by nandhini for medway req to allow fixed type also to edit price
        if (($('#hndbilling_no').val() == null || $('#hndbilling_no').val() == "") || ($('#hdnrequest_id').val() == null || $('#hdnrequest_id').val() == "")) {
            $('.txt_unitRate').prop('disabled', false)
            $('#Hrange_min').val(col15);
        }
    }
    else {
        $('.txt_unitRate').prop('disabled', true)
    }
    col4 = col4.split(' ');
    var discount = col4[0];
    var type = col4[1];
    if (type == '₹') { type = 1; }
    else if (type == '%') { type = 2; }
    else { type = ''; }
    //if ($.trim(col17) != '') {
    if(col24==1){
        $('#txt_remarks').val(col17);
        $('#txt_remarks').removeClass("hidden");
        $('#His_description').val('1');
    }
    $('.txt_service_name').val(col1);
    $('.txt_quantity').val(col2);
    $('.txt_unitRate').val(col3);
    $('.txt_discount').val(discount);
    $('.sel_discount_type').val(type);
    $('.txt_totalamt').html(col5);
    debugger;
   
    //if ( col7[0] != '' && col7[0] != null) {
    if (col23==1) {
        col7 = col7.split('/');
        $('#doc_fee').val((col7[1]=='0'||col7[1]=='0.00')?'':col7[1]);
        $('#divdocFee').show();
        $('#divSelDoctor').show();
        var dName = (col7[0] == 0) ? '' : col7[0]
        $('.txt_doctor_name').val(dName);
        $('#Htxt_doctor_name').val(col8);
        $('.txt_doctor_name').attr('disabled', false);
        $('.is_doctor').val(1);
        //$(".txt_doctor_name option").each(function () {
        //    if ($(this).text() == col7[0]) {
        //        $('#divSelDoctor').show();
        //        $('.this').val(col8);
        //        $(this).prop('selected', 'selected');
        //        $('.txt_doctor_name').attr('disabled', false);
        //    }
        //});
    }
    else {
        $('#divdocFee').hide();
        $('#divSelDoctor').hide();
        $('.txt_doctor_name').attr('disabled', true);
        $('.txt_doctor_name').val('');
        $('#Htxt_doctor_name').val('0');
        $('#doc_fee').val('');
        $('.is_doctor').val('');
    }

    $('#HPharmacyBilling').val(col26);
    $('#HEstimationDtlId').val(col27);
    $('#HdnEstimationNo').val(col28);
    $('#hCRMService').val(col25);
    $('.master_service_id').val(col9);
    $('.package_id').val(col10);
    $('.price_matrix_id').val(col11);
    $('.Hrequestid').val(col12);
    $('.base_amount_type').val(col14);
    $('.request_details_id').val(col13);
    $('.billing_details_id').val(col18);
    $('.base_amount_value').val(col21);
    $('.is_workorder').val(col22);
    if (col22 == 3 || col14==5) {
        $('#txt_quantity').attr('onkeyup', 'numeric_dot("txt_quantity")');
    }
    else {
        $('#txt_quantity').attr('onkeyup', 'numeric_only("txt_quantity")');
    }
    if ($('#hiddenRole_id').val() == 2 || col14 == 4) {
        $('.txt_date').prop("disabled", false);
    }
    $('#btn_add').html('Update');
}

//Service Delete 
//$("#service_tbl").on('click', '.service_delete', function () {
function service_delete(id){
    //"$(this).closest(\'tr\').remove();"
    debugger;
    //$(this).closest("tr").remove();
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
   
    var visit_type = $("input[name='optradio']:checked").val()
    // var id = $(this).closest("tr").prop("id");
    if ($('#tbl_payment tr').length > 0) {
        //toastr.warning('Service can\'t be deleted.Amount collected');
        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>", 'Amount Collected.Are you sure want to delete the service?',
   {
       closeButton: true,
       progressBar: true,
       allowHtml: true,
       timeOut: 20000000,

       onShown: function (toast) {
           $("#confirmationRevertYes").click(function () {
               $('#tbl_payment').empty();
               var refund_amt = parseFloat($('#refund_amount').html()) - parseFloat($('#collect_payment').html())
               $('#refund_amount').html(Math.round(parseFloat(refund_amt)).toFixed(2))
               $('#collect_payment').html(0);
               toastr.warning('Kindly Enter the amount again');
               delete_sub(id, visit_type, 1)
           })
           $("#confirmationRevertNo").click(function () {
               return false;
           })
       }
   })

        //return false;
    }
    else {
        delete_sub(id, visit_type, 0)
    }
});
    
}
//Service delete sub function
function delete_sub(id, visit_type,count) {
    if ($('#hdnvisit_report_id').val() != '' && (visit_type == 2 || (visit_type == 1 && $('#hndbilling_no').val() != 0 && $('#hndbilling_no').val() != ''))) {

        var master_service_id = $('#' + id).find("td").eq(12).html();
        var request_id = $('#' + id).find("td").eq(15).html();
        var billno = ($('#hndbilling_no').val() == '') ? 0 : $('#hndbilling_no').val()

        var DoctorData = {
            request_id: request_id,
            dml_indicator: 'DCC',
            master_service_id: master_service_id,
            visit_type: visit_type,
            billing_no: billno,
            billing_details_id: $('#' + id).find("td").eq(20).html()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Billing',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                debugger
                console.log(data);
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data.Table;
                    if (data1[0].StringMsg == 'success') {
                        if (count == 0) {
                            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 want to delete the service?',
                    {
                        closeButton: true,
                        progressBar: true,
                        allowHtml: true,
                        timeOut: 20000000,

                        onShown: function (toast) {
                            $("#confirmationRevertYes").click(function () {
                                amount_calculation(id, request_id, master_service_id, visit_type)
                                //delete_check(id, request_id, master_service_id, 2);
                                Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);
                            })
                        }
                    })
                        }
                        else {
                            amount_calculation(id, request_id, master_service_id, visit_type)
                            Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);
                        }

                        //discount_percentage_cal();
                        //$('#auth_amt').change();

                    }
                    else {
                        if (visit_type == 2) {
                            if (count == 0) {
                                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>", 'Service already used.Are you sure want to delete the service?',
                               {
                                   closeButton: true,
                                   progressBar: true,
                                   allowHtml: true,
                                   timeOut: 20000000,

                                   onShown: function (toast) {
                                       $("#confirmationRevertYes").click(function () {

                                           //$('#' + id).remove();
                                           amount_calculation(id);
                                           Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);
                                       })
                                   }
                               })
                            }
                            else {
                                amount_calculation(id);
                                Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);
                            }
                        }
                        else {
                            toastr.warning('Service already used.You cannot delete')
                        }
                    }
                }
                else {
                    console.log(data1)

                }
            }
        })
    }
    else {
        if (count == 0) {
            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 want to delete the service?',
                   {
                       closeButton: true,
                       progressBar: true,
                       allowHtml: true,
                       timeOut: 20000000,

                       onShown: function (toast) {
                           $("#confirmationRevertYes").click(function () {

                               //$('#' + id).remove();
                               amount_calculation(id);
                               Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);

                           })
                       }
                   })
        }
        else {
            amount_calculation(id);
            Service_Org_Arr = Service_Org_Arr.filter((item) =>item.id != id);
        }

        //discount_percentage_cal();
        //$('#auth_amt').change();
    }

}

function delete_check(id, request_id, master_service_id, visit_type) {
    debugger;
    var billno = ($('#hndbilling_no').val() == '') ? 0 : $('#hndbilling_no').val()
    var DoctorData = {
        request_id: request_id,
        dml_indicator: 'DC',
        master_service_id: master_service_id,
        visit_type: visit_type,
        billing_no: billno
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billing',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data.Table;
                //if (data1[0].StringMsg == 'success') {
                //$('#' + id).remove();
                //amount_calculation();
                //}
            }
        }
    })
}

//Billing Submit Validation 
$('#btn_submit').click(function () {
    debugger;
    var bill1 = CheckFilter();
    $.when(bill1)
.then(function (data) {
    if ($('#hdnvisit_report_id').val() == "") {
        toastr.warning('Please generated the visit report');
        return false;
    }
    var rowCount = $('#service_tbl tbody tr').length
    if (rowCount == 0) {
        toastr.warning('Please add the service');
        return false;
    }
    //if ($('#His_insurance').val() == 1) {
    //    //if ($('#claim_no').val() == "" || $('#claim_no').val() == null) {
    //    //    $('#Pclaim_no').show();
    //    //    $('#Pclaim_no').fadeOut(8000);
    //    //    $('#Pclaim_no').html('Please Enter Claim Number');
    //    //    $('#claim_no').focus();
    //    //    $('#claim_no').val('');
    //    //    return false;
    //    //}
    //    if ($('#authorized_amt').val() == "" || $('#authorized_amt').val() == null || $('#authorized_amt').val() == 0) {
    //        $('#Pauthorized_amt').show();
    //        $('#Pauthorized_amt').fadeOut(8000);
    //        $('#Pauthorized_amt').html('Please Enter Claim Amount');
    //        $('#authorized_amt').focus();
    //        $('#authorized_amt').val('');
    //        return false;
    //    }
    //    if ($('#mou_discount,#co_pay,#dis_others').val() != 0 && ($('#auth_amt').val() == 0 || $('#auth_amt').val() == '')) {
    //        $('#Pauth_amt').show();
    //        $('#Pauth_amt').fadeOut(8000);
    //        $('#Pauth_amt').html('Please Enter approved amount');
    //        $('#auth_amt').focus();
    //        $('#mou_discount,#co_pay,#dis_others').val(0).change();
    //        return false;
    //    }
    //}

    if ($('#hdn_is_discount').val() == 1 && $('#sel_authorized_person').val() != 0 && $('#sel_authorized_person').val() != '' && $('#sel_authorized_person').val() != null && (($('#hndbilling_no').val() == '' || $('#hndbilling_no').val() == null) || ($('#hndbilling_no').val() && $('#hdn_wo_otp').val()))) {
        send_otp(1);
    }
    else if (parseFloat($('#balance_amount').html()) > 0) {
        $('#due_popup').modal('toggle');
    }
    else {
        SubmitBill();
    }
})
});
function SubmitBill() {
    $('#btn_due_submit').prop('disabled', true);
    var bill = bill_insert('bill');
    $.when(bill)
.then(function (data) {
    receipt_insert(data);
    claim_billing_insert(data);

});
}
//Due Reason Bill Submit
$('#btn_due_submit').click(function () {
    SubmitBill();
})
//Receipt insert
function receipt_insert(data) {
    debugger;
    var data = JSON.parse(data);
    if (data.msg == "Success") {
        // alert('Saved Successfully');
        //$('#priceMatrixEditClass').modal('toggle');
        //var billing_no=data.Table.billing_no;
        debugger;
        console.log(data);
        var data1 = data.data;
        console.log(data1.Table[0].billing_no);
        $('#hndbilling_no').val(data1.Table[0].billing_no);

        var invoiceArray = [];
        if ($('#tbl_payment tr').length > 0) {
            $("#tbl_payment tr").each(function () {

                var invoicelist = {};
                invoicelist.bank_name = $(this).find("td").eq(1).attr('data-id');
                invoicelist.payment_mode = $(this).find("td").eq(4).html();
                invoicelist.amount = $(this).find("td").eq(2).html(),
                invoicelist.reference_no = $(this).find("td").eq(3).html();
                invoicelist.user_collect_amount = ($(this).find("td").eq(5).html()=='')?0:$(this).find("td").eq(5).html();
                invoicelist.user_refund = ($(this).find("td").eq(6).html() == '') ? 0 : $(this).find("td").eq(6).html()
                invoicelist.created_by = $('#hiddenUser_id').val(),
                 invoicelist.receipt_code = "",
             invoicelist.receipt_type = 2,
             invoicelist.patient_id = $('#hdnpatientapp').val(),
             invoicelist.visit_report_id = $('#hdnvisit_report_id').val(),
             invoicelist.total_amount = $('#collect_payment').html(),
             invoicelist.hospital_id = $('#HospitalId').val(),
             invoicelist.branch_id = $('#pkg_branch_id').val();
                invoicelist.billing_no = $('#hndbilling_no').val();
                invoiceArray.push(invoicelist);


                //invoicelist.billing_no = billing_no;

            });
        }
        else {
            var invoicelist = {};
            invoicelist.receipt_type = 2,
            invoicelist.patient_id = $('#hdnpatientapp').val(),
            invoicelist.visit_report_id = $('#hdnvisit_report_id').val(),
            invoicelist.total_amount = $('#collect_payment').html(),
            invoicelist.hospital_id = $('#HospitalId').val(),
            invoicelist.branch_id = $('#pkg_branch_id').val();
            invoicelist.billing_no = $('#hndbilling_no').val();
            invoiceArray.push(invoicelist);
        }



        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/billing_invoice',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(invoiceArray),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);

                if (data.msg == "Success") {
                    $('#shade_slot_submit').hide();
                    if (parseFloat($('#refund_amount').html()) == 0) {
                        //toastr.success("Bill Generated Successfully!!!");
                    }
                    else {
                        //toastr.success("Kindly collect the refund amount " + parseFloat($('#refund_amount').html()));
                    }
                    var visit_type = $("input[name='optradio']:checked").val();
                    if (visit_type != 2) {
                        toastr.warning("<button type='button' id='confirmationRevertA4' class='btn btn-warning btn-xs mt20'>A4</button><button type='button' id='confirmationRevertA5' class='btn btn-warning btn-xs mt20'>A5</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Click the print option',
                         {
                             closeButton: true,
                             progressBar: true,
                             allowHtml: true,
                             //timeOut: 20000000,
                             timeOut: 0,
                             extendedTimeOut: 0,

                             onShown: function (toast) {
                                 $("#confirmationRevertA4").click(function () {
                                     var report = bill_report($('#hndbilling_no').val(), data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val(), 1)
                                     $.when(report)
                                   .then(function (data) {
                                       toastStatus = 1;
                                       InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                       window.location.href = '/BillingMaster/index';
                                   });
                                 })
                                 $("#confirmationRevertA5").click(function () {
                                     var report = bill_report($('#hndbilling_no').val(), $('#selected_opd_number').val(), data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val(), 2)
                                     $.when(report)
                                   .then(function (data) {
                                       toastStatus=1
                                       InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                       window.location.href = '/BillingMaster/index';
                                   });
                                 })
                                 $("#confirmationRevertNo").click(function () {
                                     toastStatus=1
                                     InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                     window.location.href = '/BillingMaster/index';
                                 })
                             },
                             //onHidden: function (toast) {
                             //    if (toastStatus == 0) {
                             //        InventoryCRMInsert($('#hndbilling_no').val())
                             //    }
                             //    window.location.href = '/BillingMaster/index';
                             //}
                         })
                    }
                    else {
                        toastr.warning("<button type='button' id='confirmationRevertA4' class='btn btn-warning btn-xs mt20'>Summary Bill</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Click the print option',
                        {
                            closeButton: true,
                            progressBar: true,
                            allowHtml: true,
                            //timeOut: 20000000,
                            timeOut: 0,
                            extendedTimeOut: 0,

                            onShown: function (toast) {

                                $("#confirmationRevertA4").click(function () {
                                    var report = ip_bill_report($('#hndbilling_no').val(), data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val(), '', '', 19)
                                    $.when(report)
                                  .then(function (data) {
                                      toastStatus=1
                                      InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                      window.location.href = '/BillingMaster/index';
                                  });
                                })
                                $("#confirmationRevertNo").click(function () {
                                    toastStatus=1
                                    InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                    window.location.href = '/BillingMaster/index';
                                })
                            },
                            onHidden: function (toast) {
                                if (toastStatus == 0) {
                                    InventoryCRMInsert($('#hndbilling_no').val(), $('#selected_opd_number').val())
                                }
                                window.location.href = '/BillingMaster/index';
                            }
                        })
                    }
                    //var report=ip_bill_report($('#hndbilling_no').val(), data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val())

                    //setTimeout(function () {
                    //    //window.location.href = '/BillingMaster/billing_view';
                    //}, 3000);



                }
            }
        })

    }
}
function InventoryCRMInsert(BillingNo,Opdnumber) {
    debugger;
    var load_data = {
        dml_indicator : "CRML",
        billing_no: BillingNo,
        Opd_number: Opdnumber

    }
    //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

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



        }
    });
}

//A5 Print
function ip_bill_report(bill_no, patientid, hospitalid, branch_id, visittype, event, id) {
    debugger;
    //var fromdate = ''; var todate = '';
    //if ($('#txtfrom_date').val() != null && $('#txtfrom_date').val() != "") {
    //    var fromdate = $('#txtfrom_date').val();
    //    var a = fromdate.split('/');
    //    fromdate = a[2] + '-' + a[1] + '-' + a[0];
    //}

    //if ($('#txtto_date').val() != null && $('#txtto_date').val() != "") {
    //    var todate = $('#txtto_date').val();
    //    var a = todate.split('/');
    //    todate = a[2] + '-' + a[1] + '-' + a[0];

    //}

    var load_data = {
        formid: id,
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        billno: bill_no

    }
    //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

    return $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            debugger;
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

            //iframe = document.createElement('iframe'); //load content in an iframe to print later
            //document.body.appendChild(iframe);

            //iframe.style.display = 'none';
            //iframe.src = link;
            //iframe.onload = function () {
            //    setTimeout(function () {
            //        iframe.focus();
            //        iframe.contentWindow.print();

            //    }, 1);
            //};



        }
    });

}


//A4 print
function bill_report(bill_no, patientid, hospitalid, branch_id, papertype, event) {
    debugger;


    var load_data = {
        formid: ((papertype == 1 || papertype == '1') ? "105" : "65"),
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        billno: bill_no

    }
    //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');
            //iframe = document.createElement('iframe'); //load content in an iframe to print later
            //document.body.appendChild(iframe);

            //iframe.style.display = 'none';
            //iframe.src = link;
            //iframe.onload = function () {
            //    setTimeout(function () {
            //        iframe.focus();
            //        iframe.contentWindow.print();
            //    }, 1);
            //};
        }
    });
}

//Billing Creation
function bill_insert(mode) {
    debugger;
    var dml_indicator = '';
    if (mode == 'copy') {
        dml_indicator = 'BC'
    }
    var rowCount = $('#service_tbl tbody tr').length

    var ServiceArray = [];
    var status = "";
    if ($('#total_net_amount').html() == $('#collect_payment').html()) {
        status = 1;
    }
    else if ($('#collect_payment').html() == '') {
        status = 3;
    }
    else {
        status = 2;
    }
    var visit_type = $("input[name='optradio']:checked").val();
    debugger;
    var due_amount = 0;
    var collect_payment = $('#collect_payment').html();
    var total_net_amount = $('#total_net_amount').html();
    if (collect_payment == '' || collect_payment == null) {
        collect_payment = 0;
    }
    if (total_net_amount == '' || total_net_amount == null) {
        total_net_amount = 0;
    }
    if (parseFloat($('#refund_amount').html()) == 0) {
        due_amount = parseFloat($('#balance_amount').html());
        //if (parseFloat($('#collect_payment').html()) > parseFloat($('#total_net_amount').html())) {

        //    due_amount = parseFloat(collect_payment) - parseFloat(total_net_amount);
        //}
        //else {
        //    due_amount = parseFloat(total_net_amount) - parseFloat(collect_payment);
        //}
    }
    else {
        due_amount = 0;
    }
    if (due_amount == "NaN" || due_amount == NaN) {
        due_amount = 0;
    }



    due_amount = due_amount.toFixed(2);
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var curDate = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
    $('#shade_slot_submit').show();
    $('#btn_submit').attr('disabled', true);
    $("#service_tbl tbody tr").each(function () {
        debugger;
        var fee = 0;

        var bill = ($('#hndbilling_copy_no').val() == '') ? ((billing_no == "") ? 0 : billing_no) : $('#hndbilling_copy_no').val();

        var list = {};
        if ($(this).find("td").eq(9).html() != null && $(this).find("td").eq(9).html() != '') {
            if ($(this).find("td").eq(9).html().split('/')[1] != '' && $(this).find("td").eq(9).html().split('/')[1] != null) {
                fee = $(this).find("td").eq(9).html().split('/')[1]
            }
        }

        var discount = $(this).find("td").eq(4).html();
        var discount_type = '', discount_val = '';
        discount = discount.split(' ');
        discount_val = discount[0]
        discount_type = discount[1];
        if (discount_val == '') {
            discount_val = 0;
        }
        if (discount_type == '₹') {
            discount_type = 1;
        }
        else {
            discount_type = 2;
        }
        var discount_amount = ($(this).find("td").eq(5).html() == '' ? 0 : $(this).find("td").eq(5).html())
        var net_amount = ($(this).find("td").eq(6).html() == '' ? 0 : $(this).find("td").eq(7).html())
        debugger;
        list.billing_code = "",
            list.patient_id = $('#hdnpatientapp').val(),
            list.opd_number = $('#selected_opd_number').val(),
        list.visit_report_id = $('#hdnvisit_report_id').val(),
        list.hospital_id = $('#HospitalId').val(),
        list.visit_type = visit_type
        list.created_by = $('#hiddenUser_id').val(),
        list.due_amount = due_amount,
        list.total_amount = $('#net_amount').html(),
        list.total_net_amount = $('#total_net_amount').html(),
        list.received_amount = $('#collect_payment').html(),
        list.branch_id = $('#pkg_branch_id').val(),
        list.h_discount = $('#txt_tot_discount_amt').val(),
        list.discount_reason = $('#txt_dis_reason').val(),
        list.due_reason = $('#txt_due_reason').val(),
        list.h_discount_type = $('#authorized_discount').val(),
        list.h_total_discount_amount = $('#total_discount').html(),
        list.discount_authorization_by = $('#sel_authorized_person').val(),
        list.patient_type_id = '1',//1. self 2. insurance
        list.status = status,
        list.billing_channel = 1,
        list.created_on = curDate,
        list.discharge_date = curDate,
        //list.request_id = $('#hdnrequest_id').val(),
        list.advance_amount = $('#advance_amount').html(),

        list.master_service_id = $(this).find("td").eq(12).html(),
        list.amount = $(this).find("td").eq(3).html(),
        list.service_quantity = $(this).find("td").eq(1).html(),
        list.discount = discount_val
        list.discount_type = discount_type,
        list.created_by = $('#hiddenUser_id').val(),
        list.package_id = $(this).find("td").eq(13).html(),
        list.billing_type = 2, //1. work order initiated\n2. appointment initiated'
        list.discharge_type = 1,
        list.discharge_date = curDate,
        list.ward_id = $('#Hwardid').val(), //$('#hndward_id').val(),
        list.billing_class = $('#Hbilling_class').val(), // $('#hndbilling_class').val(),
        // doctor_id = $(this).find("td").eq(6).html().
        list.doctor_id = $(this).find("td").eq(11).html();
        list.billing_no = bill;
        list.billing_remarks = $('#txt_billing_remarks').val()
        list.OTP_Status = $('#hdn_wo_otp').val();
        //if ($(this).find("td").eq(7).html() != '' && $(this).find("td").eq(7).html() != null) {
        //    //var date = $(this).find("td").eq(7).html().split('/');
        //    //var date_split=date[2]+'-'+date[1]+'-'+date[0]
        //    list.request_date = $(this).find("td").eq(7).html();
        //}
        //else {
        //    list.request_date = curDate;
        //}
        var base_amount_type = $(this).find("td").eq(17).html();
        var date = $(this).find("td").eq(8).html();
        var start_date = null, start_time = null, end_date = null, end_time = null
        if (base_amount_type == 4) {
            start_date = date.split('-')[0].split(" ")[0];
            start_time = date.split('-')[0].split(" ")[1] + ' ' + date.split('-')[0].split(" ")[2];
            end_date = date.split('-')[1].split(" ")[0];
            end_time = date.split('-')[1].split(" ")[1] + ' ' + date.split('-')[1].split(" ")[2];
        }
        else {
            start_date = date.split('-')[0].split(" ")[0];
            start_time = date.split('-')[0].split(" ")[1] + ' ' + date.split('-')[0].split(" ")[2];

        }
        list.request_date = start_date,
        list.request_time = start_time,
        list.end_date = end_date,
        list.end_time = end_time,
        list.service_quantity_amount = $(this).find("td").eq(2).text().split('(')[0],
        list.price_matrix_id = $(this).find("td").eq(14).html(),
        list.request_number = $(this).find("td").eq(15).html(),
        list.request_details_id = $(this).find("td").eq(16).html(),
        list.service_discount_amount = discount_amount,
        list.service_net_amount = net_amount,
        list.billing_refund = $('#refund_amount').html(),
        list.remarks = $(this).find("td").eq(10).html(),
        //list.claim_no = $('#claim_no').val(),
        //list.authorized_amount = $('#authorized_amt').val(),
        // list.approved_amount = (($('#auth_amt').val() == '') ? 0 : $('#auth_amt').val()),
        //list.mou_discount = (($('#mou_discount').val()=='')?0:$('#mou_discount').val()),
        //list.co_pay = ($('#co_pay').val() == '') ? 0 : $('#co_pay').val(),
        //list.other_discount = ($('#dis_others').val() == '') ? 0 : $('#dis_others').val(),
        list.authorized_amount = (($('#final_claim_amount').html() == '') ? 0 : $('#final_claim_amount').html()),
        // list.approved_amount = (($('#collect_claim_amount').html() == '') ? 0 : $('#collect_claim_amount').html()),
        list.billing_details_id = $(this).find("td").eq(20).html()
        list.service_tax_percentage = $(this).find("td").eq(6).html().split('%')[0]
        list.service_tax_amount = $(this).find("td").eq(21).html()
        list.tax_amount = $('#total_tax_amount').html()
        list.doctor_fee = (fee == '-' || fee == '' || fee == null) ? 0 : fee
        list.dml_indicator = dml_indicator
        list.charge_percentage = (!($(this).find("td").eq(22).html()) ? 0 : $(this).find("td").eq(22).html())
        list.CRMService = (!($(this).find("td").eq(27).html()) ? 0 : $(this).find("td").eq(27).html())
        list.PharmacyBillNo = (!($(this).find("td").eq(28).html()) ? 0 : $(this).find("td").eq(28).html()),
        list.is_insurance = $('#EntityType').val()||0,
        list.is_entity = $('#Entity').val() || 0,
        list.insurance_id = $('#HdnEntityid').val() || 0,
        list.is_MultiPay = $('#CMultiPay').val() || 0,
        list.Corporate_Insuranceid = $('#MPCIName').val() || 0,
         list.estimation_details_id = (!($(this).find("td").eq(29).html()) ? 0 : $(this).find("td").eq(29).html()),
         list.estimation_no = (!($(this).find("td").eq(30).html()) ? 0 : $(this).find("td").eq(30).html()),
         list.estimateid =$('#HEstimateId').val()||0
        

       

        var count = 0;
        for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
            var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
            id = id.split('_');
            id = id[1]



            var is_final = $('#td_final_' + id).attr('data-id');
            
            if (is_final == 1) {
                count++;
            }
           
        }
        list.is_final_amount = count
        list.audiologist_user_id = $('#SelAudiologist').val()
        ServiceArray.push(list);
    });

    return $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Service',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ServiceArray),
        success: function (data) {
            //var data1 = JSON.parse(data);
            //var data1 = data1.data;
            //console.log(data1.Table[0].billing_no);
            var status = 1;
            return status;

            //return data;
        }
    });

}

//Amount Adding
$('#btn_payment').click(function () {
    debugger;
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    var payment_mode = $('#sel_payment_mode').val();
    var received_amt = $('#txt_received_amt').val();
    var transaction = $('#txt_transaction').val();
    var net_amount = $('#net_amount').html();
    var total_net_amount = $('#total_net_amount').html();
    if ($('#sel_payment_mode').val() == 0) {
        $('#Psel_payment_mode').show();
        $('#Psel_payment_mode').fadeOut(8000);
        $('#Psel_payment_mode').html('Please payment mode');
        $('#sel_payment_mode').focus();
        $('#sel_payment_mode').val(0);
        return false;
    }
    if ($('#sel_payment_mode option:selected').text().toUpperCase().includes('CARD')) {
        if ($('#txt_bank_name').val() == '' || $('#txt_bank_name').val() == 0) {
            $('#Ptxt_bank_name').show();
            $('#Ptxt_bank_name').fadeOut(8000);
            $('#Ptxt_bank_name').html('Please Enter Bank Name');
            $('#txt_bank_name').focus();
            $('#txt_bank_name').val();
            return false;
        }
    }

    if ($('#txt_received_amt').val() == "" || $('#txt_received_amt').val() == 0) {
        $('#Ptxt_received_amt').show();
        $('#Ptxt_received_amt').fadeOut(8000);
        $('#Ptxt_received_amt').html('Please enter amount');
        $('#txt_received_amt').focus();
        $('#txt_received_amt').val('');
        return false;
    }

    //if (payment_mode == 2306) {
    //    debugger;
    //    if ($('#txt_received_amt').val()>200000) {
    //        alert('Amount Exceed');
    //        return false;
    //    }
    //    else {
    //        var received_amt = $('#txt_received_amt').val();
    //    }

    //}
    //else {
    //    var received_amt = $('#txt_received_amt').val();
    //}

    if ($('#txt_user_collect').val() != '' && $('#txt_user_collect').val() != 0 && parseFloat($('#txt_user_collect').val()) < parseFloat($('#txt_received_amt').val()))
    {
        $('#txt_user_collect').change();
        return false;
    }
    if (parseFloat($('#txt_user_collect').val()) == parseFloat($('#txt_received_amt').val())) {
        $('#txt_user_refund').val(0);
    }
   
    var paymentmodeexists = 0;
    if ($('#tbl_payment tr').length > 0) {
        $("#tbl_payment tr").each(function () {
            if ($('#sel_payment_mode').val() == $(this).find("td").eq(4).html()) {
                paymentmodeexists++;
            }
        })
    }

    if (paymentmodeexists > 0) {
        toastr.warning('This payment mode already exists');    
        return false;
    }
    
    
    debugger;

    var collectedamount = 0;
    var balanceamount = 0;
    var txt_received_amt = $('#txt_received_amt').val();

    var balance_amount = parseFloat($('#balance_amount').html());

    var collect_payment1 = $('#collect_payment').html();
    var total_net_amount = $('#total_net_amount').html();

    if (parseFloat(txt_received_amt) > parseFloat(balance_amount)) {
        toastr.warning('Balance Amount and received Amount is over lap');
        $('#txt_received_amt').val('');
        return false;
    }
    else {

        collectedamount = parseFloat(collect_payment1) + parseFloat(txt_received_amt);
        balanceamount = parseFloat(total_net_amount) - parseFloat(collectedamount);
        balanceamount = Math.round(balanceamount.toFixed(2));
        $('#collect_payment').html(Math.round(collectedamount).toFixed(2));
        $('#balance_amount').html(Math.round(parseFloat(balanceamount).toFixed(2)));
        $('#txt_received_amt').val(balanceamount);
        $('#sms_payment').val(balanceamount);
        //$('#auth_amt').change();
        claim_calculation();
    }

    var collect_payment = 0;
    if ($('#tbl_payment tr').length > 0) {
        $("#tbl_payment tr").each(function () {
            collect_payment = parseFloat(collect_payment) + parseFloat($(this).find("td").eq(1).html());
        });
    }
    collect_payment = parseFloat(collect_payment) + parseFloat(received_amt);
    if (parseFloat(collect_payment) > parseFloat(total_net_amount)) {
        toastr.warning('Please check the service total net amount ' + net_amount);
        return false;
    }


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

        ikey_payment = 'row' + tot_row;
    }

    // $('#collect_payment').html(collect_payment);

    var tr = '';
    tr = tr + '<tr id="t_' + ikey_payment + '"><td>' + $('#sel_payment_mode option:selected').text() + '</td><td data-id=' + $('#txt_bank_name').val() + '>' + $('#txt_bank_name option:selected').text() + '</td><td>' + received_amt + '</td><td>' + transaction + '</td><td class="hide">' + $('#sel_payment_mode').val() + '</td><td>' + $('#txt_user_collect').val() + '</td><td>' + $('#txt_user_refund').val() + '</td><td><button class="btn deleteicon-btn btn-sm" title="Delete Payment" onclick=\'DeletePayment(\"' + ikey_payment + '\",\"' + received_amt + '\")\'><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>';

    $('#tbl_payment').append(tr);
    $('#sel_payment_mode').val(0);
    $('#txt_user_collect,#txt_user_refund').val('');
    $('#txt_received_amt').val($('#balance_amount').html())
    $('#txt_transaction').val('');
    $('#txt_bank_name').val('');
})
});

function DeletePayment(row_id, received_amount) {
    $('#t_' + row_id).remove();
    var collectedamount = 0;
    var balanceamount = 0;
    var txt_received_amt = received_amount;

    var balance_amount = parseFloat($('#balance_amount').html());

    var collect_payment1 = $('#collect_payment').html();
    var total_net_amount = $('#total_net_amount').html();

    collectedamount = parseFloat(collect_payment1) - parseFloat(txt_received_amt);
    balanceamount = parseFloat(total_net_amount) - parseFloat(collectedamount);
    balanceamount = Math.round(balanceamount.toFixed(2));
    $('#collect_payment').html(Math.round(collectedamount).toFixed(2));
    $('#balance_amount').html(Math.round(parseFloat(balanceamount).toFixed(2)));
    $('#txt_received_amt').val(balanceamount);
    $('#sms_payment').val(balanceamount);
    claim_calculation();

}

//$(".txt_quantity,.txt_discount,.sel_discount_type").keyup(function () {
//    var totval = '';
//    var quantity = $('.txt_quantity').val();
//    var unitRate = $('.txt_unitRate').html()
//    var txt_discount = $('.txt_discount').val();
//    var sel_discount_type = $('.sel_discount_type').val();
//    totval = quantity * unitRate;
//    if (sel_discount_type == 1) {
//        totval = totval - txt_discount
//    }
//    else if (sel_discount_type == 2) {
//        totval = totval - ((totval / 100) * txt_discount)
//    }
//    else {
//        totval = totval;
//    }
//    $('.txt_totalamt').html(totval);
//});

//$("#service_tbl").on('click', '.txt_service_name', function () {
//    // get the current row
//    var currentRow = $(this).closest("tr");
//    console.log(currentRow);
//    var col1 = currentRow.find("td:eq(0)").text(); // get current row 1st TD value
//    var col2 = currentRow.find("td:eq(1)").text(); // get current row 2nd TD
//    var col3 = currentRow.find("td:eq(3)").text(); // get current row 3rd TD
//    var data = col1 + "\n" + col2 + "\n" + col3;
//    alert(data);
//});
//function patient_details(patient_id) {
//    var DoctorData = {
//        patient_id: patient_id,
//        dml_indicator: 'PD'
//    }

//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/IP_OP_Billings',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(DoctorData),
//        success: function (data) {
//            var data2 = JSON.parse(data);
//            if (jQuery.isEmptyObject((data2.data))) {
//            }
//            else {
//                debugger;
//                $('.pat-stripe-bgop').show();
//                if (data2.msg == "Success") {
//                    var data1 = data2.data;
//                    console.log('data1---------->' + data1.Table);
//                    if (data1.Table.length > 0) {
//                        for (var i = 0; i < data1.Table.length; i++) {
//                            $('#patient_name').html(data1.Table[i].patient_name);
//                            $('#patient_id').html(data1.Table[i].patient_id);
//                            $('#phone_number').html(data1.Table[i].phone_number_1);

//                            var hieghtdb = parseInt(data1.Table[i].patient_height * 12) + parseInt(data1.Table[i].patient_height_metric);
//                            var hieghtout = Math.round(hieghtdb * 2.54);
//                            $('#patient_height').html(hieghtout);
//                            $('#patient_weight').html(data1.Table[0].patient_weight);
//                            $('#patient_address').html('<i class="fa fa-map-marker" aria-hidden="true"></i> &nbsp;' + data1.Table[i].address_line_1 + ' ' + data1.Table[i].address_line_2 + ' ' + data1.Table[i].town_village + ' ' + data1.Table[i].city_name + ' ' + data1.Table[i].country_name + ' - ' + data1.Table[i].pincode)
//                            if (data1.Table[i].photo != "" && data1.Table[i].photo != null) {
//                                $('#patient_photo').html("<img src=" + data1.Table[i].photo + " />");
//                            }
//                            else {
//                                $('#patient_photo').html("<img src='/Content/img/profile_icon.png'/>");
//                            }
//                            var VDOB = '', Vage = '', vage_registered_date = '', gender = '';
//                            VDOB = (data1.Table[i].DOB);
//                            Vage = (data1.Table[i].patient_age);
//                            vage_registered_date = (data1.Table[i].age_registered_date);
//                            if (VDOB == "" || VDOB == null) {
//                                if (vage_registered_date == "" || vage_registered_date == null) {
//                                    if (Vage == "" || Vage == null) {
//                                        age = '-';
//                                    }
//                                    else {
//                                        age = Vage + ' Yrs';
//                                    }
//                                }
//                                else {
//                                    age_reg_date = new Date(vage_registered_date);
//                                    var today = new Date();
//                                    var ageval = '';
//                                    ageval = Math.floor((today - age_reg_date) / (365.25 * 24 * 60 * 60 * 1000));
//                                    age = ageval + ' Yrs';
//                                }

//                            }
//                            else {
//                                dob = new Date(VDOB);
//                                var today = new Date();
//                                var ageval = '';
//                                ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
//                                age = ageval + ' Yrs';
//                            }
//                            if (data1.Table[i].gender == 1) {
//                                gender = 'M';
//                            }
//                            else if (data1.Table[i].gender == 2) {
//                                gender = 'F';
//                            }
//                            $('#patient_age').html(age + ' / ' + gender);
//                        }
//                        $('#doctor_name').html(data1.Table[0].doctor_name);
//                        $('#noof_visit').html(data1.Table[0].visit_count);
//                        $('#visit_date').html(data1.Table[0].created_on);
//                        $('#visit_no').html(data1.Table[0].visit_report_id);
//                    }
//                }
//                else {
//                    console.log(data);
//                }
//            }
//        }
//    });
//}

//Loading Payment Type
function LoadPayment_Type(val) {
    debugger;
    var val_branch_id = '';
    if (val == '' || val == undefined) {
        val_branch_id = $('#pkg_branch_id').val()
    }
    else {
        val_branch_id = val
    }

    var receipt_data = {
        Dml_Indicator: 'PL',
       // branch_id: val_branch_id //one master concept
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(receipt_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data1 = data.data.Table;
                var data2 = data.data.Table1;
                console.log(data1);
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    $('#sel_payment_mode').empty();
                    $('#txt_bank_name').empty();
                    var Service = '', service1 = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Service = Service + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#sel_payment_mode').append(default_opt + Service);
                    $.each(data2, function (i, emp) {
                        service1 = service1 + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#txt_bank_name').append(default_opt + service1);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}

//Receiving Payment Change Function Check whether the payment less than or equals the total Bill
$('#txt_received_amt').change(function () {
    debugger;

    var collectedamount = 0;
    var balanceamount = 0;
    var txt_received_amt = $('#txt_received_amt').val();

    var balance_amount = $('#balance_amount').html();

    var collect_payment = $('#collect_payment').html();
    var total_net_amount = $('#total_net_amount').html();

    if (parseFloat(txt_received_amt) > parseFloat(balance_amount)) {
        toastr.warning('The Received Amount is greater than the Balance Amount');
        $('#txt_received_amt').val('');
        $('#txt_received_amt').focus();
        return false;
    }

})

//$('.txt_service_name ').change(function () {
//    var id = $('.txt_service_name ').val();

//    loadservicedetails(id)

//})
//Service Name onchange for loading service code
function loadservicedetails(id) {
    debugger;
    $('#Hmaster_service_id').val(id);

    indicator_id = 'SLCI'
    var wardid = 0, Hbilling_class = 0
    var service_data = {
        Dml_Indicator: indicator_id,
        master_service_id: id,
        wardid: wardid,
        billing_class: Hbilling_class
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        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 {
                    if (data1.length > 0) {
                        //$('#Hbase_amount_type').val(data1[0].base_amount_type);
                        //if (data1[0].base_amount_type == 4) {
                        //    $('#div_req_end').show();
                        //    $('#req_quantity').prop('disabled', true);

                        //}
                        //else {
                        //    $('#div_req_end').hide();
                        //    $('#req_quantity').prop('disabled', false);
                        //}
                        //$('#req_service_code').val(data1[0].service_code);
                        //$('#service_amount').val(data1[0].base_amount_value);
                        //$('#Hworkorder').val(data1[0].work_order);
                        //$('#Hwork_order_type').val(data1[0].work_order_type);
                        //$('#H_is_package').val(data1[0].is_package);
                        //$('#Hpackage_id').val(data1[0].package_id);

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

function service_detele(id) {
    debugger;
    var visit_type = $("input[name='optradio']:checked").val()
    var id = 'tr_' + id
    if ($('#hdnvisit_report_id').val() != '' && visit_type == 2) {

        var master_service_id = $('#' + id).eq(11).html();
        var request_id = $('#' + id).eq(14).html();

        var DoctorData = {
            request_id: request_id,
            dml_indicator: 'DC',
            master_service_id: master_service_id,
            visit_type: visit_type
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/IP_OP_Billing',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                debugger
                console.log(data);
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data;
                    if (data1[0].StringMsg == 'success') {
                        $('#' + id).remove();
                    }
                    else {
                        toastr.warning('Service already used.You cannot delete')
                    }
                }
                else {
                    console.log(data1)

                }
            }
        })
    }
    else {
        $('#' + id).remove();
    }
    var Net_Amount = 0, Total_Net_Amount = 0, total_discount = 0;
    $("#service_tbl tbody tr").each(function () {
        debugger;
        var discount_type = $(this).find("td").eq(4).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        cur_val = $(this).find("td").eq(3).html();
        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);
        Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(3).html());
        total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
    });
    $('#net_amount').html(parseFloat(Net_Amount).toFixed(2));
    $('#total_net_amount').html(Math.round(Total_Net_Amount).toFixed(2));
    $('#total_discount').html(parseFloat(total_discount).toFixed(2));

}


//DatePicker calculation for Hourly Service
$('.datetimepicker2,.datetimepicker1').on('change dp.change', function (e) {
    debugger;
    var start_date = $('.txt_date').val();
    var end_date = $('.txt_end_date').val();
    if (start_date != '' && end_date != '') {
        var quantity = 0;
        var start_date = new Date(moment($('.txt_date').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        var end_date = new Date(moment($('.txt_end_date').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        console.log(start_date);
        console.log(end_date);
        var diff = (end_date - start_date) / 1000 / 60 / 60;
        console.log(diff);
        diff1 = diff.toString();
        var a = diff1.split('.')[0];
        if (diff != a) {
            console.log(a);
            var chk = a + '.5';
            if (parseFloat(diff) <= parseFloat(chk)) {
                quantity = parseFloat(chk);
            }
            else {
                quantity = Math.ceil(diff);
            }
        }
        else {
            quantity = diff;
        }
        console.log(quantity);
        $('.txt_quantity').val(quantity);
        $('.txt_quantity').prop("disabled", true);
        quantity_check();
    }
})

//Send Payment Via SMS-code started
$('#btnsmspayment').click(function () {
    if ($('#txtmobile_no').val() == '') {
        $('#Ptxtmobile_no').show();
        $('#Ptxtmobile_no').fadeOut(8000);
        $('#Ptxtmobile_no').html('Please enter mobile number');
        $('#txtmobile_no').focus();
        return false;
    }
    if ($('#sms_amount').val() == '' || $('#sms_amount').val() == 0) {
        $('#Psms_amount').show();
        $('#Psms_amount').fadeOut(8000);
        $('#Psms_amount').html('Please enter mobile number');
        $('#sms_amount').focus();
        return false;
    }
    else {
        debugger;
        if ($('#hdn_is_discount').val() == 1 && $('#sel_authorized_person').val() != 0 && $('#sel_authorized_person').val() != '' && ($('#hndbilling_no').val() == '' || $('#hndbilling_no').val() == null)) {
            send_otp(2);
        }
        else {
            sms_function();
        }
    }


})

//call the bill creation method and link will be sent
function sms_function() {
    var bill = bill_insert('sms');
    debugger;
    $.when(bill)
         .then(function (data) {
             debugger
             var data1 = JSON.parse(data);
             if (data1.msg == "Success") {
                 debugger;
                 console.log(data1);
                 var data1 = data1.data;
                 console.log(data1.Table[0].billing_no);
                 $('#hndbilling_no').val(data1.Table[0].billing_no);
                 var sms = sms_payment(data1.Table[0].billing_no);
                 $.when(sms)
                 .then(function (data1) {
                     claim_billing_insert(data);
                     if ($('#tbl_payment tr').length > 0) {
                         receipt_insert(data);
                     }
                     else {
                         toastr.warning("<button type='button' id='confirmationRevertA4' class='btn btn-warning btn-xs mt20'>A4</button><button type='button' id='confirmationRevertA5' class='btn btn-warning btn-xs mt20'>A5</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Click the print option',
                      {
                          closeButton: true,
                          progressBar: true,
                          allowHtml: true,
                          timeOut: 0,
                          extendedTimeOut: 0,

                          onShown: function (toast) {
                              $("#confirmationRevertA4").click(function () {
                                  var report = bill_report($('#hndbilling_no').val(), data1.Table[0].patientid, data1.Table[0].hospitalid, $('#pkg_branch_id').val(), 1)
                                  $.when(report)
                                .then(function (data) {
                                    window.location.href = '/BillingMaster/index';
                                });
                              })
                              $("#confirmationRevertA5").click(function () {
                                  var report = ip_bill_report($('#hndbilling_no').val(), data1.Table[0].patientid, data1.Table[0].hospitalid, $('#pkg_branch_id').val(), '', '', 19)
                                  $.when(report)
                                .then(function (data) {
                                    window.location.href = '/BillingMaster/index';
                                });
                              })
                              $("#confirmationRevertNo").click(function () {
                                  window.location.href = '/BillingMaster/index';
                              })
                          },
                          onHidden: function (toast) {
                              window.location.href = '/BillingMaster/index';
                          }
                      })
                     }

                 });

             }
         });
}
//payment link sent 
function sms_payment(bill_no) {
    debugger;
    console.log(bill_no);
    var invoice_no_temp = "";
    var Amount_temp = "";
    invoice_no_temp = invoice_no_temp + ',' + bill_no;
    Amount_temp = Amount_temp + ',' + $('#sms_amount').val();
    var smspayment = {
        email_id: $('#txtemail').val(),
        phone_number: $('#txtmobile_no').val(),
        created_by: $('#hiddenUser_id').val(),
        valid_for: '2',
        valid_type: 'days',
        valid_date: '',
        currency: 'INR',
        amount: $('#sms_amount').val(),
        due_date: '',
        invoice_no: '1',
        Dml_Indicator: 'I',
        patient_id: $('#hdnpatientapp').val(),
        customer_name: $('#PatName').val(),//$('.pat-stripe-user-name').html(),
        invoice_no_temp: invoice_no_temp,
        Amount_temp: Amount_temp,
        //doctor_id: $('#pop_doctor_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                debugger;
                var data = JSON.parse(data);
                var data = data.data;
                if (data.length > 0) {
                    var sms_invoice_no = data[0].sms_invoice_no;
                    var email_id = data[0].email_id;
                    var phone_number = data[0].phone_number;
                    var amount = data[0].amount;
                    var invoice_no = "";
                    var Amount = "";
                    var invoice_no_temp = "";
                    var Amount_temp = "";
                    var smspayment = {
                        email_id: $('#txtemail').val(),
                        phone_number: $('#txtmobile_no').val(),
                        created_by: $('#hiddenUser_id').val(),
                        valid_for: '2',
                        valid_type: 'days',
                        valid_date: '',
                        currency: 'INR',
                        amount: $('#sms_amount').val(),
                        due_date: '',
                        sms_invoice_no: sms_invoice_no,
                        Dml_Indicator: 'sms',
                        patient_id: $('#hdnpatientapp').val(),
                        customer_name: $('#PatName').val() //$('.pat-stripe-user-name').html()

                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/sms_invoice_payment',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(smspayment),
                        success: function (data) {
                            if (jQuery.isEmptyObject((data))) {

                            }
                            else {
                                toastr.success('Payment link sent');
                                //window.location.href = '/BillingMaster/billing_view';

                            }
                        }
                    });
                }
            }
        }
    })

}

//collect payment via sms button click function
$('#pay_via_sms').click(function () {
    //$('#divpay').hide();
    $('#btn_submit').hide();
    $('#divsmspay').show();
    $('#sms_amount').val($('#balance_amount').html());
})

//collect payment via payment modes button click function
$('#pay_via_modes').click(function () {
    $('#divpay').show();
    $('#btn_submit').show();
    $('#divsmspay').hide();
})

//sms_payment_amount change function
$('#sms_amount').change(function () {
    var sms_amount = $('#sms_amount').val();
    var balance_amount = $('#balance_amount').html();
    if (parseFloat(sms_amount) > parseFloat(balance_amount)) {
        toastr.warning('Amount exceeds balance amount.Kindly enter again');
        $('#sms_amount').val('');
    }
})

//Discount Amount Check
$('.txt_discount,.sel_discount_type').change(function () {
    debugger;
    var discount = $('.txt_discount').val();
    var tot_amt = $('.txt_totalamt').html();
    var dis_type = $('.sel_discount_type').val();
    if (dis_type == 1) {
        if (parseFloat(discount) > parseFloat(tot_amt)) {
            $('#Ptxt_discount').show();
            $('#Ptxt_discount').fadeOut(5000);
            $('#Ptxt_discount').html('Discount amount should not greater than net amount');
            $('#txt_discount').focus();
            $('.txt_discount').val(0);
            $('.sel_discount_type').val(1);
            return false;
        }
    }
    else {
        if (parseFloat(discount) > 100) {
            $('#Ptxt_discount').show();
            $('#Ptxt_discount').fadeOut(5000);
            $('#Ptxt_discount').html('Discount Percentage should not greater than 100');
            $('#txt_discount').focus();
            $('.txt_discount').val(0);
            $('.sel_discount_type').val(1);
            return false;
        }
        else {
            discount = parseFloat(tot_amt) * (parseFloat(discount) / 100);
            if (parseFloat(discount) > parseFloat(tot_amt)) {
                $('#Ptxt_discount').show();
                $('#Ptxt_discount').fadeOut(5000);
                $('#Ptxt_discount').html('Discount amount should not greater than net amount');
                $('#txt_discount').focus();
                $('.txt_discount').val(0);
                $('.sel_discount_type').val(1);
                return false;
            }
        }
    }
})

//Amount Calculation Starts

//Service delete calculation
function amount_calculation(tbl_id,request_id,master_service_id,visit_type) {
    debugger;
    var auto_dis=0, Net_Amount = 0, Total_Net_Amount = 0,Total_Net_Amount1=0 ,total_discount = 0, balanceamount = 0, collectedamount = 0, net = 0.0, tax_amount = 0.0;;
    var dis_type = $('#authorized_discount').val();
    var discount_amt = ($('#txt_tot_discount_amt').val() == '' ? 0 : $('#txt_tot_discount_amt').val());
 
    $("#service_tbl tbody tr").each(function () {
        var id1 = $(this).closest("tr").prop("id");
        if (tbl_id == id1) {
            return true;
        }
        var discount_type = $(this).find("td").eq(4).html();
        var charge_percentage = $(this).find("td").eq(22).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        cur_val = $(this).find("td").eq(3).html();
        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        if (charge_percentage == 0) {
            Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);

            Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(3).html());

            //total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
            total_discount = total_discount + parseFloat($(this).find("td").eq(5).html())
            auto_dis = total_discount
            net = net + parseFloat($(this).find("td").eq(7).html())
            tax_amount = tax_amount + parseFloat($(this).find("td").eq(21).html());
            Total_Net_Amount1 = parseFloat(Total_Net_Amount1) + parseFloat(cur_val)+ parseFloat($(this).find("td").eq(21).html())
        }


    });
    //$('#total_tax_amount').html(tax_amount);
    //$('#net_amount').html(Net_Amount);
    //$('#total_net_amount').html(parseFloat(Total_Net_Amount)-parseFloat(discount_amt));
    //$('#total_discount').html(parseFloat(total_discount)+parseFloat(discount_amt));
    //balanceamount = parseFloat(Total_Net_Amount) - parseFloat(collectedamount) - parseFloat(discount_amt);
    //balanceamount = Math.round(balanceamount).toFixed(2);
    //$('#balance_amount').html(balanceamount);
    
   
    var advance_amount = 0;
    if ($('#advance_amount').html() == '' || $('#advance_amount').html() == null) {
        advance_amount = 0;
    }
    else {
        advance_amount = $('#advance_amount').html()
    }
    //Total_Net_Amount = parseFloat(Total_Net_Amount) - parseFloat(advance_amount);
    //$('#net_amount').html(Net_Amount.toFixed(2));
    //$('#total_net_amount').html(Total_Net_Amount.toFixed(2));
    debugger
   
  
    //var auth_amt = ($('#auth_amt').val() == '' ? 0 : $('#auth_amt').val());
    //var mou_discount = ($('#mou_discount').val() == '' ? 0 : $('#mou_discount').val());
    //var co_pay = ($('#co_pay').val() == '' ? 0 : $('#co_pay').val());
    //var dis_others = ($('#dis_others').val() == '' ? 0 : $('#dis_others').val());
    var auth_amt = 0, mou_discount = 0, co_pay = 0, dis_others = 0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]



        var is_final = $('#td_final_' + id).attr('data-id');
        if (is_final == 1) {
            auth_amt = auth_amt + parseFloat($('#td_approved_' + id).html());
            mou_discount = mou_discount + parseFloat($('#td_mou_' + id).html());
            co_pay = co_pay + parseFloat($('#td_co_' + id).html());
            dis_others = dis_others + parseFloat($('#td_dis_' + id).html());
        }
    }
    var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
   
    if (discount_amt != 0) {
        if (dis_type == 2) {
            discount_amt = parseFloat(Total_Net_Amount1) * (parseFloat(discount_amt) / 100);
        }
    }
    total_discount = parseFloat(total_discount) + parseFloat(discount_amt);
    Total_Net_Amount = parseFloat(Total_Net_Amount1) - parseFloat(discount_amt);
    if (parseFloat(approved_amt) > parseFloat(Total_Net_Amount)) {
        toastr.warning('Claim amount exceeds bill amount.Please Enter again');
        //$('#auth_amt,#mou_discount,#co_pay,#dis_others,#authorized_amt').val(0);
        //approved_amt = 0;
        ////$('#auth_amt').change();
        return false;
    }
    if (parseFloat(advance_amount) > parseFloat(Total_Net_Amount)) {

        $('#refund_amount').html(Math.round((Math.round(parseFloat(advance_amount) - parseFloat(Total_Net_Amount) + parseFloat(approved_amt))) + parseFloat(($('#collect_payment').html()))).toFixed(2))
        $('#balance_amount').html(parseFloat(0).toFixed(2));
        $('#sms_amount,#txt_received_amt').val(0);
        //$('#collect_payment').html(Math.round(Total_Net_Amount));
    }
    else {
        if ((parseFloat(approved_amt) > (parseFloat(advance_amount) + parseFloat($('#collect_payment').html()))) && (parseFloat(approved_amt) == parseFloat(Total_Net_Amount))) {
            var refund_amt = Math.abs(parseFloat(Total_Net_Amount) - parseFloat(approved_amt))
            $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat(advance_amount)).toFixed(2));
            balanceamt = 0.0;
            // balanceamt = Math.abs((parseFloat(Total_Net_Amount)) - parseFloat(approved_amt) - parseFloat($('#collect_payment').html()))

        }
        else if ((parseFloat(approved_amt) + parseFloat(advance_amount) + parseFloat($('#collect_payment').html())) > parseFloat(Total_Net_Amount)) {
            refund_amt = Math.abs(parseFloat(Total_Net_Amount) - parseFloat(approved_amt) - parseFloat(advance_amount) - $('#collect_payment').html());

            $('#refund_amount').html(Math.round(refund_amt).toFixed(2));
            balanceamt = 0.0;
        }

        else {
            $('#refund_amount').html(parseFloat(0).toFixed(2));
            balanceamt = Math.abs(parseFloat(Total_Net_Amount) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat($('#collect_payment').html()))
        }
        $('#balance_amount').html(Math.round(parseFloat(balanceamt)).toFixed(2));
        $('#txt_received_amt').val(Math.round(parseFloat(balanceamt).toFixed(2)));
        $('#sms_amount').val(Math.round(parseFloat(balanceamt).toFixed(2)));
       
        // balanceamt = parseFloat(Total_Net_Amount) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat($('#collect_payment').html());
        // $('#balance_amount').html(Math.round(balanceamt.toFixed(2)));
    }
    $('#net_amount').html(parseFloat(Total_Net_Amount1).toFixed(2));
    $('#total_tax_amount').html(tax_amount.toFixed(2));
    
     //$('#net_amount').html(Math.round(Net_Amount.toFixed(2)));
     //if (discount_amt != 0) {
     //    if (dis_type == 2) {
     //        discount_amt = parseFloat($('#net_amount').html()) * (parseFloat(discount_amt) / 100);
     //    }
     //}
     //total_discount = parseFloat(total_discount) + parseFloat(discount_amt);
     //Total_Net_Amount = parseFloat(net) - parseFloat(discount_amt);
    $('#total_net_amount').html(Math.round(Total_Net_Amount).toFixed(2));
     $('#total_discount').html(parseFloat(discount_amt).toFixed(2));
    $('#' + tbl_id).remove();
    //if ( visit_type == 2) {
    //    delete_check(tbl_id, request_id, master_service_id, visit_type)
    //}
    automated_charge_cal(auto_dis);
}
//Service Add/Edit calculation
function discount_percentage_cal() {
    debugger;
    var auto_dis = 0, Net_Amount = 0, Total_Net_Amount = 0, Total_Net_Amount1 = 0, total_discount = 0.0, net = 0.0, tax_amount = 0.0;
    var dis_type = $('#authorized_discount').val();
    if ($('#authorized_discount').val() == 1) {
        if (parseFloat($('#total_net_amount').html()) < parseFloat($('#txt_tot_discount_amt').val())) {
            toastr.warning('Discount Amount exceeds Total amount.Please Enter again');
            $('#txt_tot_discount_amt').val('');
            $('#txt_tot_discount_amt').focus();
        }
    }
    var discount_amt = ($('#txt_tot_discount_amt').val() == '' ? 0 : $('#txt_tot_discount_amt').val());
    var quantity = 0, rate = 0;
    //total_net_amount = parseFloat(total_net_amount) - parseFloat(discount_amt);
    $("#service_tbl tbody tr").each(function () {
        debugger;
        quantity = parseFloat(quantity) + parseFloat($(this).find("td").eq(1).html())
        rate = parseFloat(rate) + parseFloat($(this).find("td").eq(3).html())
        var discount_type = $(this).find("td").eq(4).html();
        var charge_percentage = $(this).find("td").eq(22).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        cur_val = $(this).find("td").eq(3).html();
        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);
        if (charge_percentage == 0) {
            Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(3).html());
            total_discount = total_discount + parseFloat($(this).find("td").eq(5).html())
            auto_dis = total_discount
            net = net + parseFloat($(this).find("td").eq(7).html())
            tax_amount = tax_amount + parseFloat($(this).find("td").eq(21).html());
            Total_Net_Amount1 = parseFloat(Total_Net_Amount1) + parseFloat(cur_val) + parseFloat($(this).find("td").eq(21).html())
        }
    });
    
    $('#total_tax_amount').html((tax_amount).toFixed(2));
    var advance_amount = 0;
    if ($('#advance_amount').html() == '' || $('#advance_amount').html() == null) {
        advance_amount = 0;
    }
    else {
        advance_amount = $('#advance_amount').html()
    }
    //Total_Net_Amount = parseFloat(Total_Net_Amount) - parseFloat(advance_amount);
    //$('#net_amount').html(Net_Amount.toFixed(2));
    //$('#total_net_amount').html(Total_Net_Amount.toFixed(2));
    debugger
    $('#net_amount').html(parseFloat(Total_Net_Amount1).toFixed(2));
    if (discount_amt != 0) {
        if (dis_type == 2) {
            discount_amt = parseFloat(Total_Net_Amount1) * (parseFloat(discount_amt) / 100);
        }
    }
   // total_discount = parseFloat(total_discount) + parseFloat(discount_amt);
    if (parseFloat(advance_amount) > parseFloat(net)) {
        Total_Net_Amount = parseFloat(Total_Net_Amount1) - parseFloat(discount_amt);
        $('#total_net_amount').html(Math.round(Total_Net_Amount).toFixed(2));
        $('#refund_amount').html(Math.round(parseFloat(advance_amount) - parseFloat(net) + parseFloat($('#collect_payment').html())).toFixed(2))
    }
    else {
        Total_Net_Amount = parseFloat(Total_Net_Amount1) - parseFloat(discount_amt) //- parseFloat(advance_amount);

        $('#total_net_amount').html(Math.round(Total_Net_Amount).toFixed(2));
        $('#total_discount').html(parseFloat(discount_amt).toFixed(2));
    }
  
    $('#total_discount').html(parseFloat(discount_amt).toFixed(2));
    var visit_type = $("input[name='optradio']:checked").val();
    //footer_binding_calc();
    //if (visit_type == 2) {
    automated_charge_cal(auto_dis);
    //}

}
//Service Add/Update table footer binding
function footer_binding_calc() {
    var  Net_Amount = 0, total_discount = 0.0, net = 0.0, tax_amount = 0.0;
    var quantity = 0, rate = 0;
    $("#service_tbl tbody tr").each(function () {
        debugger;
            quantity = parseFloat(quantity) + parseFloat($(this).find("td").eq(1).html())
            rate = parseFloat(rate) + parseFloat($(this).find("td").eq(2).text().split('(')[0]);
            Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(3).html());
            total_discount = total_discount + parseFloat($(this).find("td").eq(5).html())
            net = net + parseFloat($(this).find("td").eq(7).html())
            tax_amount = tax_amount + parseFloat($(this).find("td").eq(21).html());

    });
    $('#tbl_tot_quan').html(quantity)
    //$('#tbl_tot_rate').html(parseFloat(rate).toFixed(2))
    $('#tbl_tot_amt').html('₹' + parseFloat(Net_Amount).toFixed(2))
    $('#tbl_tot_dist').html('₹'+parseFloat(total_discount).toFixed(2))
    $('#tbl_tot_tax').html('₹' + parseFloat(tax_amount).toFixed(2))
    $('#tbl_tot_net').html('₹' + parseFloat(net).toFixed(2))
}

//Discount Authorization Calculation
function Authorized_Person_cal() {
    //discount_percentage_cal();
    debugger;
    var total_discount1 = 0.0;
    $("#service_tbl tbody tr").each(function () {
        debugger;


        //total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
        total_discount1 = total_discount1 + parseFloat($(this).find("td").eq(5).html())

    });
    var max_percentage = $('#max_percentage').html();
    var tot_discount_amt = $('#txt_tot_discount_amt').val();
    var total_net_amount = $('#total_net_amount').html();
    var collect_payment = $('#collect_payment').html();
    var discount_type = $('#authorized_discount').val();
    var net_amount = $('#net_amount').html();
    var tax_amount = $('#total_tax_amount').html();
    var advance_amount = $('#advance_amount').html();
    var refund_amt = 0;
    if (parseFloat(tot_discount_amt) > parseFloat(max_percentage)) {
        toastr.warning('Please check the max discount price');
        $('#txt_tot_discount_amt').val('');
        $('#txt_tot_discount_amt').focus();
        discount_percentage_cal();
        balanceamount = parseFloat($('#total_net_amount').html()) - parseFloat($('#collect_payment').html());
        balanceamount = Math.round(balanceamount).toFixed(2);
        $('#balance_amount').html(parseFloat(balanceamount).toFixed(2));
        $('#sms_amount,#txt_received_amt').val(balanceamount)
        return false;
    }

    if (max_percentage == '') { max_percentage = 0 }
    if (tot_discount_amt == '') { tot_discount_amt = 0 }
    if (total_net_amount == '') { total_net_amount = 0 }
    if (collect_payment == '') { collect_payment = 0 }

    var check_collected_amt = parseFloat(total_net_amount) - parseFloat(collect_payment);
    var t1 = total_net_amount;
    if (discount_type == 1) {
        tot_discount_amt = (parseFloat(tot_discount_amt));
        // total_net_amount = parseFloat(net_amount) - parseFloat(tot_discount_amt)  + parseFloat(tax_amount) - parseFloat($('#advance_amount').html());
    }
    else {
        //tot_discount_amt = (((parseFloat(tot_discount_amt) / 100) * parseFloat(net_amount)) + parseFloat(total_discount1))
        tot_discount_amt = (((parseFloat(tot_discount_amt) / 100) * parseFloat(net_amount)))
    }
    total_net_amount = parseFloat(net_amount) - parseFloat(tot_discount_amt) //+ parseFloat(tax_amount) //- parseFloat($('#advance_amount').html());

    // var total_discount = parseFloat(t1) - parseFloat(total_net_amount.toFixed());
    //var total_discount = 0.0;
    //total_discount = parseFloat(total_discount) + parseFloat($('#total_discount').html());
    total_discount = parseFloat(tot_discount_amt) // + parseFloat(total_discount1);
    //var auth_amt = ($('#auth_amt').val() == '' ? 0 : $('#auth_amt').val());
    //var mou_discount = ($('#mou_discount').val() == '' ? 0 : $('#mou_discount').val());
    //var co_pay = ($('#co_pay').val() == '' ? 0 : $('#co_pay').val());
    //var dis_others = ($('#dis_others').val() == '' ? 0 : $('#dis_others').val());
    var auth_amt = 0, mou_discount = 0, co_pay = 0, dis_others = 0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]
        auth_amt = auth_amt + parseFloat($('#td_approved_' + id).html());
        mou_discount = mou_discount + parseFloat($('#td_mou_' + id).html());
        co_pay = co_pay + parseFloat($('#td_co_' + id).html());
        dis_others = dis_others + parseFloat($('#td_dis_' + id).html());
    }
    var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
    if ($('#authorized_discount').val() == 1) {
        if (parseFloat($('#total_net_amount').html()) < parseFloat(tot_discount_amt)) {
            toastr.warning('Please check the amount');
            $('#txt_tot_discount_amt').val('');
            $('#txt_tot_discount_amt').focus();
            discount_percentage_cal();
            //balanceamount = parseFloat($('#total_net_amount').html()) - parseFloat($('#collect_payment').html());
            balanceamount = Math.abs(parseFloat($('#total_net_amount').html()) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat($('#collect_payment').html()))
            balanceamount = Math.round(balanceamount);
            $('#balance_amount').html(Math.round(parseFloat(balanceamount)).toFixed(2));
            $('#sms_amount,#txt_received_amt').val(balanceamount)
            return false;
        }
    }

    if (parseFloat($('#advance_amount').html()) > total_net_amount) {
        if (parseFloat(approved_amt) > parseFloat(total_net_amount)) {
            toastr.warning('Claim amount exceeds bill amount.Please Enter again');
            //$('#auth_amt,#mou_discount,#co_pay,#dis_others,#authorized_amt').val(0);
            //approved_amt = 0;
            return false;
        }

        //$('#collect_payment').html(total_net_amount.toFixed());
        var refund_amt = parseFloat($('#advance_amount').html()) - parseFloat(total_net_amount) + approved_amt;
        $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat($('#collect_payment').html())).toFixed(2));
        $('#balance_amount').html(parseFloat(0).toFixed(2));
        $('#sms_amount,#txt_received_amt').val(0);

    }
    else {
        if (parseFloat(total_net_amount) < 0 || total_net_amount < collect_payment) {
            toastr.warning('Please check the collected amount');
            $('#sel_authorized_person').val(0);
            $('#max_percentage_div').hide();
            $('#max_percentage').val(0);
            $('#txt_tot_discount_amt').val('');
            $('#txt_tot_discount_amt').focus();

            discount_percentage_cal();
            //balanceamount = parseFloat($('#total_net_amount').html()) - parseFloat($('#collect_payment').html())- parseFloat($('#advance_amount').html());
            //balanceamount = Math.round(balanceamount).toFixed(2);
            //$('#balance_amount').html(balanceamount);

            return false;
        }
        if (parseFloat(approved_amt) > parseFloat(total_net_amount)) {
            toastr.warning('Claim amount exceeds bill amount.Please Enter again');
            //$('#auth_amt,#mou_discount,#co_pay,#dis_others,#authorized_amt').val(0);
            //approved_amt = 0;
            return false;
        }
        if (parseFloat(approved_amt) > (parseFloat(advance_amount) + parseFloat(collect_payment)) && (parseFloat(approved_amt) == parseFloat(total_net_amount))) {
            refund_amt = Math.abs(parseFloat(total_net_amount) - parseFloat(approved_amt))
            $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat(advance_amount)).toFixed(2));
            // balanceamount = Math.abs(parseFloat(total_net_amount) - parseFloat(approved_amt) - parseFloat(collect_payment))
            balanceamount = 0.0;

        }
        else if ((parseFloat(approved_amt) + parseFloat(advance_amount) + parseFloat(collect_payment)) > parseFloat(total_net_amount)) {
            refund_amt = Math.abs(parseFloat(total_net_amount) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment));
            $('#refund_amount').html(Math.round(refund_amt).toFixed(2));
            balanceamount = 0.0;
        }
        else {

            $('#refund_amount').html(parseFloat(0).toFixed(2));
            balanceamount = Math.abs(parseFloat(total_net_amount) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment))
        }
        // balanceamount = parseFloat(total_net_amount) -parseFloat(approved_amt)- parseFloat(collect_payment) - parseFloat($('#advance_amount').html());
        balanceamount = Math.round(balanceamount).toFixed(2);
        $('#balance_amount').html(Math.round(balanceamount).toFixed(2));
        $('#sms_amount,#txt_received_amt').val(Math.round(balanceamount));
    }

    $('#total_discount').html(parseFloat(total_discount).toFixed(2));
    $('#total_net_amount').html(Math.round(total_net_amount).toFixed(2));

    // $('#auth_amt').change();
}

//Authorized amount change function
function claim_calculation() {
    debugger;
    var net_amount = $('#net_amount').html();
    var total_net_amt = $('#total_net_amount').html();
    var collect_payment = $('#collect_payment').html();
    var discount_amt = $('#total_discount').html();
    var advance_amount = $('#advance_amount').html();
    var discount_amount = $('#total_discount').html();
    var tax_amount = $('#total_tax_amount').html();
    var balance_amt = parseFloat(total_net_amt) - parseFloat(collect_payment);
    var auth_amt = 0, mou_discount = 0, co_pay = 0, dis_others = 0,c1=0,in1=0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]
       
    
        
        var is_final = $('#td_final_' + id).attr('data-id');
        if (is_final == 1) {
            
            if (!($('#divclaimType').hasClass('hidden'))) {
                if ($('#td_claimtype_' + id).attr('data-id') == 1) {
                    c1++
                }
                else if ($('#td_claimtype_' + id).attr('data-id') == 2) {
                    in1++
                }
            }
            else {
                c1++;
            }
            auth_amt = auth_amt + parseFloat($('#td_approved_' + id).html());
            mou_discount = mou_discount + parseFloat($('#td_mou_' + id).html());
            co_pay = co_pay + parseFloat($('#td_co_' + id).html());
            dis_others = dis_others + parseFloat($('#td_dis_' + id).html());
            
            //break;
        }
      
    }
    if ($('#divclaimType').hasClass('hidden') == true) {
        if (c1 == 1) {
            $('#is_final').prop('disabled', true);
        }
        else {
            $('#is_final').prop('disabled', false);
        }
    }
    else {
        if (c1 == 1 && in1==1) {
            $('#is_final').prop('disabled', true);
        }
        else {
            $('#is_final').prop('disabled', false);
        }

    }
   
   
    var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
    if (parseFloat(advance_amount) > parseFloat(total_net_amt)) {
        refund_amt = parseFloat(advance_amount) - ((Math.round(parseFloat(net_amount)) - parseFloat(discount_amt)) - parseFloat(approved_amt))
        $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat($('#collect_payment').html())).toFixed(2));
    }
    else {
        if ((parseFloat(approved_amt) > (parseFloat(advance_amount) + parseFloat(collect_payment))) && (parseFloat(approved_amt) == parseFloat(total_net_amt))) {
            var refund_amt = Math.abs(parseFloat(total_net_amt) - parseFloat(approved_amt))
            $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat(advance_amount) + parseFloat(collect_payment)).toFixed(2));
            // balance_amt = Math.abs((parseFloat(net_amount) + parseFloat(tax_amount) - parseFloat(discount_amt)) - parseFloat(approved_amt) - parseFloat(collect_payment) - parseFloat(advance_amount))
            balance_amt = 0.0;

        }
        else if ((parseFloat(approved_amt) + parseFloat(advance_amount) + parseFloat(collect_payment)) > parseFloat(total_net_amt)) {
            refund_amt = Math.abs(parseFloat(total_net_amt) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment));
            $('#refund_amount').html(Math.round(refund_amt).toFixed(2));
            balance_amt = 0.0;
        }
        else {
            $('#refund_amount').html(parseFloat(0).toFixed(2));
            balance_amt = Math.abs((Math.round(parseFloat(net_amount)) - parseFloat(discount_amt)) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment))
        }
        $('#balance_amount').html(Math.round(parseFloat(balance_amt)).toFixed(2));
        $('#sms_amount,#txt_received_amt').val(Math.round(parseFloat(balance_amt).toFixed(2)));
        $('#final_claim_amount').html(Math.round(parseFloat(approved_amt)))

    }
}

//Automated charge calculation
function automated_charge_cal(total_discount) {
    var total_discount = total_discount;
    debugger;
    var net_amount = $('#net_amount').html();
    var total_net_amount = $('#total_net_amount').html();
    var balance_amt = $('#balance_amount').html();
    var tot_tax_amount = $('#total_tax_amount').html();
    var discount_amt = ($('#txt_tot_discount_amt').val() == '' ? 0 : $('#txt_tot_discount_amt').val());
    var dis_type = $('#authorized_discount').val();
    var auth_amt = 0, mou_discount = 0, co_pay = 0, dis_others=0
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]



        var is_final = $('#td_final_' + id).attr('data-id');
        if (is_final == 1) {
            auth_amt = auth_amt + parseFloat($('#td_approved_' + id).html());
            mou_discount = mou_discount + parseFloat($('#td_mou_' + id).html());
            co_pay = co_pay + parseFloat($('#td_co_' + id).html());
            dis_others = dis_others + parseFloat($('#td_dis_' + id).html());
        }
    }
    var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
    $("#service_tbl tbody tr").each(function () {
        var charge_percentage = $(this).find("td").eq(22).html();
        var quantity = $(this).find("td").eq(1).html();
       
        if (parseFloat(charge_percentage) > 0) {
            total_discount = total_discount + parseFloat($(this).find("td").eq(5).html())
            //net_amount = parseFloat(net_amount) - parseFloat($(this).find("td").eq(3).html())
            //total_net_amount = parseFloat(total_net_amount) - parseFloat($(this).find("td").eq(7).html())
            //balance_amt = Math.abs(parseFloat(balance_amt)-parseFloat($(this).find("td").eq(7).html()))
            var percen = (parseFloat(charge_percentage) / 100) * net_amount
         
            var tax_amount = parseFloat((parseFloat($(this).find("td").eq(6).html()) / 100)) * parseFloat(percen);
            var tot_amt = (parseFloat(percen) * parseFloat(quantity)) + parseFloat(tax_amount)
            $(this).find("td").eq(2).html((parseFloat(percen).toFixed(2)));
            $(this).find("td").eq(3).html(parseFloat(percen * quantity).toFixed(2));
            $(this).find("td").eq(7).html(parseFloat(parseFloat(tot_amt)-parseFloat( $(this).find("td").eq(5).html())).toFixed(2));
            $(this).find("td").eq(21).html(parseFloat(tax_amount).toFixed(2));
            $('#net_amount').html(parseFloat(parseFloat($('#net_amount').html()) + parseFloat(percen * quantity)-parseFloat( $(this).find("td").eq(5).html())).toFixed(2));
            //if (discount_amt != 0) {
            //    if (dis_type == 2) {
            //        discount_amt = parseFloat($('#net_amount').html()) * (parseFloat(discount_amt) / 100);
            //    }
            //}
            total_discount = parseFloat(total_discount) + parseFloat(discount_amt);
            //$('#total_discount').html(parseFloat(discount_amt).toFixed(2));
            $('#total_tax_amount').html((parseFloat(tot_tax_amount) + parseFloat(tax_amount)).toFixed(2))
            
            //if(parseFloat($('#advance_amount').html())<parseFloat($('#total_net_amount').html())){
            //    var amt = parseFloat($('#total_net_amount').html()) - parseFloat($('#collect_payment').html()) - parseFloat($('#advance_amount').html())
            //    if (parseFloat(approved_amt) > parseFloat(amt)) {
            //        $('#balance_amount').html(Math.round(parseFloat(approved_amt) - parseFloat(amt)).toFixed(2))
            //        //amt = parseFloat(approved_amt) - parseFloat(amt)
            //    }
            //    else {
            //        amt = parseFloat(amt) - parseFloat(approved_amt)
            //       // $('#balance_amount').html(Math.round(parseFloat(amt)-parseFloat(approved_amt)).toFixed(2));
            //    }
            //    $('#refund_amount').html(0)
            //}
            //else{
            //    $('#balance_amount').html(0);
            //    $('#refund_amount').html(Math.round(parseFloat($('#advance_amount').html()-$('#total_net_amount').html())))
            //}
            
            $('#txt_received_amt').val($('#balance_amount').html());

        }
    })
    if (discount_amt != 0) {
        if (dis_type == 2) {
            discount_amt = parseFloat($('#net_amount').html()) * (parseFloat(discount_amt) / 100);
        }
    }
    $('#total_discount').html(parseFloat(discount_amt).toFixed(2));
    $('#total_net_amount').html(Math.round((parseFloat($('#net_amount').html()) - parseFloat($('#total_discount').html()))).toFixed(2));

    var amt = parseFloat($('#collect_payment').html()) + parseFloat($('#advance_amount').html()) + parseFloat(approved_amt)
    if (parseFloat(amt) > parseFloat($('#total_net_amount').html())) {
        $('#balance_amount').html(parseFloat(0).toFixed(2));
        $('#refund_amount').html(Math.round(parseFloat(amt) - parseFloat($('#total_net_amount').html())).toFixed(2))
    }
    else {
        $('#balance_amount').html(Math.round(parseFloat($('#total_net_amount').html()) - parseFloat(amt)).toFixed(2));
        $('#refund_amount').html(parseFloat(0).toFixed(2))
    }
    $('#txt_received_amt,#sms_amount').val($('#balance_amount').html());
    footer_binding_calc();
}

// $('#auth_amt,#mou_discount,#co_pay,#dis_others').change(function () {
//        debugger;
//        var net_amount = $('#net_amount').html();
//        var total_net_amt = $('#total_net_amount').html();
//        var collect_payment = $('#collect_payment').html();
//        var discount_amt = $('#total_discount').html();
//        var advance_amount = $('#advance_amount').html();
//        var discount_amount = $('#total_discount').html();
//        var tax_amount = $('#total_tax_amount').html();
//        var balance_amt = parseFloat(total_net_amt) - parseFloat(collect_payment);
//        var auth_amt = ($('#auth_amt').val() == '' ? 0 : $('#auth_amt').val());
//        var mou_discount = ($('#mou_discount').val() == '' ? 0 : $('#mou_discount').val());
//        var co_pay = ($('#co_pay').val() == '' ? 0 : $('#co_pay').val());
//        var dis_others = ($('#dis_others').val() == '' ? 0 : $('#dis_others').val());
//        var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
//        if (($.trim($(this).val()) != '' && $.trim($(this).val()) != 0)) {
//            if (parseFloat(approved_amt) > parseFloat(total_net_amt)) {
//                toastr.warning("Amount exceeds Bill amount");
//                $(this).val(0);
//                var id = $(this).id;
//            }



//        }
//        var auth_amt = ($('#auth_amt').val() == '' ? 0 : $('#auth_amt').val());
//        var mou_discount = ($('#mou_discount').val() == '' ? 0 : $('#mou_discount').val());
//        var co_pay = ($('#co_pay').val() == '' ? 0 : $('#co_pay').val());
//        var dis_others = ($('#dis_others').val() == '' ? 0 : $('#dis_others').val());
//        var approved_amt = (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others));
//        if (parseFloat(advance_amount) > parseFloat(total_net_amt)) {
//            refund_amt = parseFloat(advance_amount)-((parseFloat(net_amount) + parseFloat(tax_amount) - parseFloat(discount_amt)) - parseFloat(approved_amt))
//            $('#refund_amount').html(parseFloat(Math.round(refund_amt).toFixed(2))+parseFloat($('#collect_payment').html()));
//        }
//        else {
//            if ((parseFloat(approved_amt) > (parseFloat(advance_amount)+parseFloat(collect_payment))) && (parseFloat(approved_amt) == parseFloat(total_net_amt))) {
//                var refund_amt = Math.abs(parseFloat(total_net_amt) - parseFloat(approved_amt) )
//                $('#refund_amount').html(Math.round(parseFloat(refund_amt) + parseFloat(advance_amount) + parseFloat(collect_payment)));
//                // balance_amt = Math.abs((parseFloat(net_amount) + parseFloat(tax_amount) - parseFloat(discount_amt)) - parseFloat(approved_amt) - parseFloat(collect_payment) - parseFloat(advance_amount))
//                balance_amt = 0.0;

//            }
//            else if ((parseFloat(approved_amt) + parseFloat(advance_amount)+parseFloat(collect_payment)) > parseFloat(total_net_amt)) {
//                refund_amt = Math.abs(parseFloat(total_net_amt) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment));
//                $('#refund_amount').html(Math.round(refund_amt));
//                balance_amt = 0.0;
//            }
//            else {
//                $('#refund_amount').html(0);
//                balance_amt = Math.abs((parseFloat(net_amount) + parseFloat(tax_amount) - parseFloat(discount_amt)) - parseFloat(approved_amt) - parseFloat(advance_amount) - parseFloat(collect_payment))
//            }
//            $('#balance_amount').html(Math.round(parseFloat(balance_amt).toFixed(2)));
//            $('#sms_amount,#txt_received_amt').val(Math.round(parseFloat(balance_amt).toFixed(2)));


//        }
//      //  var amt = parseFloat(net_amount) - 
//        //var amt = parseFloat(balance_amt) - (parseFloat(auth_amt) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others))
//})
//$('#authorized_amt').change(function () {
//    debugger;
//    var total_net_amt = $('#total_net_amount').html();
//    var auth_amt=$('#authorized_amt').val();
//    if (parseFloat(auth_amt) > parseFloat(total_net_amt)) {
//        toastr.warning('Authorized amount exceeds Total amount.Please Enter Again');
//        $('#authorized_amt').val(0);
//    }
//})

//Calculation End

// Claim Start //


$("#Entity_yes").click(function () {
    debugger;
    $('#div_EntityType').removeClass('hide');
    //$('.divEmp').removeClass('hide');

        //if ($('#P_emp_name').val() == 'null') {
        //    $('#txt_emp_name').val('')
        //}
        //else {
        //    $('#txt_emp_name').val($('#P_emp_name').val())
        //}

        //if ($('#P_emp_code').val() == 'null') {
        //    $('#txt_emp_code').val('')
        //}
        //else {
        //    $('#txt_emp_code').val($('#P_emp_code').val())
        //}
});

$("#Entity_no").click(function () {
    debugger;
    claim_clear()
});

function claim_clear() {
    $('#div_EntityType').addClass('hide');
    $('.divEmp').addClass('hide');
    $('#txt_emp_name,#txt_emp_code').val('');
    $('#divInsuranceName').addClass('hide');
    $('#EntityType_Insurance').removeClass('active');
    $('#EntityType_Corporate').removeClass('active');
    $('#EntityType_Insurance').addClass('not-active');
    $('#EntityType_Corporate').addClass('not-active');
    $('#EntityType').val('');
    $('#HdnEntityid').val('');
    $('#CMultiPay').prop('checked', false);
    $('#divMultiPay').addClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').val(0);
}

//function claimreload() {
//    $('#div_EntityType').addClass('hide');
//    $('#divInsuranceName').addClass('hide');
//    $('#EntityType_Insurance').removeClass('active');
//    $('#EntityType_Corporate').removeClass('active');
//    $('#EntityType_Insurance').addClass('not-active');
//    $('#EntityType_Corporate').addClass('not-active');
//    $('#Entity_yes').removeClass('active');
//    $('#Entity_yes').addClass('not-active');
//    $('#Entity_no').removeClass('not-active');
//    $('#Entity_no').addClass('active');
//    $('#EntityType').val('');
//    $('#HdnEntityid').val('');
//}

$('#EntityType').change(function () {
    debugger;
    $('#divMultiPay').show();
    var entity_type = $('#EntityType').val();
    $('#ddInsuranceName').val('');
    $('#divInsuranceName').removeClass('hide');
    $('#divMultiPay').removeClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').prop('checked', false);
    $('#CMultiPay').val(0);
    if (entity_type == 1) {
        $('#ins_chk_lbl').html('Indirect');
        $('#ins_sel_lbl').html('TPA<span class="red">*</span>');
        $('.divEmp').addClass('hide');
        $('#txt_emp_name,#txt_emp_code').val('');
    }
    else {
        $('#ins_chk_lbl').html('MultiPay');
        $('#ins_sel_lbl').html('Insurance Name<span class="red">*</span>');
        $('.divEmp').removeClass('hide');

        if ($('#P_emp_name').val() == 'null') {
            $('#txt_emp_name').val('')
        }
        else {
            $('#txt_emp_name').val($('#P_emp_name').val())
        }

        if ($('#P_emp_code').val() == 'null') {
            $('#txt_emp_code').val('')
        }
        else {
            $('#txt_emp_code').val($('#P_emp_code').val())
        }
    }
});
//Indirect or Multipay onchange
$('#CMultiPay').change(function () {
    debugger;
    this.value = this.checked ? 1 : 0;
    if (this.value == '1') {
        $('#divTPA').removeClass('hide');
    }
    else {
        $('#divTPA').addClass('hide');
        $('#MPCIName').val('');
    }
})

//Autocomplete for Insurance and corporate
$('#ddInsuranceName').autocomplete({
    
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Ipmanagement/AutoEntity',
            type: "POST",
            dataType: "json",
            //data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val(), branchid: $('#pkg_branch_id').val() },
            data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val() },
            success: function (data) {
                debugger;
                console.log(data);
                var data2 = JSON.parse(data);
                var data = data2.data;
                response($.map(data, function (item) {
                    return { label: item.entity_name, value: item.entity_name, id: item.master_entity_id };
                }))

            }
        })
    },
    minLength: 1,
        select: function (event, ui) {
        debugger;
       
        $('#HdnEntityid').val(ui.item.id);
        Corporate_Insurance($('#HdnEntityid').val(), 0);
         $('#MPCIName').val(0);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
 
});


//Load Insurance Name when corporate is choosed
function Corporate_Insurance(Corporateid, CIid) {
    debugger;
    var dml = '', EntityType = $('#EntityType').val();

    if (EntityType == 1) {
        dml = 'PITPA'
    }
    else if (EntityType == 2) {
        dml = 'PCIN'
    }

    var Billingata = {
        Dml_Indicator: dml,
        insurance_id: Corporateid

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Billingata),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            $('#MPCIName').empty();

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

            }
            else {

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

                    var CInsurance;

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

                        CInsurance = CInsurance + '<option value="' + emp.master_entity_billing_id + '">' + emp.entity_name + '</option>';

                    });
                    $('#MPCIName').append(default_opt + CInsurance);

                    if (CIid != '' || CIid != 0) {
                        $('#MPCIName').val(CIid);
                    }
             

                }
                else {
                    console.log(data);
                }
                var sel = ''
                sel = $('#MPCIName').val();
                if (sel == null) {
                    debugger;
                    $('#divMultiPay').hide();
                    $('#divTPA').hide();
                }
                else {
                    $('#divMultiPay').show();
                    $('#divTPA').show();
                }
                
            }
        }
    });

}

// Claim End 

//Payment mode onchange
$('#sel_payment_mode').change(function () {
    debugger;
    var mode = $('#sel_payment_mode option:selected').text();
    if (mode.toUpperCase().includes('CARD')) {
        $('#div_bank').removeClass('hidden');
    }
    else {
        $('#div_bank').addClass('hidden');
        $('#txt_bank_name').val('');
    }
})

// Billing OTP on discount applied
function send_otp(flag) {
    $('#Hdnflag').val(flag);
    var dis_type = $('#authorized_discount').val();
    var discount_amt = ($('#txt_tot_discount_amt').val() == '' ? 0 : $('#txt_tot_discount_amt').val());
    var Total_Net_Amount1 = 0;
    //$("#service_tbl tbody tr").each(function () {
    //    var id1 = $(this).closest("tr").prop("id");
        
    //    var discount_type = $(this).find("td").eq(4).html();
    //    var charge_percentage = $(this).find("td").eq(22).html();
    //    var dis_amt = '', dis_type = '', cur_val = '';
    //    cur_val = $(this).find("td").eq(3).html();
    //    if (discount_type != '') {
    //        discount_type = discount_type.split(' ');
    //        dis_amt = discount_type[0];
    //        dis_type = discount_type[1];
    //        if (dis_type == '₹') {
    //            cur_val = cur_val - dis_amt
    //        }
    //        else if (dis_type == '%') {
    //            cur_val = cur_val - ((cur_val / 100) * dis_amt)
    //        }
    //    }
    //    if (charge_percentage == 0) {
           
    //        Total_Net_Amount1 = parseFloat(Total_Net_Amount1) + parseFloat(cur_val) + parseFloat($(this).find("td").eq(21).html())
    //    }


    //});
    //if (discount_amt != 0) {
    //    if (dis_type == 2) {
    //        discount_amt = parseFloat(Total_Net_Amount1) * (parseFloat(discount_amt) / 100);
    //    }
    //}

    var DoctorData = {

        dml_indicator: 'BOTP',
        visit_reportid: $('#Vvisit_reportid').val(),
        total_net_amount: $('#net_amount').html(),
        discount_amount: $('#total_discount').html(),
        patient_name: $('#PatName').val(),//$('.pat-stripe-user-name').html(),
        patient_id: $('#hdnpatientapp').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billing',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;

                $('#otp_popup').modal('toggle');
            }
        }
    })
}

//otp submit button
$('#btn_otp_submit').click(function () {
    if ($.trim($('#txt_otp').val()) == '') {
        $('#Ptxt_otp').show();
        $('#Ptxt_otp').fadeOut(8000);
        $('#Ptxt_otp').html('Please Enter OTP');
        $('#txt_otp').focus();
        $('#txt_otp').val();
        return false;
    }
    var DoctorData = {

        dml_indicator: 'BOTPC',
        visit_reportid: $('#Vvisit_reportid').val(),
        otp: $('#txt_otp').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billing',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                data1 = data1.data.Table[0];
                if (data1.Strmsg == 'success') {
                    $('#hdn_wo_otp').val(2);
                    $('#otp_popup').modal('toggle');
                    toastr.success('OTP Verified Successfully');
                    if ($('#Hdnflag').val() == 1) {
                        var bill = bill_insert('bill');
                        $.when(bill)
                    .then(function (data) {
                        receipt_insert(data);
                        claim_billing_insert(data);

                    });
                    }
                    else if ($('#Hdnflag').val() == 2) {
                        sms_function();
                    }
                }
                else {
                    toastr.warning('OTP is wrong.Please Enter again');
                }
            }
        }
    })
})
//otp without submit
$('#btn_otp_wo_submit').click(function () {
    $('#hdn_wo_otp').val('1');
    $('#otp_popup').modal('toggle');
    if ($('#Hdnflag').val() == 1) {
        var bill = bill_insert('bill');
        $.when(bill)
    .then(function (data) {
        receipt_insert(data);
        claim_billing_insert(data);

    });
    }
    else if ($('#Hdnflag').val() == 2) {
        sms_function();
    }
})

//Resend OTP button
$('#btn_resend_otp').click(function () {

    var DoctorData = {

        dml_indicator: 'BOTPR',
        visit_reportid: $('#Vvisit_reportid').val(),
        total_net_amount: $('#net_amount').html(),
        discount_amount: $('#total_discount').html(),
        patient_name: $('#PatName').val(),//$('.pat-stripe-user-name').html(),
        patient_id: $('#hdnpatientapp').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billing',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;

                toastr.success('OTP Resend Successfully.');
            }
        }
    })

});

//Claim concept 
$('#btnclaimadd').click(function () {
    debugger;
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    if ($.trim($('#claim_no').val()) == '') {
        $('#Pclaim_no').show();
        $('#Pclaim_no').fadeOut(8000);
        $('#Pclaim_no').html('Please Enter Claim');
        $('#claim_no').focus();
        $('#claim_no').val();
        return false;
    }
    if (!$('#divclaimType').hasClass('hidden')) {
        if ($('#claim_type').val() == '' || $('#claim_type').val() == 0) {
            $('#Pclaim_type').show();
            $('#Pclaim_type').fadeOut(8000);
            $('#Pclaim_type').html('Please Enter Claim');
            $('#claim_type').focus();
            $('#claim_type').val();
            return false;
        }
    }
    if ($.trim($('#auth_amt').val()) == '' || $.trim($('#auth_amt').val()) == 0) {
        $('#Pauth_amt').show();
        $('#Pauth_amt').fadeOut(8000);
        $('#Pauth_amt').html('Please Enter approved amount');
        $('#auth_amt').focus();
        $('#auth_amt').val();
        return false;
    }
    var approved_amount = $('#auth_amt').val();
    var mou_discount = ($('#mou_discount').val() == '') ? 0 : $('#mou_discount').val();
    var co_pay = ($('#co_pay').val() == '') ? 0 : $('#co_pay').val();
    var dis_others = ($('#dis_others').val() == '') ? 0 : $('#dis_others').val();
    var tot_amt = parseFloat(approved_amount) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others);
    var t1=0
    if ($('#is_final').val() == 1) {
        //if (parseFloat($('#total_net_amount').html()) < parseFloat(tot_amt)) {
        //    toastr.warning('Amount should be less the total amount')
        //    $('#auth_amt,#mou_discount,#co_pay,#dis_others').val(0);
        //    return false;
        //}
        //else {
        t1 = tot_amt
        //}
    }
    //else {
    var claim_no = $('#claim_no').val();
    var claim_type = ($('#claim_type').val() == '0' || $('#claim_type').val() == '') ? 0 : $('#claim_type').val();
    var claim_type_text = ($('#claim_type').val() == '0' || $('#claim_type').val() == '') ? '-' : $('#claim_type option:selected').text();
    var auth_amt1 = 0, mou_discount1 = 0, co_pay1 = 0, dis_others1 = 0;
    var approve_date = ($('#approve_date').val() == '') ? '-' : $('#approve_date').val()
    var count = 0,arr=[];
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]
        arr.push(id);
        if ($('#td_final_' + id).attr('data-id') == 1) {
            count++;

            auth_amt1 = auth_amt1 + parseFloat($('#td_approved_' + id).html());
            mou_discount1 = mou_discount1 + parseFloat($('#td_mou_' + id).html());
            co_pay1 = co_pay1 + parseFloat($('#td_co_' + id).html());
            dis_others1 = dis_others1 + parseFloat($('#td_dis_' + id).html());
        }
    }
    var approved_amt = (parseFloat(auth_amt1) + parseFloat(mou_discount1) + parseFloat(co_pay1) + parseFloat(dis_others1));
        
    if (((parseFloat(t1) + parseFloat(approved_amt)) > parseFloat($('#total_net_amount').html())) && $('#is_final').val() == 1) {
        toastr.warning('Amount Exceeds the bill amount..Kindly check the amount')
        return false;
    }
    else {
        var row_count =($('#tbl_claim>tbody>tr').length==0)?0: Math.max.apply(Math, arr);
           
        var tr = '<tr id=tclaim_' + (row_count + 1) + '><td id=td_claimid_' + (row_count + 1) + ' data-id=0>' + claim_no + '</td><td id=td_claimtype_' + (row_count + 1) + ' data-id=' + claim_type + '>' + claim_type_text + '</td><td id=td_approved_' + (row_count + 1) + '>' + approved_amount + '</td><td id=td_mou_' + (row_count + 1) + '>' + mou_discount + '</td><td id=td_co_' + (row_count + 1) + '>' + co_pay + '</td><td id=td_dis_' + (row_count + 1) + '>' + dis_others + '</td><td id=td_date_' + (row_count + 1) + '>' + approve_date + '</td><td id=td_final_'+(row_count+1)+' data-id='+$('#is_final').val()+'>'+($('#is_final').val()==1?'Yes':'No')+'</td><td><span class="btn btn-xs mr-10 btn-edit " onclick=claim_edit(' + (row_count + 1) + ')><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick="claim_delete(' + (row_count + 1) + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>'
        $('#tbl_claim tbody:last').append(tr);
        $('#final_claim_amount').html(Math.round(parseFloat(t1) + parseFloat(approved_amt)))
        $('#claim_no').val('');
        $('#claim_type').val(0);
        $('#auth_amt').val(0);
        $('#mou_discount').val(0);
        $('#co_pay').val(0);
        $('#dis_others').val(0);
        //if (count!=0 || $('#is_final').val()=='1') {
        //    $('#is_final').prop('disabled', true)
        //}
        $('#is_final').prop('checked', false)
        $('#is_final').val(2);
        claim_calculation();
    }
    //}
})
})
//claim edit
function claim_edit(id) {
    var bill = CheckFilter();
    $.when(bill)
.then(function (data) {
    $('#claim_no').val($('#td_claimid_' + id).html());
    $('#claim_type').val($('#td_claimtype_' + id).attr('data-id'));
    $('#auth_amt').val($('#td_approved_' + id).html());
    $('#mou_discount').val($('#td_mou_' + id).html());
    $('#co_pay').val($('#td_co_' + id).html());
    $('#dis_others').val($('#td_dis_' + id).html());
    var count = 0,in1=0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id1 = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id1 = id1.split('_');
        id1 = id1[1]
       
        if ($('#td_final_' + id1).attr('data-id') == 1) {
            if (!($('#divclaimType').hasClass('hidden'))) {
                if ($('#td_claimtype_' + id1).attr('data-id') == 1) {
                    count++
                }
                else if ($('#td_claimtype_' + id1).attr('data-id') == 2) {
                    in1++
                }
            }
            else {
                count++;
            }
        }
            
    }
    if ($('#divclaimType').hasClass('hidden') == true) {
        if (count == 1) {
            $('#is_final').prop('checked', false);
            $('#is_final').prop('disabled', true);
            $('#is_final').val(2);
        }
    }
    else {
        if ((count == 1) && $('#td_claimtype_' + id).attr('data-id')==1) {
            $('#is_final').prop('checked', false);
            $('#is_final').prop('disabled', true);
            $('#is_final').val(2);
        }
        if ((in1 == 1) && $('#td_claimtype_' + id).attr('data-id') == 2) {
            $('#is_final').prop('checked', false);
            $('#is_final').prop('disabled', true);
            $('#is_final').val(2);
        }

    }

    if ($('#td_final_' + id).attr('data-id') == 1) {
        $('#is_final').prop('checked', 'checked');
        $('#is_final').prop('disabled', false);
        $('#is_final').val(1);
    }
    
    ($('#td_date_' + id).html() == '-') ? $('#approve_date').val('') : $('#approve_date').val($('#td_date_' + id).html());
    
    $('#hdn_claim_rowid').val(id);
    $('#btnclaimadd').hide();
    $('#btnclaimup').show();
})
}
//Claim Delete
function claim_delete(id) {
    if ($('#td_final_' + id).attr('data-id') == 1) {
        $('#is_final').prop('disabled',false)
    }
    $('#tclaim_' + id).remove();
    claim_calculation();

}
//Claim update
$('#btnclaimup').click(function () {
    if ($.trim($('#claim_no').val()) == '') {
        $('#Pclaim_no').show();
        $('#Pclaim_no').fadeOut(8000);
        $('#Pclaim_no').html('Please Enter Claim');
        $('#claim_no').focus();
        $('#claim_no').val();
        return false;
    }
    if (!$('#divclaimType').hasClass('hidden')) {
        if ($('#claim_type').val() == '' || $('#claim_type').val() == 0) {
            $('#Pclaim_type').show();
            $('#Pclaim_type').fadeOut(8000);
            $('#Pclaim_type').html('Please Enter Claim');
            $('#claim_type').focus();
            $('#claim_type').val();
            return false;
        }
    }
    if ($.trim($('#auth_amt').val()) == '' || $.trim($('#auth_amt').val()) == 0) {
        $('#Pauth_amt').show();
        $('#Pauth_amt').fadeOut(8000);
        $('#Pauth_amt').html('Please Enter approved amount');
        $('#auth_amt').focus();
        $('#auth_amt').val();
        return false;
    }
    var approved_amount = $('#auth_amt').val();
    var mou_discount = ($('#mou_discount').val() == '') ? 0 : $('#mou_discount').val();
    var co_pay = ($('#co_pay').val() == '') ? 0 : $('#co_pay').val();
    var dis_others = ($('#dis_others').val() == '') ? 0 : $('#dis_others').val();
    var tot_amt = parseFloat(approved_amount) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others);
    var t1=0
    if ($('#is_final').val() == 1) {
        //if (parseFloat($('#total_net_amount').html()) < parseFloat(tot_amt)) {
        //    toastr.warning('Amount should be less than total amount')
        //    $('#auth_amt,#mou_discount,#co_pay,#dis_others').val(0);
        //    return false;
        //}
        //else {
            t1 = tot_amt
        //}
    }
    var claim_no = $('#claim_no').val();
    var claim_type = ($('#claim_type').val() == '0' || $('#claim_type').val() == '') ? 0 : $('#claim_type').val();
    var claim_type_text = ($('#claim_type').val() == '0' || $('#claim_type').val() == '') ? '-' : $('#claim_type option:selected').text();
    var auth_amt1 = 0, mou_discount1 = 0, co_pay1 = 0, dis_others1 = 0;
    var count = 0;
    for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
        var id = $('#tbl_claim').find("tr").eq(i + 1).prop("id");
        id = id.split('_');
        id = id[1]
        if (parseInt($('#hdn_claim_rowid').val()) == id) {
            continue;
        }
        if ($('#td_final_' + id).attr('data-id') == 1) {
            count++;

            auth_amt1 = auth_amt1 + parseFloat($('#td_approved_' + id).html());
            mou_discount1 = mou_discount1 + parseFloat($('#td_mou_' + id).html());
            co_pay1 = co_pay1 + parseFloat($('#td_co_' + id).html());
            dis_others1 = dis_others1 + parseFloat($('#td_dis_' + id).html());
        }
    }
    var approved_amt = (parseFloat(auth_amt1) + parseFloat(mou_discount1) + parseFloat(co_pay1) + parseFloat(dis_others1));
    //var approved_amount = $('#auth_amt').val();
    //var mou_discount = $('#mou_discount').val();
    //var co_pay = $('#co_pay').val();
    //var dis_others = $('#dis_others').val();
    //var tot_amt = parseFloat(approved_amount) + parseFloat(mou_discount) + parseFloat(co_pay) + parseFloat(dis_others);
    if (((parseFloat(t1) + parseFloat(approved_amt)) > parseFloat($('#total_net_amount').html())) && $('#is_final').val() == 1) {
        toastr.warning('Amount Exceeds the bill amount..Kindly check the amount')
        return false;
    }
    if ((parseFloat(t1) + parseFloat(approved_amt)) < parseFloat($('#collect_claim_amount').html())) {
        toastr.warning('Amount Should not be less than Collected Claim Amount')
        return false;
    }
    var id = $('#hdn_claim_rowid').val();
    $('#td_claimid_' + id).html($('#claim_no').val());
    $('#td_claimtype_' + id).html(claim_type_text);
    $('#td_claimtype_' + id).attr('data-id', claim_type);
    $('#td_final_' + id).attr('data-id', $('#is_final').val());
    $('#td_final_' + id).html(($('#is_final').val() == 1 ? 'Yes' : 'No'));
    $('#td_approved_' + id).html(($('#auth_amt').val() == '') ? 0 : $('#auth_amt').val());
    $('#td_mou_' + id).html(($('#mou_discount').val() == '') ? 0 : $('#mou_discount').val());
    $('#td_co_' + id).html(($('#co_pay').val() == '') ? 0 : $('#co_pay').val());
    $('#td_dis_' + id).html(($('#dis_others').val() == '') ? 0 : $('#dis_others').val())
    $('#td_date_' + id).html($('#approve_date').val())
    //if (count != 0 || $('#is_final').val() == '1') {
    //    $('#is_final').prop('disabled', true)
    //}
    $('#final_claim_amount').html(Math.round(parseFloat(t1) + parseFloat(approved_amt)))
    $('#is_final').prop('checked', false)
    $('#is_final').val(2);
    $('#claim_no').val('');
    $('#auth_amt').val(0);
    $('#mou_discount').val(0);
    $('#co_pay').val(0);
    $('#dis_others').val(0);
    $('#hdn_claim_rowid').val('');
    $('#btnclaimup').hide();
    $('#btnclaimadd').show();
    $('#claim_type').val(0);
    claim_calculation();

})
//claim type change function
$('#claim_type').change(function () {
    debugger;
    var value = $('#claim_type').val();
    var count = 0,in1=0;
    for (i = 1; i <= $('#tbl_claim>tbody>tr').length; i++) {
        var claim_type = $('#td_claimtype_' + i).attr('data-id');
        var is_final = $('#td_final_' + i).attr('data-id');
        if (claim_type == value && is_final == 1) {
            count++
        }
        //else if (claim_type == 2 && is_final == 1) {
        //    count++
        //}
    }
    if (count==1) {
        $('#is_final').attr('disabled', true);
    }
    else {
        $('#is_final').attr('disabled', false);
    }
})
//Claim Billing Insert
function claim_billing_insert(data) {
    var data = JSON.parse(data);
    if (data.msg == "Success") {

        debugger;
        console.log(data);
        var data1 = data.data;
        var claimArray = [];
        console.log(data1.Table[0].billing_no);
        if ($('#tbl_claim>tbody>tr').length > 0) {
            for (var i = 0; i < $('#tbl_claim>tbody>tr').length; i++) {
                var claimlist = {};
                var id = i + 1;
                var date1=''
                if ($('#td_date_' + id).html() == '-') {
                    date1=moment(new Date()).format('YYYY-MM-DD')
                }
                else {
                    var date = $('#td_date_' + id).html().split('/')
                    date1 = date[2] + '-' + date[1] + '-' + date[0]
                }
                claimlist.claim_no = $('#td_claimid_' + id).html()
                claimlist.claim_type = $('#td_claimtype_' + id).attr('data-id')
                claimlist.approved_amount = $('#td_approved_' + id).html()
                claimlist.mou_discount = ($('#td_mou_' + id).html() == '') ? 0 : $('#td_mou_' + id).html()
                claimlist.co_pay = ($('#td_co_' + id).html() == '') ? 0 : $('#td_co_' + id).html()
                claimlist.other_discount = ($('#td_dis_' + id).html() == '') ? 0 : $('#td_dis_' + id).html()
                claimlist.is_final_amount = ($('#td_final_' + id).attr('data-id') == '') ? 2 : $('#td_final_' + id).attr('data-id')
                claimlist.billing_no = data1.Table[0].billing_no;
                claimlist.dml_indicator = 'I'
                claimlist.claim_billing_id = $('#td_claimid_' + id).attr('data-id')
                claimlist.approve_date = date1
                claimArray.push(claimlist);
            }
        }
        else {
            var claimlist = {};
            claimlist.billing_no = data1.Table[0].billing_no;
          
            claimArray.push(claimlist);

        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/Billing_Claim',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(claimArray),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);

                if (data.msg == "Success") {
                }
            }
        })
    }
}
//Bill copy edit for Insurance Bill
function bill_copy_edit() {
    debugger;
    var DoctorData = {
        billing_no: $('#hndbilling_copy_no').val(),
        dml_indicator: 'BCE'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $('#billingDetailsWrap').hide();
                    $('#discount_div').addClass('hidden');
                    $('#div_claim').addClass('hidden');
                    $('#divpay').addClass('hidden');
                    $('#pay_div').addClass('hidden');
                    $('#btn_submit').addClass('hidden');
                    $('#btn_submit_copy').removeClass('hidden');
                    var patient_id = data1.Table[0].patient_id;
                    var bill = PatientSearch(patient_id, data1.Table[0].visit_type, $('#hndbranch').val(), data1.Table[0].visit_report_id);
                    $.when(bill)
                   .then(function (data3) {
                       var da1 = JSON.parse(data3);
                       if (da1.msg == "Success") {
                           console.log(data1);
                           da1 = da1.data;
                        
                           $('#hdn_entity').val(da1[0].entity_id);
                           $('#hdn_is_scheme').val(da1[0].is_scheme);
                       }

                   });
                    $('#pkg_branch_id').val($('#hndbranch').val());
                    $('#hdnvisit_report_id').val(data1.Table[0].visit_report_id);
                    $('.pat-stripe-bgop').show();
                    $('#total_net_amount').html(Math.round(parseFloat(data1.Table[0].total_amount)).toFixed(2));
                    $('#advance_amount').html(0);
                    $('#hndbilling_class').val(data1.Table[0].billing_class);
                    $('#hndward_id').val(data1.Table[0].ward_id);
                    $('#net_amount').html(parseFloat(data1.Table[0].total_amount).toFixed(2));
                    $('#total_discount').html(0);
                    $('#total_tax_amount').html(Math.round(data1.Table[0].tax_amount));
                    $('#refund_amount').html(parseFloat(0).toFixed(2));
                    $('#balance_amount').html(Math.round(parseFloat(data1.Table[0].total_amount)).toFixed(2));
                    $('#collect_payment').html(0);
                    //$('.advance_amount_div,.collect_amount_div,.refund_amount_div,.balance_amount_div').addClass('hide');
                    if (data1.Table[0].visit_type == 1) {
                        $("#op").prop("checked", true);
                    }
                    else if (data1.Table[0].visit_type == 2)
                    { $("#ip").prop("checked", true); }
                    else if (data1.Table[0].visit_type == 3)
                    { $("#home_care").prop("checked", true); }
                    else if (data1.Table[0].visit_type == 4)
                    { $("#diagnostics").prop("checked", true); }
                    else if (data1.Table[0].visit_type == 7)
                    { $("#daycare").prop("checked", true); }
                    for (var i = 0; i < data1.Table.length; i++) {
                        $('#hdnpatientapp').val(patient_id);

                        var rowCount = $('#service_tbl tbody tr').length;
                        if (rowCount == 0) {
                            rowCount = 1
                        }
                        else {
                            var id = $('#service_tbl tbody tr:last').attr('id');
                            id = id.split('_');
                            rowCount = parseInt(id[1]) + (1);
                        }

                        var sel_discount_type = data1.Table[i].service_dis_type;
                        if (sel_discount_type == 1) {
                            sel_discount_type = '₹';
                        }
                        else {
                            sel_discount_type = '%';
                        }
                        var date_time;
                        if (data1.Table[i].base_amount_type == 4) {
                            date_time = data1.Table[i].request_date + " " + data1.Table[i].request_time + " - " + data1.Table[i].end_date + " " + data1.Table[i].end_time;
                        }
                        else {
                            date_time = data1.Table[i].request_date + " " + data1.Table[i].request_time
                        }
                        if (data1.Table[0].is_entity == 1) {
                            var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour(data1.Table[i].base_amount_type) + '"><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].service_quantity + '</td><td>' + parseFloat(data1.Table[i].service_quantity_amount).toFixed(2) + '</td>'
                            tr += '<td>' + parseFloat(data1.Table[i].amount).toFixed(2) + '</td><td>' + data1.Table[i].discount_detail + ' ' + sel_discount_type + '</td><td>' + parseFloat(data1.Table[i].service_discount_amount).toFixed(2) + '</td><td>' + data1.Table[i].service_tax_percentage + '%</td><td>' + parseFloat(data1.Table[i].service_net_amount).toFixed(2) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_number + '</td><td class="hide">0</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">' + data1.Table[i].billing_details_id + '</td><td class="hide">' + parseFloat(data1.Table[i].service_tax_amount).toFixed(2) + '</td><td class="hide">0</td>'
                            tr += '<td><span class="btn btn-xs mr-10 btn-edit service_edit"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete" onclick="service_copy_delete(' + rowCount + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
                            $('#service_tbl_footer1').show();
                            $('#btn_add').show();
                        }
                        else {
                            var tr = '<tr id="tr_' + rowCount + '" class="' + bill_row_colour(data1.Table[i].base_amount_type) + '"><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].service_quantity + '</td><td>' + parseFloat(data1.Table[i].service_quantity_amount).toFixed(2) + '</td>'
                            tr += '<td>' + parseFloat(data1.Table[i].amount).toFixed(2) + '</td><td>' + data1.Table[i].discount_detail + ' ' + sel_discount_type + '</td><td>' + parseFloat(data1.Table[i].service_discount_amount).toFixed(2) + '</td><td>' + data1.Table[i].service_tax_percentage + '%</td><td>' + parseFloat(data1.Table[i].service_net_amount).toFixed(2) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_number + '</td><td class="hide">0</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">' + data1.Table[i].billing_details_id + '</td><td class="hide">' + parseFloat(data1.Table[i].service_tax_amount).toFixed(2) + '</td><td class="hide">0</td>'
                            //tr += '<td>' + data1.Table[i].discount_detail + ' '+sel_discount_type+'</td><td>' + data1.Table[i].amount + '</td><td>'+data1.Table[i].request_date+'</td><td>' + data1.Table[i].first_name + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td>'
                            //tr += '<td><span class="btn btn-xs btn-primary service_edit"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick="service_delete(' + rowCount + ')"><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';
                            tr += '<td> - </td></tr>';
                            $('#service_tbl_footer1').hide();
                            $('#btn_add').hide();
                        }
                        $('#service_tbl tbody').append(tr);
                       //- LoadDoctor();
                        footer_binding_calc();
                    }

                }
                else {
                    console.log(data2);
                }
            }
        }
    })
}
//Copy Bill service delete
function service_copy_delete(id) {
    $('#tr_' + id).remove();
}
//Bill_copy_submit
$('#btn_submit_copy').click(function () {
    debugger;
    var bill = bill_insert('copy');
    $.when(bill)
.then(function (data) {
    var data = JSON.parse(data);
    if (data.msg = 'Success') {

        var visit_type = $("input[name='optradio']:checked").val();

        toastr.warning("<button type='button' id='confirmationRevertA4' class='btn btn-warning btn-xs mt20'>Summary Bill</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Click the print option',
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            //timeOut: 20000000,
            timeOut: 0,
            extendedTimeOut: 0,

            onShown: function (toast) {
                debugger;
                $("#confirmationRevertA4").click(function () {
                    debugger;
                    //var report = ip_bill_report(data.data.Table[0].billing_no, data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val(), 2)
                    formid = '';
                    if (visit_type == 2) {
                        formid = '114';
                    }
                    else {
                        formid = '120';
                    }

                    var report = ip_bill_report(data.data.Table[0].billing_no, data.data.Table[0].patientid, data.data.Table[0].hospitalid, $('#pkg_branch_id').val(), '', '', formid)


                    $.when(report)
                  .then(function (data) {
                      window.location.href = '/BillingMaster/billing_view';
                  });
                })
                $("#confirmationRevertNo").click(function () {
                    window.location.href = '/BillingMaster/billing_view';
                })
            },
            onHidden: function (toast) {
                window.location.href = '/BillingMaster/billing_view';
            }
        })



    }
    else {
        console.log(data);
    }


});
})
//Load visit type
function LoadVisitType(op_val,type) {
    debugger;
    var DoctorData = {
        dml_indicator: 'LVT',
    }
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                $('#div_visit').empty();
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '', hide = '';
                    $.each(data1.Table, function (i, emp) {
                        hide = (emp.visit_typeid == '2') ? 'hide' : '';
                        style = (emp.visit_typeid == '2') ? '' : 'style="display:inline !important;"'
                        tr = tr + ' <label class="radio-inline ' + hide + '" ' + style + '><input type="radio" class="ClsVisit" name="optradio" value="' + emp.visit_typeid + '" id="' + emp.id + '" onchange=visit_change(' + emp.visit_typeid + ')>' + emp.visit_type_name + '</label>'
                    })
                    $('#div_visit').append(tr);
                    if (type != '' && type != 0 && type != null) {
                        $("input[name='optradio'][value='" + type + "']").prop('checked', true);
                        visit_change(type);
                    }
                    ($('#HEstimateId').val() != '0' && $('#HEstimateId').val() != '') ? $('.ClsVisit').prop('disabled', 'disabled') : ''
                    if (op_val == 1) {
                        $('#op').prop('checked', true)
                        $('#op').val($('#op_daycare_val').val())

                        $('#ip').prop('disabled', true)
                        $('#home_care').prop('disabled', true)
                        $('#diagnostics').prop('disabled', true)
                        $('#daycare').prop('disabled', true)
                        $('#emergency_reg').prop('disabled', true)

                        visit_change(op_val)
                    }
                    else if (op_val == 7) {
                        $('#daycare').prop('checked', true)
                        $('#daycare').val($('#op_daycare_val').val())

                        $('#ip').prop('disabled', true)
                        $('#op').prop('disabled', true)
                        $('#home_care').prop('disabled', true)
                        $('#diagnostics').prop('disabled', true)
                        $('#emergency_reg').prop('disabled', true)
                    }
                    else if (op_val == 8) {
                        $('#emergency_reg').prop('checked', true)
                        $('#emergency_reg').val($('#op_daycare_val').val())

                        $('#ip').prop('disabled', true)
                        $('#op').prop('disabled', true)
                        $('#home_care').prop('disabled', true)
                        $('#diagnostics').prop('disabled', true)
                        $('#daycare').prop('disabled', true)
                    }
                    else if (op_val == 4) {
                        $('#diagnostics').prop('checked', true)
                        $('#diagnostics').val($('#op_daycare_val').val())

                        $('#ip').prop('disabled', true)
                        $('#op').prop('disabled', true)
                        $('#home_care').prop('disabled', true)
                        $('#daycare').prop('disabled', true)
                        $('#emergency_reg').prop('disabled', true)
                    }
                    else {
                        console.log(op_val)
                    }
                }
            }
        }
    });
}
//Only for OP claim will appear
function visit_change(id) {
    debugger;
    var val = id
    if ($('#hclaimstatus').val() == 0 && $('#hclaimvisit').val() == 28) {
        $('#divClaim').hide()
       
    }
    else {
        if (val == 1) {
            $('#divClaim').show();
            $('#divSelOpdDropdown').show();
            LoadOpdnumber();
        }
        else {
            $('#divClaim').hide();
            $('#divReferredDoctor').hide();
            $('#divSelOpdDropdown').show();
            LoadOpdnumber();
            $("#Entity_no").click();
        }
    }

    if (val == 11) {  //added by nandhini
        $('#divHealthCareUsers').show();
        $('#divSelDoctorDropdown').hide();
        

        //check any technition schedule for audiologists exists
        var OTBdata = {
            P_Dml_Indicator: "SCP",
            branch_id: $('#pkg_branch_id').val(),
            Patient_Name: $('#hdnpatientapp').val()
        }
        debugger;
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Calender/OTCreation',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(OTBdata),
            success: function (data) {
                debugger;
                var data = JSON.parse(data);
                debugger;
                if (data.msg == "Success") {
                    var data1 = data.data;

                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var b = data1.Table;
                        if (b.length > 0) {
                            $('#SelAudiologist').val(b[0].DMO);
                        }
                    }
                }
            }
        });
    }
    else {
        $('#divHealthCareUsers').hide();
        $('#divSelDoctorDropdown').show();
        $('#SelAudiologist').val('');
    }
    if (val == 11) {
        $('#divReferredDoctor').show();

        var DoctorData = {
            Dml_Indicator: "HDL",
            hospital_id: $('#HospitalId').val(),
            branch_id: $('#SelBranch').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CalendarConfiguration/HosiptalSelect',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                //$('#directappointment').modal('toggle');
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        var tr = '';
                        var SelRole = '';
                        $('#SelReferredDoctor').empty();
                        debugger;
                        var default_opt = '<option value="0">--Select--</option>';
                        var j = 0;
                        if (data1.length > 0) {
                            for (var i = 0; i < data1.length; i++) {
                                j++;

                                SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';

                            }
                            $('#SelReferredDoctor').append(default_opt + SelRole);

                            if ($('#hiddenRole_id').val() == 1) {
                                $('#SelReferredDoctor').val($('#HiddenDoctorID').val());
                                $('#SelReferredDoctor').attr('disabled', true);
                            }
                            
                        }
                    }
                    else {
                        console.log(data);
                    }

                }
            }
        });
    }  }


//User collect amount onchange
$('#txt_user_collect').change(function () {
    var bal_amt = $('#txt_received_amt').val()
    var collect_amt = $('#txt_user_collect').val()
    if (parseFloat(collect_amt) > parseFloat(bal_amt)) {
        $('#txt_user_refund').val(parseFloat(collect_amt) - parseFloat(bal_amt))
    }
    else if (parseFloat(collect_amt) < parseFloat(bal_amt)) {
        $('#Ptxt_user_collect').show();
        $('#Ptxt_user_collect').fadeOut(8000);
        $('#Ptxt_user_collect').html('Please enter the amount greater than received amount');
        $('#txt_user_collect').focus();
        $('#txt_user_collect').val('');
        $('#txt_user_refund').val('');
        return false;
    }
    else {
        $('#txt_user_refund').val(0)
    }
})
//Bill Row Colour
function bill_row_colour(id) {
    var color = ''
    if (id == 1) {
        color = 'bill-input'
    }
    else if (id == 2) {
        color = 'bill-fixed'
    }
    else if (id == 3) {
        color = 'bill-range'
    }
    else if (id == 4) {
        color = 'bill-hourly'
    }
    else if (id == 5) {
        color = 'bill-daywise'
    }
    return color
}
//Final amount onchange in claim
$('#is_final').on('change', function () {
    this.value = this.checked ? 1 : 2;

}).change();

function Hideshow() {
    debugger;
    var show = {
        dml_indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(show),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            $('#hclaimstatus').empty();
            $('#hclaimvisit').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;
                var claimvisit = data.data.Table[27].master_vist_type_id;
                var claimstatus = data.data.Table[27].status;
                $('#hclaimstatus').val(claimstatus);
                $('#hclaimvisit').val(claimvisit);               
                if ($('#hclaimstatus').val() == 0 && $('#hclaimvisit').val() == 28) {
                    debugger;
                    $('#advance_amount_div').hide();

                }

            }
        }
    });
}
//Search AutoComplete in Service List Table
$('#srch_service').keyup(function () {
    debugger;
    SearchFilteration();
 
})
//Bind the filtered Service Table List
function SearchBind(data) {
    $('#service_tbl tbody').empty()
    if (data.length > 0) {
       
        $.each(data, function (i, item) {
            var tr = '<tr id="tr_' + item.rowCount + '" class="' + bill_row_colour(item.base_amount_type) + '" ><td>' + item.service_name + '</td><td>' + item.quantity + '</td><td>' + parseFloat(item.Rate).toFixed(2) + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat(item.base_amount_value) + ')</span></td>'
            tr += '<td>' + parseFloat(item.TotalAmt).toFixed(2) + '</td><td>' + +item.discount + ' ' + item.sel_discount_type + '</td><td>' + parseFloat(item.discount_amount).toFixed(2) + '</td><td>' + item.tax_percentage + '%</td><td>' + parseFloat(item.tot_net_amt).toFixed(2) + '</td><td>' + item.ser_date + '</td><td>' + item.doc_name + '</td><td>' + item.remarks + '</td><td class="hide">' + item.doctor_id + '</td><td class="hide">' + item.master_service_id + '</td><td class="hide">' + item.package_id + '</td><td class="hide">' + item.price_matrix_id + '</td><td class="hide">' + item.request_id + '</td><td class="hide">' + item.request_details_id + '</td><td class="hide">' + item.base_amount_type + '</td><td class="hide">' + item.range_min + '</td><td class="hide">' + item.range_max + '</td><td class="hide">' + item.billing_details_id + '</td><td class="hide">' + parseFloat(item.tax_amount).toFixed(2) + '</td><td class="hide">' + item.charge_percentage + '</td><td class="hide">' + parseFloat(item.base_amount_value) + '</td><td class="hide">' + item.is_workorder + '</td><td class="hide">' + item.is_doctor + '</td><td class="hide">' + item.is_description + '</td><td class="hide">' + item.CRMService + '</td><td class="hide">' + item.PharmacyBillNo + '</td>'
            tr += '<td>'+item.editDelete+' </td></tr>';
            $('#service_tbl tbody').append(tr);
        })
    }
    return true;
}
//for restoring Orginal Service Table when other actions are performed(Edit/Submit/Payment Add/Discount Add/Delete/Claim)
function CheckFilter() {
    debugger;
    if ($('#srch_service').val() || $('#srch_type').val()!=0) {
        $('#srch_service').val('');
        $('#srch_type').val(0)
        var bill = SearchBind(Service_Org_Arr);
        $.when(bill)
    .then(function (data) {
        return true;
    })
    }
    else {
        return true;
    }
}
//Search Type-2 based on Investigation(workorder service) and Normal Service
$('#srch_type').change(function () {
    debugger;
    SearchFilteration()
   
})

function SearchFilteration()
{
    var filteredArr = [];
    if (Service_Org_Arr.length > 0) {
        var fillType = '', fillType1 = '';
        if ($('#srch_service').val()) {
            fillType = 'item.service_name.toUpperCase().includes($("#srch_service").val().toUpperCase())'
        }
        if ($('#srch_type').val() == 1) {
            fillType1 = 'item.is_workorder == 1'

        }
        else if ($('#srch_type').val() == 2) {
            fillType1 = 'item.is_workorder != 1'
        }
        else {
            fillType1 = '';

        }
        filteredArr = Service_Org_Arr.filter((item) =>(fillType1 != '' ? eval(fillType1) : true) && (fillType != '' ? eval(fillType) : true));

        SearchBind(filteredArr);
    }
}
//Doctor Autocomplete
$('#SelDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HUL", branch_id: $('#pkg_branch_id').val() },   //altered by nandhini changed HDL indicator to HUL for listing all users (dhanwanthralaya req) on 09/10/2024
            success: function (data) {
                debugger;
                $('#HdnSelDoctor').val('');
                $('#HdnSelDoctor_userid').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid ,user_id: item.doctor_user_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HdnSelDoctor').val(ui.item.id);
        $('#HdnSelDoctor_userid').val(ui.item.user_id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
$('.txt_doctor_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#pkg_branch_id').val() },
            success: function (data) {
                debugger;
                $('#Htxt_doctor_name').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Htxt_doctor_name').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
//Convert To Bill From Estimate Concept
function LoadEstimateDetails() {
    var serviceData = {
        estimation_no: $('#HEstimateId').val(),
        dml_indicator: 'EL'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Estimation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(serviceData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    console.log(data1);
                    debugger;
                    var total_tax = 0.0;
                    if (data1.Table.length > 0) {
                        //$('.pat-stripe-bgop').show();
                        var patient_id = data1.Table[0].patient_id;
                        $('#hndbranch').val(data1.Table[0].branchid);
                       // $('#hdnvisit_report_id').val(data1.Table[0].branchid)
                        //if (data1.Table[0].visit_reportid == 0) {

                        //}
                        //else {
                          
                        //    var bill = PatientSearch(patient_id, data1.Table[0].is_ip, $('#hndbranch').val(), $('#hdnvisit_report_id').val());
                        //    $.when(bill)
                        //.then(function (data3) {
                        //    var da1 = JSON.parse(data3);
                        //    if (da1.msg == "Success") {
                        //        console.log(data1);
                        //        da1 = da1.data;
                        //        $('#hdn_is_discount').val(da1[0].is_discount_authorization)
                        //        $('#hdn_entity').val(da1[0].entity_id);
                        //        $('#hdn_is_scheme').val(da1[0].is_scheme);
                        //    }

                        //});
                        //}
                       
                        $('#pkg_branch_id').val($('#hndbranch').val()).attr("disabled", true);
                        $('#txtPaitentSearch_bill').val(data1.Table[0].PatientName).attr("disabled", true);
                        $('#hdnpatientapp').val(data1.Table[0].patient_id);
                        //$('.pat-stripe-bgop').show();

                        $('#hndbilling_class').val(data1.Table[0].billing_class);
                        $('#hndward_id').val(data1.Table[0].ward_id);
                       
                        //$('#hndward_id').val(data1.Table[0].is_ip);
                       
                        
                        $("input[name='optradio'][value='" + data1.Table[0].is_ip + "']").prop('checked', true);
                        $('.clsEst').addClass('disabled');
                        $('#HdnEntityid').val(data1.Table[0].insurance_id);
                        $('#EntityType').val(data1.Table[0].is_insurance);
                        $('#Entity').val(data1.Table[0].is_entity);
                       
                       
                        if ($('#Entity').val() == 1) {
                            $("#Entity_yes").click();
                            if ($('#EntityType').val() == 1) {
                                $('#EntityType_Insurance').click();
                                Corporate_Insurance($('#HdnEntityid').val(), data1.Table[0].Corporate_Insuranceid);
                            }
                            else {
                                $('#EntityType_Corporate').click()
                            }
                            $('#CMultiPay').val(data1.Table[0].is_MultiPay);
                            if ($('#CMultiPay').val() == 1) {
                                $('#CMultiPay').prop('checked', true);
                                $('#CMultiPay').change()
                            }
                        }
                        else {
                            $("#Entity_no").click();
                        }
                       
                       
                       
                       
                        $('#His_insurance').val(data1.Table[0].is_entity);
                        $('#ddInsuranceName').val(data1.Table[0].insurance_name);
                        var bill = LoadVisitType('', data1.Table[0].is_ip);
                        $.when(bill)
                        .then(function (data3) {
                            if (data1.Table[0].visit_reportid != 0) {
                                $('#SelDoctor').val(data1.Table[0].DoctorName).attr('disabled', true);
                                $('#HdnSelDoctor').val(data1.Table[0].reqdoctor_id)
                                $('#hdnvisit_report_id').val(data1.Table[0].visit_report_id)
                             
                                VisitReport_Creation()
                            }

                        });
                      
                        var netamount = 0;
                        for (var i = 0; i < data1.Table.length; i++) {
                           
                            if (data1.Table[i].charge_percentage == '0') {
                                netamount += data1.Table[i].total_amount;
                            }

                            var rowCount = $('#service_tbl tbody tr').length;
                            if (rowCount == 0) {
                                rowCount = 1
                            }
                            else {
                                var id = $('#service_tbl tbody tr:last').attr('id');
                                id = id.split('_');
                                rowCount = parseInt(id[1]) + (1);
                            }

                            var sel_discount_type = $('.sel_discount_type').val();
                            if (sel_discount_type == 1) {
                                sel_discount_type = '₹';
                            }
                            else {
                                sel_discount_type = '%';
                            }
                            var tax_amount = 0.0;
                            if (data1.Table[i].is_tax == 1 && data1.Table[i].charge_percentage == '0') {
                                tax_amount = (parseFloat(data1.Table[i].total_amount)) * (parseFloat(data1.Table[i].tax_percentage) / 100);
                            }
                            total_tax = total_tax + parseFloat(tax_amount);

                            var date_time
                            if (data1.Table[i].base_amount_type == 4)
                                date_time = data1.Table[i].service_date + " " + data1.Table[i].service_time + " - " + data1.Table[i].service_end_date + " " + data1.Table[i].service_end_time;
                            else
                                date_time = data1.Table[i].service_date + " " + data1.Table[i].service_time
                            var Rate = parseFloat(data1.Table[i].base_amount).toFixed(2) + '<br/><span class="base_txt_class">(Actual Amt: ' + parseFloat(data1.Table[i].base_amount) + ')</span>';

                            var tr = '<tr  id="tr_' + rowCount + '" tabindex=' + (rowCount - 1) + ' class="del_chk ' + bill_row_colour(data1.Table[i].base_amount_type) + '"><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].quantity + '</td><td>' + Rate + '</td>'
                            tr += '<td>' + parseFloat(data1.Table[i].total_amount).toFixed(2) + '</td><td>0' + ' ' + '₹</td><td>0</td><td>' + data1.Table[i].tax_percentage + '%</td><td>' + parseFloat(parseFloat(tax_amount) + parseFloat(data1.Table[i].total_amount)).toFixed(2) + '</td><td>' + date_time + '</td><td>' + data1.Table[i].first_name + '</td><td>' + ((data1.Table[i].remarks == null) ? '' : data1.Table[i].remarks) + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td><td class="hide">' + data1.Table[i].request_details_id + '</td><td class="hide">' + data1.Table[i].base_amount_type + '</td><td class="hide">' + data1.Table[i].range_min + '</td><td class="hide">' + data1.Table[i].range_max + '</td><td class="hide">0</td><td class="hide">' + parseFloat(tax_amount).toFixed(2) + '</td><td class="hide">' + data1.Table[i].charge_percentage + '</td><td class="hide">' + parseFloat(data1.Table[i].base_amount) + '</td><td class="hide">' + data1.Table[i].is_workorder + '</td><td class="hide">' + data1.Table[i].is_doctor + '</td><td class="hide">' + data1.Table[i].is_description + '</td><td class="hide">' + data1.Table[i].CRMService + '</td><td class="hide">' + data1.Table[i].PharmacyBillNo + '</td><td class="hide">' + data1.Table[i].estimation_details_id + '</td><td class="hide">' + $('#HEstimateId').val() + '</td>'
                            //tr += '<td></td><td>' + data1.Table[i].total_amount + '</td><td></td><td>' + data1.Table[i].first_name + '</td><td class="hide">' + data1.Table[i].doctor_id + '</td><td class="hide">' + data1.Table[i].master_service_id + '</td><td class="hide">' + data1.Table[i].package_id + '</td><td class="hide">' + data1.Table[i].price_matrix_id + '</td><td class="hide">' + data1.Table[i].request_id + '</td>'
                            tr += '<td><span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
                            $('#service_tbl tbody').append(tr);
                            var ObjArr = {
                                rowCount: rowCount,
                                id: 'tr_' + rowCount,
                                base_amount_type: data1.Table[i].base_amount_type,
                                service_name: data1.Table[i].service_name,
                                quantity: data1.Table[i].quantity,
                                Rate: data1.Table[i].base_amount,
                                base_amount_value: data1.Table[i].base_amount,
                                TotalAmt: data1.Table[i].total_amount,
                                discount: 0,
                                sel_discount_type: 0,
                                discount_amount: 0,
                                tax_percentage: data1.Table[i].tax_percentage,
                                tax_amount: tax_amount,
                                tot_net_amt: parseFloat(parseFloat(tax_amount) + parseFloat(data1.Table[i].total_amount)),
                                ser_date: date_time,
                                doc_name: data1.Table[i].first_name,
                                remarks: (data1.Table[i].remarks == null) ? '-' : data1.Table[i].remarks,
                                doctor_id: data1.Table[i].doctor_id,
                                master_service_id: data1.Table[i].master_service_id,
                                package_id: data1.Table[i].package_id,
                                price_matrix_id: data1.Table[i].price_matrix_id,
                                request_id: data1.Table[i].request_id,
                                request_details_id: data1.Table[i].request_details_id,
                                range_min: data1.Table[i].range_min,
                                range_max: data1.Table[i].range_max,
                                billing_details_id: 0,
                                charge_percentage: data1.Table[i].charge_percentage,
                                is_workorder: data1.Table[i].is_workorder,
                                is_doctor: data1.Table[i].is_doctor,
                                is_description: data1.Table[i].is_description,
                                CRMservice: data1.Table[i].CRMService,
                                PharmacyBillNo: data1.Table[i].PharmacyBillNo,
                                estimation_details_id: data1.Table[i].estimation_details_id,
                                estimation_no:$('#HEstimateId').val(),
                                editDelete: '<span class="btn btn-xs mr-10 btn-edit service_edit" onclick=ServiceEdit("tr_' + rowCount + '")><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick=service_delete("tr_' + rowCount + '")><i class="fa fa-trash-o" aria-hidden="true"></i></span>'

                            }
                            Service_Org_Arr.push(ObjArr);
                            //- LoadDoctor();
                            authorized_person();
                            //LoadPayment_Type();
                        }
                        LoadPayment_Type(); //changed by tharuni because inside the loop LoadPayment_Type called
                        $('#net_amount').html((parseFloat(parseFloat(netamount) + parseFloat(total_tax)).toFixed(2)));
                        $('#total_net_amount').html(Math.round((netamount + total_tax)).toFixed(2));
                        $('#advance_amount').html(Math.round((data1.Table[0].advance_amount)).toFixed(2));
                        $('#total_tax_amount').html((total_tax));
                        footer_binding_calc();
                        if (data1.Table[0].advance_amount > netamount) {


                            //$('#collect_payment').html((netamount+total_tax).toFixed(2));
                            $('#balance_amount').html(parseFloat(0).toFixed(2));
                            $('#sms_payment,#txt_received_amt').val(0);
                            $('#refund_amount').html(Math.round((data1.Table[0].advance_amount - (netamount + total_tax))).toFixed(2));

                        }
                        else {


                            $('#balance_amount').html(Math.round(parseFloat(netamount) + parseFloat(total_tax) - parseFloat(data1.Table[0].advance_amount)).toFixed(2));
                            $('#txt_received_amt').val(Math.round((netamount + total_tax - data1.Table[0].advance_amount).toFixed(2)));
                            $('#sms_payment').val(Math.round((netamount - data1.Table[0].advance_amount + total_tax).toFixed(2)));
                            $('#refund_amount').html(parseFloat(0).toFixed(2));

                        }
                        //if (data1.Table[0].is_ip == 2) {
                        automated_charge_cal(0)
                        //}

                    }
                    

                    $('#shade_slot').hide();
                    $('#btn_submit').attr('disabled', false);
                }
                else {
                }
            }

        }
    });
}



function LoadUsersList() {
   
    var DoctorData = {
        Dml_Indicator: "UL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelAudiologist').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_user_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#SelAudiologist').html(default_opt + SelRole);
                    }

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

