$(document).ready(function () {
    LoadPatientList();
 
});

function LoadPatientList() {
    var pateintdata = {       
        Dml_Indicator: "S"   
    }

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

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

                    if (data1.Table.length > 0) {
                        var tr = "";
                        $('#tblPatientList_Body').empty();
                        for (var i = 0; i < data1.Table.length; i++) {
                            var gender = (data1.Table[i].gender == "0" || data1.Table[i].gender == null || data1.Table[i].gender == "") ? "-" : data1.Table[i].gender == "1" ? "Male" : "Female";
                            tr = tr + "<tr><td>" + (i + 1) + "</td><td>" + data1.Table[i].patient_id + "</td><td>" + data1.Table[i].first_name + "</td><td>" + data1.Table[i].age + "/" + gender + "</td><td>" + data1.Table[i].phone_number_1 + "</td><td>" + data1.Table[i].total_ip_visits + "</td><td>" + data1.Table[i].last_admitted_date + "</td><td>" + data1.Table[i].last_discharged_time + "</td><td><button class='btn btn-primary 104' onclick=ViewPatientAllVisits('" + data1.Table[i].patient_id + "');>View</button></td></tr>";
                        }

                        $('#tblPatientList_Body').append(tr);

                        $('#tblPatientList').DataTable({
                            "lengthChange": false,
                            "info": false,
                            "paging": true,
                            "ordering": false
                        });
                        check_priviliges();
                    }

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


function ViewPatientAllVisits(patient_id) {
    var pateintdata = {
        Dml_Indicator: "VS",
        patient_id: patient_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPVisitPatientDetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    document.getElementById("billingoverlay").style.display = "block";
                    if (data1.Table.length > 0) {
                        var tr = "";
                        $('#tblpatientvisitlist tbody').empty();
                        for (var i = 0; i < data1.Table.length; i++) {

                            tr = tr + '<tr class="selectedRow" onclick=\'ShowVisitDetails(\"' + data1.Table[i].ip_patient_id + '\",\"' + data1.Table[i].ip_visit_report_id + '\",\"' + data1.Table[i].is_insurance + '\",\"' + data1.Table[i].is_pending + '\",\"' + data1.Table[i].is_final_bill_generated + '\")\';><td><a href="#" onclick=\'ShowVisitDetails(\"' + data1.Table[i].ip_patient_id + '\",\"' + data1.Table[i].ip_visit_report_id + '\",\"' + data1.Table[i].is_insurance + '\",\"' + data1.Table[i].is_pending + '\",\"' + data1.Table[i].is_final_bill_generated + '\")\';>' + data1.Table[i].ip_visit_report_id + '</a></td><td>' + data1.Table[i].admission_date + '</td><td><span id="billAmount_' + data1.Table[i].ip_visit_report_id + '">' + data1.Table[i].total_bill_amount + '</span></td></tr>';
                        }


                        $('#tblpatientvisitlist tbody').append(tr);
                        $('#patientlistview').show();
                        $('#patientlist').hide();

                    }

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

    });
}

function ShowVisitDetails(patient_id, visit_report_id,is_insurance,is_pending,is_final_bill_generate) {
    debugger;
    document.getElementById("billingoverlay").style.display = "none";
    $('#txtPatientID').val(patient_id);
    $('#txtVisitReportID').val(visit_report_id);
    $('#txtPaymentVisitReportID').val(visit_report_id);
    $('#isPaymentpaid').val(is_pending);
    $('#isFinalBillGenerated').val(is_final_bill_generate);
    if (is_insurance == "1" || is_insurance == true || is_insurance=="true") {
        $('#Insurance_tab').show();
        $('#InsuranceListTab').show();
    }
    else {
        $('#Insurance_tab').hide();
        $('#InsuranceListTab').hide();
    }

    if ($('#isPaymentpaid').val() == true || $('#isPaymentpaid').val() == "true" || $('#isPaymentpaid').val() == "1") {
        $('#btnGenerateFinalBill').prop('disabled', false);
    }
    else {
        $('#btnGenerateFinalBill').prop('disabled', true);
    }
    $('#overview_tab').addClass('us-db-loader-active-inv');
    LoadPatientOverview();
    
   
}

function LoadPatientOverview() {
    var pateintdata = {
        Dml_Indicator: "SVL",
        visit_report_id: $('#txtVisitReportID').val(),
        patient_id: $('#txtPatientID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPVisitPatientDetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if (data1.Table.length > 0) {
                        $('#lblName').html(data1.Table[0].first_name);
                        var gender = (data1.Table[0].gender == "0" || data1.Table[0].gender == null || data1.Table[0].gender == "") ? "-" : data1.Table[0].gender == "1" ? "Male" : "Female";
                        $('#lblAge').html(data1.Table[0].age + " / " + gender);
                        $('#lblVisitReportID').html(data1.Table[0].ip_visit_report_id);
                        $('#lblDOA').html(data1.Table[0].admitted_date);
                        $('#lblDOD').html(data1.Table[0].ip_discharge_time);
                        var pending = data1.Table[0].is_pending == "0" ? "Pending" : "Paid";
                        $('#lblPaymentStatus').html(pending);
                        $('#lblOperationName').html(data1.Table[0].ip_surgery_type);
                    }

                    if (data1.Table1.length > 0) {
                        var tr = "";
                        $('#tblTransferOrder').empty();
                        tr = $('<table id="example1" class="table table-striped" />');

                        tr.append("<thead class='table-bg'><tr><th>From</th><th>Transfer To</th><th>Transfer Date Time</th><th>Bed No</th><th>Reason</th><th>Time Spend</th><th>Transfered by</th></tr></thead><tbody>");

                        $.each(data1.Table1, function (i, emp) {

                            row_data = "<tr><td>" + emp.ip_From + "</td><td>" + emp.ip_to + "</td><td>" + emp.transfer_date_time + "</td><td>" + emp.bed_id + "</td><td>" + emp.ip_reason + "</td><td>" + emp.timespend + "</td><td>" + emp.created_by + "</td></tr>";
                            tr.append(row_data);
                        });
                        tr.append("</tbody></table>");
                        $('#tblTransferOrder').html(tr);
                    }
                    else {
                        $('#tblTransferOrder').empty();
                    }

                    if (data1.Table2.length > 0) {
                        $('#tblActiveInvoice tbody').empty();
                        var tr = "";
                        for (var i = 0; i < data1.Table2.length; i++) {

                            tr = tr + '<tr><td>' + data1.Table2[i].invoice_id + '</td><td>' + data1.Table2[i].invoice_date + '</td><td>' + data1.Table2[i].invoice_description + '</td><td>' + data1.Table2[i].invoice_amount + '</td><td><a class="delete btn btn-default  btn-sm" href="javascript:void(0);" onclick=Delete_Active_invoice(\"' + data1.Table2[i].invoice_id + '\",\"' + data1.Table2[i].lab_order_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';

                        }


                        $('#tblActiveInvoice tbody').append(tr);
                        //$('#activeInvoice_body').append(tr);

                    }
                    else {
                        $('#tblActiveInvoice tbody').empty();
                    }

                    if (data1.Table3.length > 0) {
                        var tr = "";
                        $('#tblClosedInvoice tbody').empty();
                        for (var i = 0; i < data1.Table3.length; i++) {
                            var payment_type = '';
                            if (data1.Table3[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data1.Table3[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data1.Table3[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else if (data1.Table3[i].payment_type == 4) {
                                payment_type = 'Insurance';
                            }
                            else {
                                payment_type = '';
                            }

                            tr = tr + '<tr><td>' + data1.Table3[i].invoice_id + '</td><td>' + data1.Table3[i].invoice_date + '</td><td>' + data1.Table3[i].invoice_description + '</td><td>' + data1.Table3[i].invoice_amount + '</td></tr>';

                        }

                        $('#tblClosedInvoice tbody').html(tr);
                    }
                    else {
                        $('#tblClosedInvoice tbody').empty();
                    }

                    if (data1.Table4.length > 0) {
                        $('lblInsuranceCompanyName').html(data1.Table4[0].company_name);
                        $('lblInsuranceNo').html(data1.Table4[0].insurance_no);
                        $('lblInsuranceType').html(data1.Table4[0].insurance_type);
                        $('InsuranceExpiryDate').html(data1.Table4[0].insurance_expiry_date);
                    }

                    LoadIPPayments();

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

            $('#overview_tab').removeClass('us-db-loader-active-inv');
        }

    });
}

function LoadIPPayments() {
    var pateintdata = {
        Dml_Indicator: "S",
        visit_report_id: $('#txtVisitReportID').val()       
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPPayment_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            $('#tblHistoryPayments tbody').empty();
            $('#tblInsurancePaymentList tbody').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {
                
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    $('#tblHistoryPayments tbody').empty();
                    $('#tblInsurancePaymentList tbody').empty();
                    if (data1.Table.length > 0) {
                        var tr = ""; var is_pending = ""; var is_final_bill_generate = "";
                        for (var i = 0; i < data1.Table.length; i++) {

                            is_pending = data1.Table[i].is_pending;
                            is_final_bill_generate = data1.Table[i].is_final_bill_generated;

                            var payment_type = '';
                            if (data1.Table[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data1.Table[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data1.Table[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else if (data1.Table[i].payment_type == 4) {
                                payment_type = 'Insurance';
                            }
                            else {
                                payment_type = '';
                            }

                            var bill_type = "";
                            if (data1.Table[i].type == 1) {
                                bill_type = "IP Advance";
                            }
                            else if (data1.Table[i].type == 2) {
                                bill_type = "Final Bill";
                            }
                            else if (data1.Table[i].type == 3) {
                                bill_type = "Refund";
                            }
                            else {
                            }

                            tr = tr + '<tr><td>' + data1.Table[i].payment_id + '</td><td>' + data1.Table[i].bill_date + '</td><td>' + bill_type + '</td><td>' + payment_type + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].discount + '</td><td>' + data1.Table[i].payment_amount + '</td><td><a class="delete btn btn-default  btn-sm" href="javascript: void(0);" onclick=DeletePayment(\"' + data1.Table[i].payment_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';
                        }

                        $('#tblHistoryPayments tbody').append(tr);

                        $('#isPaymentpaid').val(is_pending);
                        $('#isFinalBillGenerated').val(is_final_bill_generate);

                        if ($('#isPaymentpaid').val() == true || $('#isPaymentpaid').val() == "true" || $('#isPaymentpaid').val() == "1") {
                            $('#btnGenerateFinalBill').prop('disabled', false);
                        }
                        else {
                            $('#btnGenerateFinalBill').prop('disabled', true);
                        }
                    }
                    else {
                        $('#tblHistoryPayments tbody').empty();
                    }


                    if (data1.Table1.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data1.Table1.length; i++) {

                            var payment_type = '';
                            if (data1.Table1[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data1.Table1[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data1.Table1[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else if (data1.Table1[i].payment_type == 4) {
                                payment_type = 'Insurance';
                            }
                            else {
                                payment_type = '';
                            }

                            tr = tr + '<tr><td>' + data1.Table1[i].payment_id + '</td><td>' + data1.Table1[i].bill_date + '</td><td>' + data1.Table[i].type + '</td><td>' + payment_type + '</td><td>' + data1.Table1[i].total_amount + '</td><td>' + data1.Table1[i].discount + '</td><td>' + data1.Table1[i].payment_amount + '</td><td><button class="btn btn-primary">Claim Insurance</button></td></tr>';
                        }

                        $('#tblInsurancePaymentList tbody').append(tr);
                    }
                    else {
                        $('#tblInsurancePaymentList tbody').empty();
                    }

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

function Delete_Active_invoice(invoice_id, lab_id) {
    var r = confirm("Are You sure You want delete the Invoice: " + invoice_id + "");
    if (r == true) {
        var InvoiceId = {
            Dml_Indicator: 'IPD',
            invoice_id: invoice_id,
            Patient_id: $('#txtPatientID').val(),
            visit_report_id: $('#txtVisitReportID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/invoice_payment',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(InvoiceId),
            success: function (data) {

                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                    toastr.warning("Something went wrong. Try again later.");
                }
                else {

                    if (data2.msg == "Success") {
                        
                        var data = JSON.parse(data);
                        if (data.length > 0) {
                            var data = data2.data;
                            if (data[0].StringMsg == 'Success') {
                                debugger;
                                $('#tblActiveInvoice tbody').empty();
                                var tr = "";
                                var totalSumAmount = 0;
                                for (var i = 0; i < data.length; i++) {
                                    totalSumAmount = parseFloat(totalSumAmount) + parseFloat(data[i].invoice_amount);
                                    tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td><a class="delete btn btn-default  btn-sm" href="javascript:void(0);" onclick=Delete_Active_invoice(\"' + data[i].invoice_id + '\",\"' + data[i].lab_order_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';

                                }

                                $('#tblActiveInvoice tbody').append(tr);

                                $("#tblpatientvisitlist_body tr").each(function () {
                                    $(this).find("#billAmount_" + $('#txtVisitReportID').val()).html(totalSumAmount.toFixed(2));
                                });
                            }
                            else if (data[0].StringMsg == 'Cannot able to delete') {
                                toastr.warning('Payment Received - Unable to Delete Invoice');
                            }

                        }

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

            }
        });
    }
}


$('#btnAddInvoice').click(function () {
    var InvoiceDate = $('#InvoiceDate').val();
    var InvoiceName = $('#InvoiceName').val();
    var InvoiceAmount = $('#InvoiceAmount').val();
    if ($.trim(InvoiceDate) == '') {
        $('#PInvoiceDate').show();
        $('#PInvoiceDate').fadeOut(8000);
        $('#PInvoiceDate').html('Select the invoice date');
        $('#InvoiceDate').focus();
        $('#InvoiceDate').val('');
        return false;
    }
    if ($.trim(InvoiceName) == '') {
        $('#PInvoiceName').show();
        $('#PInvoiceName').fadeOut(8000);
        $('#PInvoiceName').html('Enter the invoice name');
        $('#InvoiceName').focus();
        $('#InvoiceName').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the invoice amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '0') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the valid amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    var InvoiceDates = InvoiceDate.split('/');
    InvoiceDate = InvoiceDates[2] + "-" + InvoiceDates[1] + "-" + InvoiceDates[0];
    var invoice = {
        Patient_id: $('#txtPatientID').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        invoice_description: $('#InvoiceName').val(),
        invoice_date: InvoiceDate,
        invoice_amount: $('#InvoiceAmount').val(),
        invoice_status: 1,
        balance_amount: $('#InvoiceAmount').val(),
        Dml_Indicator: 'IPI',
        visit_report_id: $('#txtVisitReportID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {

                if (data2.msg == "Success") {
                  
                    var data1 = JSON.parse(data);
                    if (data1.length > 0) {
                        debugger;
                        var data1 = data2.data;
                        $('#tblActiveInvoice tbody').empty();
                        var tr = "";
                        var totalSumAmount = 0;
                        for (var i = 0; i < data1.length; i++) {
                            totalSumAmount = parseFloat(totalSumAmount) + parseFloat(data1[i].invoice_amount);
                            tr = tr + '<tr><td>' + data1[i].invoice_id + '</td><td>' + data1[i].invoice_date + '</td><td>' + data1[i].invoice_description + '</td><td>' + data1[i].invoice_amount + '</td><td><a class="delete btn btn-default  btn-sm" href="javascript:void(0);" onclick=Delete_Active_invoice(\"' + data1[i].invoice_id + '\",\"' + data1[i].lab_order_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';

                        }

                        $('#tblActiveInvoice tbody').append(tr);

                        $("#tblpatientvisitlist_body tr").each(function () {
                            $(this).find("#billAmount_" + $('#txtVisitReportID').val()).html(totalSumAmount.toFixed(2));
                        });
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('#InvoiceDate').val('');
            $('#InvoiceName').val('');
            $('#InvoiceAmount').val('');
           
        }
    });
});



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

    if ($.trim($('#PaymentDate').val()) == '') {
        $('#PPaymentDate').show();
        $('#PPaymentDate').fadeOut(8000);
        $('#PPaymentDate').html('Select the payment date');
        $('#PaymentDate').focus();
        $('#PaymentDate').val('');
        return false;
    }

    if ($.trim($('#selIPType').val()) == '' || $('#selIPType').val()==0) {
        $('#PselIPType').show();
        $('#PselIPType').fadeOut(8000);
        $('#PselIPType').html('Select the Type');
        $('#selIPType').focus();
        $('#selIPType').val('');
        return false;
    }

    if ($.trim($('#selIPPaymentType').val()) == '' || $('#selIPPaymentType').val() == 0) {
        $('#PselIPPaymentType').show();
        $('#PselIPPaymentType').fadeOut(8000);
        $('#PselIPPaymentType').html('Select the payment type');
        $('#selIPPaymentType').focus();
        $('#selIPPaymentType').val('');
        return false;
    }

    if ($.trim($('#txtTotalPayAmount').val()) == '') {
        $('#PtxtTotalPayAmount').show();
        $('#PtxtTotalPayAmount').fadeOut(8000);
        $('#PtxtTotalPayAmount').html('Enter total amount');
        $('#txtTotalPayAmount').focus();
        $('#txtTotalPayAmount').val('');
        return false;
    }

    if ($.trim($('#txtActualPayAmount').val()) == '') {
        $('#PtxtActualPayAmount').show();
        $('#PtxtActualPayAmount').fadeOut(8000);
        $('#PtxtActualPayAmount').html('Enter amount');
        $('#txtActualPayAmount').focus();
        $('#txtActualPayAmount').val('');
        return false;
    }


    var pateintdata = {
        Dml_Indicator: "I",
        visit_report_id: $('#txtVisitReportID').val(),
        patient_id: $('#txtPatientID').val(),
        type: $('#selIPType').val(),
        payment_type: $('#selIPPaymentType').val(),
        total_amount: $('#txtTotalPayAmount').val(),
        discount: $('#txtDiscount').val(),
        payment_amount: $('#txtActualPayAmount').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPPayment_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {

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

                    toastr.success("Payment added successfully");
                    $('#selIPType').val('');
                    $('#selIPPaymentType').val('');
                    $('#txtTotalPayAmount').val('');
                    $('#txtDiscount').val('');
                    $('#txtActualPayAmount').val('');
                    $('#PaymentDate').val('');
                    LoadIPPayments();

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

});


function DeletePayment(payment_id) {

    if ($('#isFinalBillGenerated').val() == true || $('#isFinalBillGenerated').val() == "true" || $('#isFinalBillGenerated').val() == "1") {
        toastr.warning("Final bill Generated already. Unable to Delete Payment");
        return false;
    }
    var pateintdata = {
        Dml_Indicator: "D",
        payment_id: payment_id       
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPPayment_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    toastr.success("Deleted successfully");
                    LoadIPPayments();

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


$('#txtTotalPayAmount').on('input',function () {
    var totalAmount = $('#txtTotalPayAmount').val();
    var discountPercentage = $('#txtDiscountPercentage').val();
    if (discountPercentage != null && discountPercentage != "") {

        var discountRs = (parseFloat(discountPercentage) / 100) * (parseFloat(totalAmount));
        var actualAmount = parseFloat(totalAmount) - discountRs;

        $('#txtDiscount').val(discountRs);
        $('#txtActualPayAmount').val(actualAmount);
    }
    else {
        $('#txtActualPayAmount').val(totalAmount);
    }
});


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

    var totalAmount = $('#txtTotalPayAmount').val();
    var discountPercentage = $('#txtDiscountPercentage').val();

    if (discountPercentage == null || discountPercentage == "" || totalAmount == null || totalAmount=="") {
        return false;               
    }

    if (parseInt(discountPercentage) > 0 && parseInt(discountPercentage) < 100) {
        var discountRs = (parseFloat(discountPercentage) / 100) * (parseFloat(totalAmount));
        var actualAmount = parseFloat(totalAmount) - discountRs;

        $('#txtDiscount').val(discountRs);
        $('#txtActualPayAmount').val(actualAmount);
    }
    else {
        $('#PtxtDiscountPercentage').show();
        $('#PtxtDiscountPercentage').fadeOut(8000);
        $('#PtxtDiscountPercentage').html('Invalid discount');
        $('#txtDiscountPercentage').focus();
        $('#txtDiscountPercentage').val('');
        return false;
    }


});



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

    var pateintdata = {
        Dml_Indicator: "GI",
        visit_report_id: $('#txtVisitReportID').val(),
        patient_id: $('#txtPatientID').val()       
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPPayment_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {
                toastr.warning("Something went wrong. Try again later.");
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    window.open("/Ipmanagement/IPGenerateFinalBillPrint?visit_report_id=" + $('#txtVisitReportID').val(), "_blank");

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


$('#btnGenerateEstimatedBill').click(function () {
    window.open("/Ipmanagement/IPEstimationBillPrint?visit_report_id=" + $('#txtVisitReportID').val(), "_blank");
});