
$(document).ready(function () {
    debugger;
    //$('.Billdetails_hidden').addClass('hidden');
    if ($('#hdnbill_code').val() == "") {
        $('.pat-strip').hide();
    }
    else {
        $('.div_hdBillfield').hide();
        //PatientSearch($('#hdnPatient_id').val(), $('#hdntype').val(), $('#hdnBranch_id').val(), $('#hdnvisit_report_id').val());
        Refund_Billdetails();
        Loadrefundtype();
    }
    LoadBranch();
});

function LoadBranch() {
    debugger
    //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) {
            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="">--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) {
                        $('#refund_branch_id').append(SubDepartment);
                        $('#refund_branch_id').change();
                    }
                    else {
                        $('#refund_branch_id').append(default_opt + SubDepartment);
                    }
                    Loadrefundtype();
                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#refund_branch_id').val($('#HospitalBranchID').val());
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#refund_branch_id').val($('#HospitalBranchID').val());
                        $('#refund_branch_id').attr('disabled', true);
                    }

                    if ($('#hdnbilling_type').val() != '') {
                        $('#refund_branch_id').val($('#hdnBranch_id').val());
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
$('#refund_branch_id').change(function () {
    Loadrefundtype();
});
//$('#btnSearch_Billno').click(function () {

   
//    if ($.trim($('#refund_branch_id').val()) == '') {
//        $('#Prefund_branch_id').show();
//        $('#Prefund_branch_id').fadeOut(8000);
//        $('#Prefund_branch_id').html('Please Select Branch');
//        $('#refund_branch_id').focus();
//        $('#refund_branch_id').val('');
//        return false;
//    }

//    if ($.trim($('#txtPaitentSearch_bill').val()) == '') {
//        $('#PbtnSearch_Billno').show();
//        $('#PbtnSearch_Billno').fadeOut(8000);
//        $('#PbtnSearch_Billno').html('Enter Bill No');
//        $('#txtPaitentSearch_bill').focus();
//        $('#txtPaitentSearch_bill').val('');
//        return false;
//    }

//    if ($.trim($('#txtPaitentSearch_bill').val()) != $.trim($('#HdnRefund_code').val())) {
//        $('#PbtnSearch_Billno').show();
//        $('#PbtnSearch_Billno').fadeOut(8000);
//        $('#PbtnSearch_Billno').html('Enter valid Bill No');
//        $('#txtPaitentSearch_bill').focus();
//        //$('#txtPaitentSearch_bill').val('');
//        return false;
//    }
//    $('#btnRefundSubmit').removeClass('hidden');
//    //$('.pat-strip').show();

//    Refund_Billdetails();
//});

function Refund_Billdetails() {

    var Billcode = '',DML='';

    if ($('#hdnbill_code').val() == "") {
        Billcode = $('#hdnbillno').val();
        
    }
    else {
        Billcode = $('#hdnbill_code').val();
    }

    if ($('#hdnWO_detailsid').val() == "")
    {
        DML = 'BDL';
    }
    else
    {
        DML = 'WBDL';
    }

    var RefundTbldata = {

        Dml_Indicator: DML,
        billing_no: Billcode,
        service_id: $('#hdnserviceid').val(),
        package_id: $('#hdnpackageid').val(),
        work_order_detailsid: $('#hdnWO_detailsid').val() == "" || $('#hdnWO_detailsid').val() == null ? 0 : $('#hdnWO_detailsid').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundTbldata),
        success: function (data) {
            $('#RefundDetails').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    
                    var RefundBill_details = '';
                    var j = 0;

                    tr = $('<div class="panel-body" id="Total">');

                    if (data1.Table.length > 0)
                    {
                        $('.Billdetails_hidden').removeClass('hidden');

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

                            j++

                            condition = "ShowHideFunction(this,'" + i + "')";

                            RefundBill_details = RefundBill_details + '<div class="row billing-row-refund"><div class="col-md-12 billing-row mt20" style="width:100% !important;"><div class="col-lg-2 col-md-2 col-sm-3 col-xs-3 pr-0"><p>Service Refund Type</p><div class="disp_if"><div class="input-group bill-qty-wrap"><select  style="width:110px;" id="che_' + i + '_RDD" onchange="RefundType_change(' + i + ')"><option value="">--Select--</option><option value="1">Service Qty Refund</option><option value="2">Service Amount Refund</option></select></div>'
                            + '<div class="ml-10"><input type="checkbox" id="che_' + i + '" name="" value="1" onclick="' + condition + '"><input type="hidden" id="HBillDetailId_' + (i) + '" name="codecheck_1" value=' + emp.billing_details_id + '><label for=""></label></div></div></div>'
                            + '<div class="col-lg-2 col-md-2 col-sm-3 col-xs-3 pr-0 pl-0"><p class="billing-row-sevice-name-text">' + emp.service_name + '</p> <p class="billing-row-service-code">Code : <span>' + emp.service_code + '</span></p><p class="billing-row-service-type">Type : <span>' + emp.service_type + '</span></p></div>'
                            + '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3 pr-0 pl-0"><p class="table-heading-br">Total Qty </p><div class="input-group billing-row-sevice-rate"><p>' + emp.service_quantity + '</p></div></div>'
                            + '<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3 pr-0 pl-0"><p class="table-heading-br">Qty </p><div class="input-group">'
                            + '<input type="tel" id="txtquantity_' + i + '" name="quantity" class="form-control input-number che_' + i + '" onchange="MaxQuantity(this.value,' + emp.service_quantity + ',this.id,' + i + ',' + emp.service_amount + ',' + emp.is_workorder + ')" disabled>'
                            + '</div></div>'
                            + '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-3 pr-0"><p class="billing-row-sevice-name-text">Other Charges</p> <p class="">Discount : <span>₹ ' + emp.discount + '</span></p><p class="">Tax: <span>₹ ' + emp.service_tax_amount + '</span></p></div>'
                            //+ '<div class="col-xs-1 col-md-1"><p class="table-heading-br">Discount</p><div class="input-group billing-row-sevice-rate"><p>' + emp.discount + '</p></div></div>'
                            + '<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3 pr-0 pl-0 mb-30"><p class="table-heading-br">Unit Rate</p><div class="input-group billing-row-sevice-rate"><p><span>₹</span> ' + emp.service_quantity_amount + ' </p></div></div>'
                            + '<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3 pr-0 pl-0"><p class="table-heading-br">Total Amount</p><div class="input-group billing-row-sevice-rate"><p><span>₹</span> ' + emp.net_amount + ' </p><input type="hidden" id="TA_' + i + '" value="' + emp.net_amount + '" /></div></div>'
                            + '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-3 pr-0 pl-0"><input type="hidden" id="hdnRefundAmount_' + i + '" /><p class="table-heading-br">Refund Amount</p><div class="input-group billing-row-sevice-rate "><input type="text" class="form-control InTotal che_' + i + '" id="refundAmt_che_' + i + '" placeholder="Refund Amount" onchange="RefundAmount(this.value,' + emp.service_quantity_amount + ',' + i + ')" disabled></div></div></div></div>'
                        });
                        tr.append(RefundBill_details);
                        tr.append('</div>');

                        $('#RefundDetails').html(tr);
                    }
                    else {
                        toastr.warning('Refund is Unavailable for this bill',
                           {
                               //closeButton: false,
                               progressBar: true,
                               allowHtml: true,
                               timeOut: 0,
                           });
                        $('.Billdetails_hidden').addClass('hidden');
                    }

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

                            $('#txtPhoneNo').val(emp.phone_number);
                            $('#txtEmailId').val(emp.email_id);
                            PatientSearch(emp.patient_id, emp.visit_type, emp.branch_id, emp.visit_report_id);
                        });

                    $('#hdnCount').val(j);
                    $("#hdnbillno").val(data1.Table1[0].billing_no);
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
}

function RefundType_change(id_num)
{
    debugger;
    var refund_amount = $('#hdnRefundAmount_' + id_num).val();
    var totalrefund = $('#totalrefund').val();
    $('#che_' + id_num).prop('checked', false);
    $('.che_' + id_num).attr('disabled', true);
    $('#refundAmt_che_' + id_num).val(0);
    $('#txtquantity_' + id_num).val('');
    $('#totalrefund').val((totalrefund - refund_amount));
    $('#hdnRefundAmount_' + id_num).val('');
}

function MaxQuantity(value, Pquantity, id, no, service_amount, is_workorder) {
    debugger;
    var totalrefund = $('#totalrefund').val();
    var TQty_amount = '', total_amount = 0;

    if (is_workorder == 1) {
        debugger;
        var floatResult = checkIntegerOrDouble(value);

        if (floatResult == "Float") {

            toastr.warning('Do not allow point values for this service');

            $('#' + id).val('');
            $('#totalrefund').val(parseFloat(totalrefund) - parseFloat($('#hdnRefundAmount_' + no).val()));
            $('#refundAmt_che_' + no).val(0);
            $('#hdnRefundAmount_' + no).val(0);

            return false;
        }

    }

    if (value > Pquantity)
    {
        toastr.warning('Refund quantity is higher than pending quantity. Please check',
            {
                //closeButton: false,
                progressBar: true,
                allowHtml: true,
                timeOut: 0,
            });

        $('#' + id).val('');
        $('#totalrefund').val(parseFloat(totalrefund) - parseFloat($('#hdnRefundAmount_' + no).val()));
        $('#refundAmt_che_' + no).val(0);
        $('#hdnRefundAmount_' + no).val(0);
    }
    else if(value==0)
    {
        toastr.warning('Refund quantity is not 0 and empty',
            {
                //closeButton: false,
                progressBar: true,
                allowHtml: true,
                timeOut: 0,
            });
        $('#' + id).val('');
        $('#totalrefund').val(parseFloat(totalrefund) - parseFloat($('#hdnRefundAmount_' + no).val()));
        $('#refundAmt_che_' + no).val(0);
        $('#hdnRefundAmount_' + no).val(0);
    }
    //else if($('#' + id).val()=='')
    //{
    //    $('#totalrefund').val(parseFloat(totalrefund) - parseFloat($('#hdnRefundAmount_' + no).val()));
    //    $('#refundAmt_che_' + no).val(0);
    //    $('#hdnRefundAmount_' + no).val('');
    //}
    else
    {
        TQty_amount = (parseFloat(value) * parseFloat(service_amount));
        //total_amount = (parseFloat(totalrefund) + parseFloat(TQty_amount));
        
        $('#refundAmt_che_' + no).val(TQty_amount);
        $('#hdnRefundAmount_' + no).val(TQty_amount);

        var count = $('#hdnCount').val();


        for (var i = 0; i < count; i++) {

            debugger;
            if ($('#che_' + (i)).prop('checked') == true || parseInt($('#SRType').val()) == 2) {

                total_amount = (parseFloat(total_amount) + parseFloat($('#refundAmt_che_' + i).val()));

            }

        }

        $('#totalrefund').val(total_amount);

    }
}

//Check Int or Double
function checkIntegerOrDouble(value) {
    if (/^-?\d+$/.test(value)) {
        return "Integer";
    } else if (/^-?\d*\.?\d+$/.test(value)) {
        return "Float";
    } else {
        return "Neither";
    }
}

function RefundAmount(value, UnitRate, id) {
    debugger;
    var quantity = $('#txtquantity_' + id).val();
    var Totalamount = (quantity * UnitRate);
    var Refundamount = (parseInt($('#refundAmt_che_' + id).val()));
    var STA = $('#TA_' + id).val();


    if (parseInt($('#che_' + id + '_RDD').val()) == 1)
    {
        if (quantity == "") {
            toastr.warning('Please Enter the Refund Quantity',
                {
                    //closeButton: false,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 0,
                });
            $('#refundAmt_che_' + id).val('');
            return false;
        }

        if (parseInt(Refundamount) > Totalamount) {
            toastr.warning('Refund amount is higher. Please check the Quantity and Unit Rate',
                {
                    //closeButton: false,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 0,
                });

            $('#refundAmt_che_' + id).val('');
        }
    }
    else
    {
        if (parseInt(Refundamount) > STA) {
            toastr.warning('Refund amount is higher.',
                {
                    //closeButton: false,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 0,
                });

            $('#refundAmt_che_' + id).val('');
        }
        else
        {
            $('#hdnRefundAmount_' + id).val(Refundamount);
        }
    }

    
}

function ShowHideFunction(e,id_val) {

    debugger;

    var id = e.id;

    if ($('#' + id + '_RDD').val() == "")
    {
        $(e).prop('checked', false);
        toastr.warning('Please Select the Service Refund Type.',
                       {
                           //closeButton: false,
                           progressBar: true,
                           allowHtml: true,
                           timeOut: 0,
                       });


        return false;
    }

    if ($(e).prop('checked')) {

        if (parseInt($('#che_' + id_val + '_RDD').val()) == 1)
        {
            $('#txtquantity_' + id_val).attr('disabled', false);
        }
        else
        {
            $('#refundAmt_che_' + id_val).attr('disabled', false);
        }
    
    }
    else {
        $('.' + id).attr('disabled', true);
        $('#che_' + id_val + '_RDD').val('');
        $('#refundAmt_' + id).val(0);
        $('#txtquantity_' + id_val).val('');
        $('#hdnRefundAmount_' + id_val).val('');
    }
}

$(document).on('input', '#Total', function () {

    var Cal_Total = 0;

    $("#Total .InTotal").each(function () {
        var Get_Invalue = $(this).val();
        if ($.isNumeric(Get_Invalue)) {
            Cal_Total += parseFloat(Get_Invalue);
        }


        $('#totalrefund').val(Cal_Total);
    });


});

$('#btnRefundSubmit').click(function () {
    SaveRefundBilling();
});

function SaveRefundBilling() {
    debugger;

    var count = $('#hdnCount').val();

    var allid = '';

    if (parseInt($('#SRType').val()) == 1 || parseInt($('#SRType').val()) == "")
    {
        if ($('#hdnCount').val() == '' || $('#hdnCount').val() == null || $('#hdnCount').val() == 0) {
            toastr.warning('Please Select Refund Service',
               {
                   //closeButton: false,
                   progressBar: true,
                   allowHtml: true,
                   timeOut: 0,
               });
            return false;
        }
    }

    if ($.trim($('#refund_branch_id').val()) == "") {
        $('#Prefund_branch_id').show();
        $('#Prefund_branch_id').fadeOut(8000);
        $('#Prefund_branch_id').html('Select Branch');
        $('#refund_branch_id').focus();
        $('#refund_branch_id').val('');
        return false;
    }

    if ($.trim($('#txtRefundtype').val()) == "") {
        $('#PtxtRefundtype').show();
        $('#PtxtRefundtype').fadeOut(8000);
        $('#PtxtRefundtype').html('Enter Refund Type');
        $('#txtRefundtype').focus();
        $('#txtRefundtype').val('');
        return false;
    }

    if ($.trim($('#ddRefundMode').val()) == "") {
        $('#PddRefundMode').show();
        $('#PddRefundMode').fadeOut(8000);
        $('#PddRefundMode').html('Select Refund Mode');
        $('#ddRefundMode').focus();
        $('#ddRefundMode').val('');
        return false;
    }

    if ($.trim($('#ddRefundMode').val()) == 2) {
        if ($('#txtVoucherCode').val() == "")
        {
            $('#sapan_VoucherCode').html('*');
            $('#PtxtVoucherCode').show();
            $('#PtxtVoucherCode').fadeOut(8000);
            $('#PtxtVoucherCode').html('Enter Voucher Code');
            $('#txtVoucherCode').focus();
            $('#txtVoucherCode').val('');
            return false;
        }
    }

    if (parseInt($('#SRType').val()) == 2) {
        
        if ($.trim($('#txtrepaid_amount').val()) == "") {
            $('#Ptxtrepaid_amount').show();
            $('#Ptxtrepaid_amount').fadeOut(8000);
            $('#Ptxtrepaid_amount').html('Enter Repaid Amount..');
            $('#txtrepaid_amount').focus();
            $('#txtrepaid_amount').val('');
            return false;
        }

        if (parseInt($('#txtrepaid_amount').val()) > parseInt($('#BRAmount').val())) {
            $('#Ptxtrepaid_amount').show();
            $('#Ptxtrepaid_amount').fadeOut(8000);
            $('#Ptxtrepaid_amount').html('Repaid Amount is high. Please check');
            $('#txtrepaid_amount').focus();
            //$('#txtrepaid_amount').val('');
            return false;
        }
        count = 1;
    }



    //for (var i = 0; i < count; i++) {

    //    if ($('#che_' + (i)).prop('checked') == true) {
    //        if (allid == '') {
    //            allid = $('#HBillDetailId_' + i).val();
    //        }
    //        else {
    //            allid = allid + ',' + $('#HBillDetailId_' + i).val();
    //        }
    //    }
    //}
    var billing_detailsid = 0, refundamt = 0, refundQuantity = 0, service_refund_type = "";

    var objRefund = [];
    for (var i = 0; i < count; i++) {


        if ($('#che_' + (i)).prop('checked') == true || parseInt($('#SRType').val()) == 2) {

            if (parseInt($('#SRType').val()) != 2)
            {
                billing_detailsid = $('#HBillDetailId_' + i).val();
                refundamt = $('#refundAmt_che_' + i).val();
                refundQuantity = $('#txtquantity_' + i).val();
                service_refund_type = $('#che_' + i + '_RDD').val();

                if (service_refund_type == 1)
                {

                    if (refundQuantity == 0 || refundQuantity == "") {
                        toastr.warning('Quantity Fields Not Empty or 0',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        $('#txtquantity_' + i).focus();
                        return false;
                    }
                }
                
                if (refundamt == 0 || refundamt == "") {
                    toastr.warning('Refund Amount Fields Not Empty or 0',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    $('#refundAmt_che_' + i).focus();
                    return false;
                }
            }


            objRefund.push({
                billing_detailsid: billing_detailsid,
                details_refundamt: refundamt,
                Dml_Indicator: 'I',
                all_detailsid: allid,
                total_refundamt: $("#totalrefund").val() == "" ? $('#txtrepaid_amount').val() : $("#totalrefund").val(),
                billing_no: $("#hdnbillno").val(),
                hospital_id: $("#HospitalId").val(),
                branch_id: $("#refund_branch_id").val(),
                created_by: $("#hiddenUser_id").val(),
                refund_quantity: refundQuantity == "" ? 0 : refundQuantity,
                refund_type: $('#txtRefundtype').val(),
                refund_mode: $('#ddRefundMode').val(),
                voucher_code: $('#txtVoucherCode').val(),
                refund_description: $('#txtRefundDescription').val(),
                work_order_detailsid: $('#hdnWO_detailsid').val() == "" || $('#hdnWO_detailsid').val() == null ? 0 : $('#hdnWO_detailsid').val(),
                billing_type: $('#hdnbilling_type').val() == "" || $('#hdnbilling_type').val() == null ? 1 : $('#hdnbilling_type').val(),
                billing_refund_code: $('#hdnrefund_code').val(),
                phone_no: $('#txtPhoneNo').val(),
                email_id: $('#txtEmailId').val(),
                billing_refund_type: $('#SRType').val() == "" ? 1 : $('#SRType').val()
            })
        }
        
    }


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

                if (data1.Table.length > 0)
                {
                    toastr.success('<button type="button" id="confirmationRevertYes" class="btn btn-warning btn-xs mt20">OK</button>', 'Refund Billing Details Inserted Successfully..',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                    $('#confirmationRevertYes').click(function () {
                      //  $('#HdnRefundtype').val('');
                        $('#txtRefundtype').val('');
                        $('#ddRefundMode').val('');
                        $('#txtVoucherCode').val('');
                        $("#totalrefund").val('');
                        $('#txtRefundDescription').val('');
                        $('#btnRefundSubmit').addClass('hidden');
                        window.location = '/BillingMaster/refund_view';
                    })
                    
                }

                
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

//$('#txtRefundtype').autocomplete({
//    source: function (request, response) {
//        $.ajax({
//            async: true,
//            url: '/BillingMaster/AutoCompleteRefund?RName=' + $('#txtRefundtype').val(),
//            type: "POST",
//            dataType: "json",
//            data: { Prefix: request.term, branch_id: $('#refund_branch_id').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.master_service_name, value: item.master_service_name, id: item.master_servie_type_id };
//                }))

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

//    }

//});
function Loadrefundtype() {
    debugger
    
    var subdepartment = {
        Dml_Indicator: "CRT",
        hospital_id: $('#HospitalId').val()
       // ,branch_id: $('#refund_branch_id').val() == "" || $('#refund_branch_id').val() == null ? $('#hdnBranch_id').val() : $('#refund_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;                   
                    var SubDepartment;
                    $('#txtRefundtype').empty();
                    var default_opt = '<option value="">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#txtRefundtype').append(SubDepartment);
                        //$('#refund_branch_id').change();
                    }
                    else {
                        $('#txtRefundtype').append(default_opt + SubDepartment);
                    }                                
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

//$('#btnrefundsend').click(function () {

//    if ($('#hdnCount').val() == '' || $('#hdnCount').val() == null || $('#hdnCount').val() == 0) {
//        toastr.warning('Please Select Refund Service..',
//           {
//               //closeButton: false,
//               progressBar: true,
//               allowHtml: true,
//               timeOut: 0,
//           });
//        return false;
//    }

//    if ($.trim($('#txtPhoneNo').val()) == "") {
//        $('#PtxtPhoneNo').show();
//        $('#PtxtPhoneNo').fadeOut(8000);
//        $('#PtxtPhoneNo').html('Enter Phone No');
//        $('#txtPhoneNo').focus();
//        $('#txtPhoneNo').val('');
//        return false;
//    }

//    if ($.trim($('#txtEmailId').val()) == "") {
//        $('#PtxtEmailId').show();
//        $('#PtxtEmailId').fadeOut(8000);
//        $('#PtxtEmailId').html('Enter Email Id');
//        $('#txtEmailId').focus();
//        $('#txtEmailId').val('');
//        return false;
//    }

//    if ($.trim($('#refund_branch_id').val()) == "") {
//        $('#Prefund_branch_id').show();
//        $('#Prefund_branch_id').fadeOut(8000);
//        $('#Prefund_branch_id').html('Select Branch');
//        $('#refund_branch_id').focus();
//        $('#refund_branch_id').val('');
//        return false;
//    }


//    var Bankdata = {
//        Dml_Indicator: "RDI",
//        phone_no: $('#txtPhoneNo').val(),
//        email_id: $('#txtEmailId').val(),
//        billing_no: $("#hdnbillno").val(),
//        branch_id: $("#refund_branch_id").val()
//    }

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

//            }
//            else {

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

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

//                        toastr.success('Refund Details Inserted Successfully..',
//                        {
//                            //closeButton: false,
//                            progressBar: true,
//                            allowHtml: true,
//                            timeOut: 0,
//                        });


                        
//                        $('#txtPhoneNo').val(''),
//                        $('#txtEmailId').val(''),
//                        $('#hdnCount').val('');
                        

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

//});
$('#SRType').change(function () {

    if ($('#refund_branch_id').val()=="")
    {
        toastr.warning('Please Select the Branch',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
        $('#SRType').val('');
        return false;
    }

    if ($('#txtPaitentSearch_bill').val() == null || $('#txtPaitentSearch_bill').val() == '')
    {
        $('#txtPaitentSearch_bill').prop("disabled", false);
    }
    if ($('#SRType').val() == "")
    {
        $('#txtPaitentSearch_bill').prop("disabled", true);
        $('#txtPaitentSearch_bill').val('');
        $('.pat-strip').hide();
        $('#hdnbillno').val('');
        $('#HdnRefund_code').val('');
        $('#btnRefundSubmit').addClass('hidden');
    }
    else {
        
        
        $('#txtPaitentSearch_bill').val('');
        $('.pat-strip').hide();
        $('#hdnbillno').val('');
        $('#HdnRefund_code').val('');
        $('#btnRefundSubmit').addClass('hidden');

    }

    if (parseInt($('#SRType').val())==2)
    {
        $('.divBRA_column').removeClass('hidden');
        $('.Billdetails_hidden').addClass('hidden');
        $('#RefundDetails').empty();
        $('#totalrefund').val('');
        $('#hdnCount').val('');
    }
    else {

        $('.divBRA_column').addClass('hidden'); 
    }
})

$(document).ready(function () {
    $('#txtPaitentSearch_bill').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: '/BillingMaster/AutoCompleteBillingCode?Billing_code=' + $('#txtPaitentSearch_bill').val() + '&branchid=' + $('#refund_branch_id').val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term, billing_refund_type: $('#SRType').val() },
                success: function (data) {
                    debugger;
                    //var data2 = JSON.parse(data);
                    //var data = data2.data;
                    response($.map(data, function (item) {
                        debugger;
                        return { label: item.billing_code, value: item.billing_code, id: item.billing_no };
                    }))

                }
            })
        },
        minLength: 1,
        select: function (event, ui) {
            $('#hdnbillno').val(ui.item.id);
            $('#HdnRefund_code').val(ui.item.value);
            $('#btnRefundSubmit').removeClass('hidden');
            //$('.pat-strip').show();
            if ($('#SRType').val() == 2)
            {
                GetBilling_RefundAmount();
            }
            else
            {
                Refund_Billdetails();
            }


        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);

        }

    });
});

function GetBilling_RefundAmount()
{
    var Billcode = '';

    if ($('#hdnbill_code').val() == "") {
        Billcode = $('#hdnbillno').val();

    }
    else {
        Billcode = $('#hdnbill_code').val();
    }

    var RefundTbldata = {

        Dml_Indicator: 'GBRA',
        billing_no: Billcode
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundTbldata),
        success: function (data) {
            $('#RefundDetails').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

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


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

                        debugger;
                        $('#txtPhoneNo').val(emp.phone_number);
                        $('#txtEmailId').val(emp.email_id);
                        $('#BRAmount').val(emp.billing_refund);
                        PatientSearch(emp.patient_id, emp.visit_type, emp.branch_id, emp.visit_report_id);
                    });

                    $("#hdnbillno").val(data1.Table[0].billing_no);
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
}