@extends('layouts.app')
@section('title', __('lang_v1.omni_channel_services'))

@section('content')

<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>@lang('lang_v1.omni_channel_services')</h1>
    <br>
    {{-- @include('layouts.partials.search_settings') --}}
</section>

<!-- Main content -->
<section class="content">
{!! Form::open(['url' => action([\App\Http\Controllers\OmniChannelServicesController::class, 'postAccountingOmni']), 'method' => 'post', 'id' => 'omni_edit_form',
    'files' => true ]) !!}  
    <div class="row">
        <div class="col-xs-12">
        <!--  <pos-tab-container> -->
            <div class="col-xs-12 pos-tab-container">
                <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pos-tab-menu">
                    <div class="list-group">
                        <a href="#" class="list-group-item text-center active">@lang('lang_v1.quickbooks')</a>
                        {{-- <a href="#" class="list-group-item text-center">@lang('lang_v1.zero')</a> --}}
                        {{-- <a href="#" class="list-group-item text-center">@lang('lang_v1.myob')</a>                     --}}
                    </div>
                </div>
                <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10 pos-tab">
                    <!-- tab 1 start -->
                    @include('business.partials.settings_quickbooks')
                    <!-- tab 1 end -->
                    <div id="collapseFilter2" class="panel-collapse active collapse " aria-expanded="true">
                        <div class="box-body">                                                      
                            <div class="col-sm-3" style="margin-left: 10px;">
                                <div class="form-group">                                     
                                    {!! Form::select('trigger_qb', $trigger, null, ['class' => 'form-control select2', 'id' => 'trigger_qb', 'placeholder' => 'Select a Trigger', 'onchange' => 'get_choose_an_action(this.value)', 'width' => '100%']) !!}
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="form-group">                                      
                                    {!! Form::select('choose_an_action_qb', [], null, ['class' => 'form-control select2', 'id' => 'choose_an_action_qb', 'placeholder' => 'Choose an action', 'width' => '100%']) !!}
                                </div>
                            </div> 
                            <div class="col-sm-3">
                                <div class="form-group">
                                    <button type="button" class="btn btn-primary btn-flat" onclick="saveTrigger()"><i class="fa fa-plus"></i> @lang( 'messages.add' )</button>
                                </div>
                            </div>             
                            @include('business.partials.list_trigger')                                                                                              
                        </div>
                    </div>
                    <!-- tab 2 start -->
                    {{-- @include('business.partials.settings_zero') --}}
                    <!-- tab 2 end -->
                    <!-- tab 3 start -->
                    {{-- @include('business.partials.settings_myob') --}}
                    <!-- tab 3 end -->
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <button class="btn btn-danger pull-right" type="submit">@lang('business.update_settings')</button>            
            <button type="button" class="btn btn-primary btn-flat pull-right" id="qb_test_btn" onclick="sync_quickbooks()">@lang('lang_v1.sync_quickbooks_data')</button>
        </div>
    </div>    
    <div class="row">
        <div class="col-md-12">
           <!-- Custom Tabs -->
           {{-- <input type="hidden" id="columnDefault" value="{{ $column_default ?? [] }}"> --}}           
            <div class="nav-tabs-custom">
                <ul class="nav nav-tabs">
                    <li class="active">
                        <a href="#expense_tab" data-toggle="tab" aria-expanded="true"><i class="fa fa-cubes" aria-hidden="true"></i> @lang('expense.expenses')</a>
                    </li>                    
                    <li>
                        <a href="#all_sales_tab" data-toggle="tab" aria-expanded="true"><i class="fa fas fa-arrow-circle-up" aria-hidden="true"></i> @lang('lang_v1.all_sales')</a>
                    </li>               
                    <li>
                        <a href="#invoices_tab" data-toggle="tab" aria-expanded="true"><i class="fa fa-envelope-open" aria-hidden="true"></i> @lang('invoice.invoices')</a>
                    </li>               
                    <li>
                        <a href="#customers_tab" data-toggle="tab" aria-expanded="true"><i class="fa fas fa-address-book" aria-hidden="true"></i> @lang('role.customers')</a>
                    </li>               
                    <li>
                        <a href="#products_tab" data-toggle="tab" aria-expanded="true"><i class="fa fas fa-address-book" aria-hidden="true"></i> @lang('product.products')</a>
                    </li>               
                </ul>

                <div class="tab-content">
                    <div class="tab-pane active" id="expense_tab">         
                        <div class="col-md-12">
                            @component('components.filters', ['title' => __('report.filters')])
                                <div class="col-md-3">
                                    <div class="form-group">
                                        {!! Form::label('type', __('lang_v1.transaction_type') . ':') !!}
                                        {!! Form::select('type', $transaction_type, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'transaction_type_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        {!! Form::label('date_qb', __('lang_v1.date') . ':') !!}
                                        {!! Form::text('date_qb', null, ['placeholder' => __('lang_v1.select_a_date_range'), 'class' => 'form-control', 'readonly', 'id' => 'date_qb']); !!}
                                    </div>
                                </div>
                        
                                <div class="col-md-3">
                                    <div class="form-group">
                                        {!! Form::label('payee_qb', __('lang_v1.payee') . ':') !!}
                                        {!! Form::select('payee_qb', $payee, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'payee_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        {!! Form::label('category_qb', __('lang_v1.category') . ':') !!}
                                        {!! Form::select('category_qb', $category, null, ['class' => 'filtervh', 'style' => 'width:100%', 'id' => 'category_qb', 'placeholder' => __('lang_v1.all')]); !!}
                                    </div>
                                </div>                                         
                            @endcomponent
                        </div>               
                        @include('business.partials.list_expense')
                    </div>
                    @can('stock_report.view')
                    <div class="tab-pane" id="all_sales_tab">     
                        @include('business.partials.list_all_sales')                                         
                    </div>
                    <div class="tab-pane" id="invoices_tab">                                              
                        @include('business.partials.list_invoices')                                           
                    </div>
                    <div class="tab-pane" id="customers_tab">   
                        @include('business.partials.list_customers')                                           
                    </div>
                    <div class="tab-pane" id="products_tab">                                              
                        @include('business.partials.list_products')                                           
                    </div>
                    @endcan
                </div>
            </div>
        </div>
    </div>
    @include('business.partials.modal_edit_invoice')
    @include('business.partials.modal_edit_expense')
    @include('business.partials.modal_edit_purchase_order')
    @include('business.partials.modal_edit_check')
    @include('business.partials.modal_edit_bill')
    @include('business.partials.modal_edit_bill_payment')
    @include('business.partials.modal_edit_payment')
    @include('business.partials.modal_edit_sales_receipt')
    @include('business.partials.modal_edit_credit_memo')
    @include('business.partials.modal_edit_estimate')
    @include('business.partials.modal_edit_refund')
{!! Form::close() !!}
</section>
<!-- /.content -->
@stop
@section('javascript')
<script type="text/javascript">
    var expense_qb_table,
        trigger_qb_table,
        customer_qb_table,
        products_qb_table,
        invoice_json,
        expense_json,
        purchase_order_json,
        check_json,
        bill_json,
        bill_payment_json,
        payment_json,
        sales_receipt_json,
        creditmemo_json,
        estimate_json,
        refund_json;
    $(document).ready(function() {        
        var bigenable = $("input[type='radio'][name='quickbooks_enable']:checked").val()        
        var zeroenable = $("input[type='radio'][name='zero_enable']:checked").val()        
        var wooenable = $("input[type='radio'][name='myob_enable']:checked").val()                      

        if(bigenable == '1') {
            // bigcommerce
            $('#quickbooks_api_url').css('display', 'block')
            $('#quickbooks_api_access_token').css('display', 'block')
            $('#quickbooks_api_key').css('display', 'block')
            $('#quickbooks_api_secret').css('display', 'block')
            $('#quickbooks_space').addClass('col-sm-3')
        } else {
            // big commerce
            $('#quickbooks_api_url').css('display', 'none')
            $('#quickbooks_api_access_token').css('display', 'none')
            $('#quickbooks_api_key').css('display', 'none')
            $('#quickbooks_api_secret').css('display', 'none')
            $('#quickbooks_space').removeClass('col-sm-3')
        }

        if(zeroenable == '1') {
            // zero
            $('#zero_api_url').css('display', 'block')
            $('#zero_api_access_token').css('display', 'block')
            $('#zero_api_key').css('display', 'block')
            $('#zero_api_secret').css('display', 'block')
            $('#zero_space').addClass('col-sm-3')
        } else {
            // zero
            $('#zero_api_url').css('display', 'none')
            $('#zero_api_access_token').css('display', 'none')
            $('#zero_api_key').css('display', 'none')
            $('#zero_api_secret').css('display', 'none')
            $('#zero_space').removeClass('col-sm-3')
        }

        if(wooenable == '1') {
            // woo commerce
            $('#myob_api_url').css('display', 'block')
            $('#myob_api_access_token').css('display', 'block')
            $('#myob_api_key').css('display', 'block')
            $('#myob_api_secret').css('display', 'block')
            $('#myob_space').addClass('col-sm-3')
        } else {
            // woo commerce
            $('#myob_api_url').css('display', 'none')
            $('#myob_api_access_token').css('display', 'none')
            $('#myob_api_key').css('display', 'none')
            $('#myob_api_secret').css('display', 'none')
            $('#myob_space').removeClass('col-sm-3')
        }

        expense_qb_table = $('#expense_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[0, 'desc']],
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": base_path + "/table_quickbooks",
                "data": function ( d ) {
                    if($('#date_qb').val()) {
                        var start = $('#date_qb').data('daterangepicker').startDate.format('YYYY-MM-DD');
                        var end = $('#date_qb').data('daterangepicker').endDate.format('YYYY-MM-DD');
                        d.start_date = start;
                        d.end_date = end;
                    }                    

                    d.transaction_type = $('select#transaction_type_qb').find('option:selected').text();
                    d.name = $('select#payee_qb').find('option:selected').text();
                    d.split = $('select#category_qb').find('option:selected').text();                    

                    d = __datatable_ajax_callback(d);
                }
            },                                      
            columns: [                                                                
                { data: 'date', name: 'date', orderable: true },
                { data: 'transaction_type', name: 'transaction_type'},                    
                { data: 'num', name: 'num'},                    
                { data: 'name', name: 'name'},                    
                { data: 'split', name: 'split'},                    
                { data: 'memo', name: 'memo'},                                    
                { data: 'account', name: 'account'},                                    
                // { data: 'balance', name: 'balance'},                    
                { data: 'amount', name: 'amount'},                    
                { data: 'action', name: 'action'},                    
            ],
        })

        all_sales_qb_table = $('#all_sales_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[0, 'desc']],
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": base_path + "/table_quickbooks?type=all_sales",
                /* "data": function ( d ) {
                    if($('#date_qb').val()) {
                        var start = $('#date_qb').data('daterangepicker').startDate.format('YYYY-MM-DD');
                        var end = $('#date_qb').data('daterangepicker').endDate.format('YYYY-MM-DD');
                        d.start_date = start;
                        d.end_date = end;
                    }                    

                    d.transaction_type = $('select#transaction_type_qb').find('option:selected').text();
                    d.name = $('select#payee_qb').find('option:selected').text();
                    d.split = $('select#category_qb').find('option:selected').text();                    

                    d = __datatable_ajax_callback(d);
                } */
            },                                      
            columns: [                                                                
                { data: 'date', name: 'date', orderable: true },
                { data: 'transaction_type', name: 'transaction_type'},                    
                { data: 'num', name: 'num'},                    
                { data: 'name', name: 'name'},                    
                { data: 'split', name: 'split'},                    
                { data: 'memo', name: 'memo'},                                    
                { data: 'account', name: 'account'},                                    
                // { data: 'balance', name: 'balance'},                    
                { data: 'amount', name: 'amount'},                    
                { data: 'action', name: 'action'},                    
            ],
        })

        invoice_qb_table = $('#invoice_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[0, 'desc']],
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": base_path + "/table_invoice_quickbooks",
                /* "data": function ( d ) {
                    if($('#date_qb').val()) {
                        var start = $('#date_qb').data('daterangepicker').startDate.format('YYYY-MM-DD');
                        var end = $('#date_qb').data('daterangepicker').endDate.format('YYYY-MM-DD');
                        d.start_date = start;
                        d.end_date = end;
                    }                    

                    d.transaction_type = $('select#transaction_type_qb').find('option:selected').text();
                    d.name = $('select#payee_qb').find('option:selected').text();
                    d.split = $('select#category_qb').find('option:selected').text();                    

                    d = __datatable_ajax_callback(d);
                } */
            },                                      
            columns: [                                                                
                { data: 'txn_date', name: 'txn_date'},
                { data: 'invoice_no', name: 'invoice_no'},                    
                { data: 'customer', name: 'customer'},                    
                { data: 'total_amt', name: 'total_amt'},                    
                { data: 'balance', name: 'balance'},                    
                { data: 'due_date', name: 'due_date'},                   
                { data: 'status', name: 'status'},                   
                { data: 'action', name: 'action'},                   
            ],
        })

        trigger_qb_table = $('#trigger_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[1, 'asc']],
            buttons: [],
            searching: false,
            paging: false,
            // scrollY: "75vh",
            // scrollX: true,
            // scrollCollapse: true                    
            "ajax": {
                "url": base_path + "/table_trigger_qb",
                /* "data": function ( d ) {
                    if($('#date_qb').val()) {
                        var start = $('#date_qb').data('daterangepicker').startDate.format('YYYY-MM-DD');
                        var end = $('#date_qb').data('daterangepicker').endDate.format('YYYY-MM-DD');
                        d.start_date = start;
                        d.end_date = end;
                    }                    

                    d.transaction_type = $('select#transaction_type_qb').find('option:selected').text();
                    d.name = $('select#payee_qb').find('option:selected').text();
                    d.split = $('select#category_qb').find('option:selected').text();                    

                    d = __datatable_ajax_callback(d);
                } */
            },                          
            /* columnDefs: [ {
                "targets": [0, 1,],
                "orderable": false,
                "searchable": false
            }], */
            columns: [                                                                
                { data: 'trigger_name', name: 'trigger_name'  },
                { data: 'action_name', name: 'action_name'},                                          
                { data: 'action', name: 'action'},                                          
            ],
        })

        customer_qb_table = $('#customer_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[0, 'asc']],
            buttons: [],                  
            "ajax": {
                "url": base_path + "/table_customer_qb",
                
            }, 
            columns: [                                                                
                { data: 'name', name: 'name'  },
                { data: 'address_line_1', name: 'address_line_1'},                                          
                { data: 'mobile', name: 'mobile'},                                          
                { data: 'email', name: 'email'},                                          
                { data: 'balance', name: 'balance'},                                          
            ],
        })

        products_qb_table = $('#products_qb_table').DataTable({
            processing: true,
            serverSide: true,
            aaSorting: [[0, 'asc']],
            buttons: [],                  
            "ajax": {
                "url": base_path + "/table_products_qb",
                
            }, 
            columns: [                                                                
                { data: 'name', name: 'name'  },
                { data: 'sku', name: 'sku'},                                          
                { data: 'type', name: 'type'},                                          
                { data: 'product_description', name: 'product_description'},                                                      
                { data: 'income_account_ref', name: 'income_account_ref'},                                                      
                { data: 'default_sell_price', name: 'default_sell_price'},                                                      
                { data: 'default_purchase_price', name: 'default_purchase_price'},                                                      
                { data: 'taxable', name: 'taxable'},                                                      
                { data: 'qty_available', name: 'qty_available'},                                                      
                { data: 'alert_quantity', name: 'alert_quantity'},                                                      
            ],
        })

        $('#get_url_token_qb').on('click', function() {
            $.ajax({
                method: "GET",
                url: base_path + '/get_url_token_qb',                
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex')
                },
                success: function(result){                    
                    $('#pos-loader').css('display', 'none')
                    window.open(result);
                }
            }); 
            // window.open(base_path + '/test-new-tab-session');                     
        })

        $('#date_qb').daterangepicker(
            dateRangeSettings,
            function (start, end) {
                $('#date_qb').val(start.format('1900-01-01') + ' ~ ' + end.format(moment_date_format));
                expense_qb_table.ajax.reload();
            }
        );
        $('#date_qb').on('cancel.daterangepicker', function(ev, picker) {
            $('#date_qb').val('');
            expense_qb_table.ajax.reload();
        });

        $(document).on('change', '#transaction_type_qb, #payee_qb, #category_qb',  function() {
            expense_qb_table.ajax.reload();
        });                     
        
        setTimeout(() => {
            $('.select2.select2-container').css('width', '100%');
        }, 200);

        window.addEventListener('storage', (event) => {            
            if(event.key == 'quickbooks_token') {
                var jsonArray = JSON.parse(event.newValue);
                $('#quickbooks_api_access_token').val(jsonArray.token)
                if(jsonArray.rc == 200) {
                    swal({
                        title: 'Information',
                        text: 'Connected to quickbooks. Do you want to sync your data now?',
                        icon: 'info',
                        buttons: {
                            cancel: "No",
                            confirm: "Yes"
                        },                      
                    }).then((confirmed) => {
                        if(confirmed) {
                            sync_quickbooks();
                        }
                    });
                } else {
                    swal({
                        title: 'Information',
                        text: jsonArray.msg,
                        icon: 'warning',
                    })
                }
            }
        });
    })     
    
    function get_choose_an_action(id) {
        $.ajax({
            method: 'GET',
            url: '/trigger_action/' + id,
            dataType: 'html',
            beforeSend: function() {                        
            },
            success: function(result) {
                // console.log(result)                    
                $('#choose_an_action_qb').html('')
                $('#choose_an_action_qb').append(result)
            },
            error: function() {
                swal({
                    title: "Warning",
                    text: "Something when wrong",
                    icon: "warning"
                })
            }
        })
    }

    function saveTrigger() {
        $.ajax({
            method: 'POST',
            url: '/trigger_action_create',
            data: {
                trigger: $('select#trigger_qb').val(),
                action: $('select#choose_an_action_qb').val(),
            },
            dataType: 'json',
            beforeSend: function() {  
                $('#pos-loader').css('display', 'inline-flex')   
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {
                    swal({
                        title: "Information",
                        icon: "warning",
                        text: result.msg
                    })                   
                } else {
                    swal({
                        title: "Success",
                        icon: "success",
                        text: result.msg
                    })                   
                }
                trigger_qb_table.ajax.reload();
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: "Warning",
                    text: "Something when wrong",
                    icon: "warning"
                })
            }
        })
    }

    function delete_trigger(id) {
        $.ajax({
            method: 'POST',
            url: '/delete_trigger/' + id,
            beforeSend: function() {                
            }, 
            success: function(result) {
                if(result.rc == 1) {                    
                    trigger_qb_table.ajax.reload();
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        });
    }

    function void_or_delete_invoice_qb(id, sync_token, type) {
        $.ajax({
            method: 'POST',
            url: '/void_or_delete_invoice_qb/' + id + '/' + sync_token + '?type=' + type,
            beforeSend: function() {         
                $('#pos-loader').css('display', 'inline-flex');       
            }, 
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {                 
                    swal({
                        title: 'Success',
                        text: result.msg,
                        icon: 'success'
                    })   
                    invoice_qb_table.ajax.reload();
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        });
    }

    function view_edit_qb(id, sync_token) {
        $.ajax({
            method: 'GET',
            url: '/view_edit_invoice_qb?id=' + id + '&sync_token=' + sync_token,
            beforeSend: function() {         
                $('#pos-loader').css('display', 'inline-flex');       
            }, 
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {                 
                    /* swal({
                        title: 'Success',
                        text: result.msg,
                        icon: 'success'
                    })  */                      
                    invoice_json = result.invoice;
                    $('#customer_invoice').html('');
                    if(result.customer) {
                        var customer = result.customer;
                        $.each(result.customer, function(k,v) {
                            var selected = v.Id == result.invoice.CustomerRef.value ? 'selected' : '';
                            $('#customer_invoice').append(`
                                <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                            `)
                        });
                    }
                    $('#customer_email_invoice').val(result.invoice.BillEmail ? result.invoice.BillEmail.Address : null);
                    var note = result.invoice.PrivateNote ? result.invoice.PrivateNote : 'Look balance';
                    if(note.includes('Voided')) {
                        $('#balance_status').html('Payment Status')
                        $('#balance_due_invoice').html('VOID');
                    } else if(result.invoice.Balance == 0 && result.invoice.TotalAmt > 0) {
                        $('#balance_status').html('Payment Status')
                        $('#balance_due_invoice').html('PAID');
                    } else {
                        $('#balance_status').html('BALANCE DUE')
                        $('#balance_due_invoice').html(__currency_trans_from_en(result.invoice.Balance, true));
                    }

                    var bill_address1 = result.invoice.BillAddr.hasOwnProperty('Line1') ? result.invoice.BillAddr.Line1 : '';
                    var bill_address2 = result.invoice.BillAddr.hasOwnProperty('Line2') ? result.invoice.BillAddr.Line2 : '';
                    var bill_address3 = result.invoice.BillAddr.hasOwnProperty('Line3') ? result.invoice.BillAddr.Line3 : '';
                    var bill_address = bill_address1 + ((bill_address2) ? '\n' + bill_address2 : '') + ((bill_address3) ? '\n' + bill_address3 : '');
                    $('#billing_address_invoice').val(bill_address);
                    $('#terms_invoice').html('');
                    if(result.term) {
                        var term = result.term;
                        $.each(term, function(k,v) {
                            var salesterm = result.invoice.SalesTermRef ? result.invoice.SalesTermRef.value : '';
                            var selected = v.Id == salesterm ? 'selected' : '';
                            $('#terms_invoice').append(`
                                <option value="${v.Id}" ${selected}>${v.Name}</option>
                            `)
                        });
                    }
                    $(document).on('shown.bs.modal', '#modal_edit_invoice, #modal_edit_expense, #modal_edit_check, #modal_edit_purchase_order', function(e) {
                        $('.dob-date-picker').datepicker({
                            autoclose: true,
                            // endDate: 'today',
                        });
                    });
                $('#invoice_date').val(format_date(result.invoice.TxnDate));
                    $('#invoice_due_date').val(format_date(result.invoice.DueDate));
                    $('#invoice_no').html(result.invoice.DocNumber);
                    var memo = result.invoice.CustomerMemo ? result.invoice.CustomerMemo.value : null;
                    $('#customer_memo').val(memo);

                    $('#tax_rate_invoice').html(`<option value="" data-rate="0">None</option>`);
                    if(result.taxrate) {
                        var taxrate = result.taxrate;                        
                        $.each(taxrate, function(k,v) {
                            var tax_id = result.invoice.hasOwnProperty('TxnTaxDetail') ? result.invoice.TxnTaxDetail.TaxLine : null;
                            var taxId = null;
                            if(tax_id) {
                                taxId = result.invoice.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value;
                            }
                            var selected = v.Id == taxId ? 'selected' : '';
                            // var tax_id = result.invoice.TxnTaxDetail.TaxLine ? result.invoice.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value : null;
                            // var selected = v.Id == tax_id ? 'selected' : '';
                            $('#tax_rate_invoice').append(`
                                <option value="${v.Id}" ${selected} data-rate="${v.RateValue}">${v.Name}</option>
                            `)
                            if(selected) {                                
                                $('span#tax_rate').html(v.RateValue + '%');
                                $('#tax_rate_invoice').find('option:selected').trigger('change.select2');                                
                            }
                        });
                    }

                    var tax_amount = result.invoice.TxnTaxDetail.TotalTax;
                    $('#tax_amount').val(tax_amount);

                    if(result.invoice.Line) {
                        $('#product_service').html('');
                        $.each(result.invoice.Line, function(k,v) {
                            if(v.DetailType == 'SalesItemLineDetail') {
                                var products = '';
                                $.each(result.product, function(kp, vp) {
                                    var selected = vp.quickbooks_id == v.SalesItemLineDetail.ItemRef.value ? 'selected' : '';
                                    products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                });
                                $('#product_service').append(`
                                    <tr>
                                        <td>${k+1}</td>
                                        <td><select class="form-control select2" id="ItemName${k+1}" name="Line[][ProductName]" onchange="get_product_data(${k+1}, 'select')">
                                            ${products}
                                        </select></td>
                                        <td><input type="text" class="form-control" id="Description${k+1}" name="Line[][Description]" value="${v.Description}"></td>
                                        <td><input type="text" class="form-control" id="Qty${k+1}" name="Line[][Qty]" value="${v.SalesItemLineDetail.Qty}" onchange="get_product_data(${k+1}, 'input')"></td>
                                        <td><input type="text" class="form-control" id="UnitPrice${k+1}" name="Line[][UnitPrice]" value="${v.SalesItemLineDetail.UnitPrice == undefined ? 0 : v.SalesItemLineDetail.UnitPrice}" onchange="get_product_data(${k+1}, 'input')"></td>
                                        <td id="totalAmount${k+1}">${v.Amount}</td>
                                        <td><a href="javascript:void(0)" id="delete${k+1}"><i class="fa fa-trash" style="color: red;"></i></a></td>
                                    </tr>
                                `);
                                $('.select2').select2({
                                    dropdownParent: $('#modal_edit_invoice')
                                });
                                setTimeout(() => {
                                    $('.select2.select2-container').css('width', '100%');
                                }, 200);
                            } else if(v.DetailType == 'SubTotalLineDetail') {
                                $('#span_subtotal').html(v.Amount);
                            } else if(v.DetailType == 'DiscountLineDetail') {
                                var percent = v.DiscountLineDetail.PercentBased ? 'percent' : 'value';
                                $('#discount_type').val(percent);
                                $('#percent_amount').val(v.DiscountLineDetail.DiscountPercent);
                                $('#total_discount').val(v.Amount);
                            }
                        })
                    }

                    // $('#span_subtotal').html(result.invoice.TotalAmt);
                    // $('#total_discount').html(result.invoice.TotalAmt);
                    var amount_received = parseFloat(result.invoice.TotalAmt) - parseFloat(result.invoice.Balance);                                    
                    amount_received = amount_received ? parseFloat(amount_received).toFixed(2) : 0;
                    $('span#amount_received').html(amount_received);                    
                    $('#total_amt').html(result.invoice.TotalAmt);
                    $('#total_amt_old').val(result.invoice.TotalAmt);
                    $('#balance_due').html(result.invoice.Balance);
                    $('#balance_due_old').val(result.invoice.Balance);
                    $('#modal_edit_invoice').modal({backdrop: 'static', keyboard: false}); 
                    get_discount();                   
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        });
        // $('#modal_edit_invoice').modal('show');        
    }

    function view_all_sales_qb(id, type) {
        $.ajax({
            method: 'GET',
            url: '/view_edit_all_sales_qb?id=' + id + '&type=' + type,
            beforeSend: function() {         
                $('#pos-loader').css('display', 'inline-flex');   
                // document.getElementById('form_purchase_order').reset();
                $('tbody[id^=category_list]').html('');
                $('tbody[id^=product_service]').html('');
            }, 
            success: function(result) {
                $('#pos-loader').css('display', 'none')                                             
                // console.log(result)
                if(result.rc == 1) {                    
                    if(type == 'Expense') {
                        expense_json = result.purchase;
                        $('#payee').html('');
                        if(result.vendor) {                            
                            var vendor = result.vendor;
                            $.each(result.vendor, function(k,v) {
                                var vendorId = result.purchase.EntityRef ? result.purchase.EntityRef.value : '';                                
                                var selected = v.Id == vendorId ? 'selected' : '';                                
                                $('#payee').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        $('#payment_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 42 || v1.Id == 41 || v1.Id == 35 || v1.Id == 36 || v1.Id == 4) {
                                    var accountId = result.purchase.AccountRef ? result.purchase.AccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#payment_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        $('span#amount').html(__currency_trans_from_en(result.purchase.TotalAmt, true));
                        $('td#span_subtotal_expense').html(__currency_trans_from_en(result.purchase.TotalAmt, true));
                        $('#payment_date').val(format_date(result.purchase.TxnDate));

                        if(result.payment_method) {                            
                            $('#payment_method').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = result.purchase.PaymentMethodRef ? result.purchase.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        }

                        $('#transaction_type').val('Expense');
                        if(result.purchase.DocNumber) {
                            $('#doc_number').html(type + ' # ' + result.purchase.DocNumber);
                        } else {
                            $('#doc_number').html(type);                         
                        }
                        $('#ref_no').val(result.purchase.DocNumber);
                        $('#memo').val(result.purchase.PrivateNote);

                        $('#category_list').html('');
                        $('#product_service_expense').html('');
                        if(result.purchase.Line) {
                            var index_product = 0;
                            var index_category = 0;
                            $.each(result.purchase.Line, function(k3,v3) {                                                                
                                var products = '';                                
                                var vendors = '';                                
                                var accounts = '';                                
                                var customers = `<option value="">None</option>`;                                
                                
                                
                                if(v3.DetailType == 'ItemBasedExpenseLineDetail') {
                                    var billable = v3.ItemBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxable = v3.ItemBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v3.ItemBasedExpenseLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.ItemBasedExpenseLineDetail.CustomerRef ? v3.ItemBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    $('#product_service_expense').append(`
                                        <tr>
                                            <td>${index_product+1}</td>
                                            <td><select class="form-control select2" id="ItemExpense${index_product+1}" name="Expense[][ProductName]">${products}</select></td>
                                            <td><input type="text" class="form-control" id="DescriptionExpense${index_product+1}" name="Expense[][Description]" value="${v3.Description ? v3.Description : ''}"></td>
                                            <td><input type="text" class="form-control" id="QtyExpense${index_product+1}" name="Expense[][Qty]" value="${v3.ItemBasedExpenseLineDetail.Qty}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceExpense${index_product+1}" name="Expense[][UnitPrice]" value="${v3.ItemBasedExpenseLineDetail.UnitPrice == undefined ? 0 : v3.ItemBasedExpenseLineDetail.UnitPrice}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td id="totalAmountExpense${index_product+1}">${v3.Amount}</td>
                                            <td><input type="checkbox" id="billable${index_product+1}" value="1" ${billable}></td>
                                            <td><input type="checkbox" id="taxable${index_product+1}" value="1" ${taxable}></td>
                                            <td><select class="form-control select2" id="customerExpense${index_product+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_product++;
                                } else if(v3.DetailType == "AccountBasedExpenseLineDetail") {
                                    if(result.account) {                                    
                                        $.each(result.account, function(k6,v6) {
                                            var accountIdRow = v3.AccountBasedExpenseLineDetail.AccountRef ? v3.AccountBasedExpenseLineDetail.AccountRef.value : '';
                                            var selected = v6.Id == accountIdRow ? 'selected' : '';
                                            accounts += `<option value="${v6.Id}" ${selected}>${v6.Name}</option>`;                                        
                                        });
                                    }
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.AccountBasedExpenseLineDetail.CustomerRef ? v3.AccountBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    var billableCategory = v3.AccountBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxableCategory = v3.AccountBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $('#category_list').append(`
                                        <tr>
                                            <td>${index_category+1}</td>
                                            <td><select class="form-control select2" id="categoryName${index_category+1}" name="Category[][CategoryName]">${accounts}</select></td>
                                            <td><input type="text" class="form-control" id="categoryDescription${index_category+1}" name="Category[][Description]" value="${v3.Description ? v3.Description : ''}" ></td>
                                            <td><input type="text" id="totalAmountCategory${index_category+1}" class="form-control" value="${v3.Amount}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="checkbox" id="billableCategory${index_category+1}" value="1" ${billableCategory}></td>
                                            <td><input type="checkbox" id="taxableCategory${index_category+1}" value="1" ${taxableCategory}></td>
                                            <td><select class="form-control select2" id="customerCategory${index_category+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_category++;
                                }


                            })
                            $('.select2').select2({
                                dropdownParent: $('#modal_edit_expense')
                            });                            
                            setTimeout(() => {
                                $('.select2.select2-container').css('width', '100%');
                            }, 200);
                        }

                        $('#modal_edit_expense').modal({backdrop: 'static', keyboard: false});
                    } else if(type == 'Purchase Order') {
                        // console.log(result);
                        purchase_order_json = result.purchase_order;
                        if(result.vendor) {
                            $('#vendor_purchase_order').html(`<option value="">None</option>`);
                            $.each(result.vendor, function(k,v) {
                                var vendorId = purchase_order_json.hasOwnProperty('VendorRef') ? purchase_order_json.VendorRef.value : null;
                                var selected = v.Id == vendorId ? 'selected' : '';
                                $('#vendor_purchase_order').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            })
                        }

                        $('#email_purchase_order').val(purchase_order_json.hasOwnProperty('POEmail') ? purchase_order_json.POEmail.Address : '');
                        $('#amount_purchase_order').html(__currency_trans_from_en(purchase_order_json.TotalAmt, true));
                        var address = purchase_order_json.hasOwnProperty('VendorAddr') ? purchase_order_json.VendorAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 : '') + '\n' + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#mailing_address').val(full_address);
                        }
                        var address = purchase_order_json.hasOwnProperty('ShipAddr') ? purchase_order_json.ShipAddr : null;
                        if(address) {
                            var Line1 = address.hasOwnProperty('Line1') ? address.Line1 : '';
                            var Line2 = address.hasOwnProperty('Line2') ? address.Line2 : '';
                            var Line3 = address.hasOwnProperty('Line3') ? address.Line3 : '';                            
                            var full_address = Line1 + '\n' + Line2 + ', ' + Line3;

                            $('#shipping_address').val(full_address);
                        }

                        $('#ship_via').val(purchase_order_json.hasOwnProperty('ShipMethodRef') ? purchase_order_json.ShipMethodRef.value : '')

                        $('#purchase_order_date').val(format_date(purchase_order_json.TxnDate));
                        $('#custom_field').html('');
                        if(purchase_order_json.hasOwnProperty('CustomField')) {
                            $.each(purchase_order_json.CustomField, function(k,v) {
                                var StringValue = v.hasOwnProperty('StringValue') ? v.StringValue : '';
                                $('#custom_field').append(`
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label for="">${v.Name}</label>
                                            <input type="text" name="${v.Name.replace(/\s/, '').replace('#','')}" id="${v.Name.replace(/\s/, '').replace('#','')}" class="form-control" value="${StringValue}">
                                        </div>
                                    </div>
                                `);
                            })
                        }

                        $('#category_list_purchase_order').html('');
                        $('#product_service_purchase_order').html('');
                        

                        $('#transaction_type').val('Purchase Order');
                        if(purchase_order_json.DocNumber) {
                            $('#doc_number_purchase_order').html('Purchase Order #' + purchase_order_json.DocNumber);
                        } else {
                            $('#doc_number_purchase_order').html('Purchase Order');                         
                        }

                        if(purchase_order_json.Line) {
                            var index_product = 0;
                            var index_category = 0;
                            // console.log(purchase_order_json);
                            $.each(purchase_order_json.Line, function(k3,v3) {                                                                
                                // console.log(v3);
                                var products = '';                                
                                var vendors = '';                                
                                var accounts = '';                                
                                var customers = `<option value="">None</option>`;                                
                                
                                
                                if(v3.DetailType == 'ItemBasedExpenseLineDetail') {
                                    var billable = v3.ItemBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxable = v3.ItemBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v3.ItemBasedExpenseLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.ItemBasedExpenseLineDetail.CustomerRef ? v3.ItemBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    $('#product_service_purchase_order').append(`
                                        <tr>
                                            <td>${index_product+1}</td>
                                            <td><select class="form-control select2" id="ItemExpense${index_product+1}" name="Expense[][ProductName]">${products}</select></td>
                                            <td><input type="text" class="form-control" id="DescriptionExpense${index_product+1}" name="Expense[][Description]" value="${v3.Description ? v3.Description : ''}"></td>
                                            <td><input type="text" class="form-control" id="QtyExpense${index_product+1}" name="Expense[][Qty]" value="${v3.ItemBasedExpenseLineDetail.Qty}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceExpense${index_product+1}" name="Expense[][UnitPrice]" value="${v3.ItemBasedExpenseLineDetail.UnitPrice == undefined ? 0 : v3.ItemBasedExpenseLineDetail.UnitPrice}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td id="totalAmountExpense${index_product+1}">${v3.Amount}</td>
                                            <td><input type="checkbox" id="billable${index_product+1}" value="1" ${billable}></td>
                                            <td><input type="checkbox" id="taxable${index_product+1}" value="1" ${taxable}></td>
                                            <td><select class="form-control select2" id="customerExpense${index_product+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_product++;
                                } else if(v3.DetailType == "AccountBasedExpenseLineDetail") {
                                    if(result.account) {                                    
                                        $.each(result.account, function(k6,v6) {
                                            var accountIdRow = v3.AccountBasedExpenseLineDetail.AccountRef ? v3.AccountBasedExpenseLineDetail.AccountRef.value : '';
                                            var selected = v6.Id == accountIdRow ? 'selected' : '';
                                            accounts += `<option value="${v6.Id}" ${selected}>${v6.Name}</option>`;                                        
                                        });
                                    }
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.AccountBasedExpenseLineDetail.CustomerRef ? v3.AccountBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    var billableCategory = v3.AccountBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxableCategory = v3.AccountBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $('#category_list_purchase_order').append(`
                                        <tr>
                                            <td>${index_category+1}</td>
                                            <td><select class="form-control select2" id="categoryName${index_category+1}" name="Category[][CategoryName]">${accounts}</select></td>
                                            <td><input type="text" class="form-control" id="categoryDescription${index_category+1}" name="Category[][Description]" value="${v3.Description ? v3.Description : ''}" ></td>
                                            <td><input type="text" id="totalAmountCategory${index_category+1}" class="form-control" value="${v3.Amount}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="checkbox" id="billableCategory${index_category+1}" value="1" ${billableCategory}></td>
                                            <td><input type="checkbox" id="taxableCategory${index_category+1}" value="1" ${taxableCategory}></td>
                                            <td><select class="form-control select2" id="customerCategory${index_category+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_category++;
                                }


                            })
                            $('.select2').select2({
                                dropdownParent: $('#modal_edit_purchase_order')
                            });
                            setTimeout(() => {
                                $('.select2.select2-container').css('width', '100%');
                            }, 200);
                        }

                        $('#memo_purchase_order').val(purchase_order_json.hasOwnProperty('memo') ? purchase_order_json.memo : '');
                        $('#privateNote_purchase_order').val(purchase_order_json.hasOwnProperty('privateNote') ? purchase_order_json.privateNote : '');

                        $('#span_subtotal_purchase_order').html(purchase_order_json.TotalAmt);

                        $('#modal_edit_purchase_order').modal('show');
                    } else if(type == 'Check') {
                        console.log(result)
                        $('#transaction_type').val('Check');
                        check_json = result.purchase;
                        $('#payee').html('');
                        if(result.vendor) {                                                        
                            $.each(result.vendor, function(k,v) {
                                var vendorId = result.purchase.EntityRef ? result.purchase.EntityRef.value : '';                                
                                var selected = v.Id == vendorId ? 'selected' : '';                                
                                $('#payee_check').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        $('#bank_account_check').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36) {
                                    var accountId = result.purchase.AccountRef ? result.purchase.AccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#bank_account_check').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        $('#amount_check').html(__currency_trans_from_en(check_json.TotalAmt, true));
                        $('#span_subtotal_check').html(__currency_trans_from_en(check_json.TotalAmt, false));

                        var address = check_json.hasOwnProperty('RemitToAddr') ? check_json.RemitToAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 : '') + '\n' + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#mailing_address_check').val(full_address);
                        }

                        $('#payment_date_check').val(format_date(check_json.TxnDate));
                        $('#check_no').val(check_json.hasOwnProperty('DocNumber') ? check_json.DocNumber : '');
                        $('#memo_check').val(check_json.hasOwnProperty('PrivateNote') ? check_json.PrivateNote : '');

                        if(check_json.hasOwnProperty('DocNumber')) {
                            $('#doc_number_check').html('Check #' + check_json.DocNumber);
                        } else {
                            $('#doc_number_check').html('Check');
                        }

                        $('#product_service_check').html('');
                        $('#category_list_check').html('');
                        if(check_json.Line) {
                            var index_product = 0;
                            var index_category = 0;
                            $.each(check_json.Line, function(k3,v3) {                                                                
                                var products = '';                                
                                var vendors = '';                                
                                var accounts = '';                                
                                var customers = `<option value="">None</option>`;                                
                                
                                
                                if(v3.DetailType == 'ItemBasedExpenseLineDetail') {
                                    var billable = v3.ItemBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxable = v3.ItemBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v3.ItemBasedExpenseLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.ItemBasedExpenseLineDetail.CustomerRef ? v3.ItemBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    $('#product_service_check').append(`
                                        <tr>
                                            <td>${index_product+1}</td>
                                            <td><select class="form-control select2" id="ItemExpense${index_product+1}" name="Expense[][ProductName]">${products}</select></td>
                                            <td><input type="text" class="form-control" id="DescriptionExpense${index_product+1}" name="Expense[][Description]" value="${v3.Description ? v3.Description : ''}"></td>
                                            <td><input type="text" class="form-control" id="QtyExpense${index_product+1}" name="Expense[][Qty]" value="${v3.ItemBasedExpenseLineDetail.Qty}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceExpense${index_product+1}" name="Expense[][UnitPrice]" value="${v3.ItemBasedExpenseLineDetail.UnitPrice == undefined ? 0 : v3.ItemBasedExpenseLineDetail.UnitPrice}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td id="totalAmountExpense${index_product+1}">${v3.Amount}</td>
                                            <td><input type="checkbox" id="billable${index_product+1}" value="1" ${billable}></td>
                                            <td><input type="checkbox" id="taxable${index_product+1}" value="1" ${taxable}></td>
                                            <td><select class="form-control select2" id="customerExpense${index_product+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_product++;
                                } else if(v3.DetailType == "AccountBasedExpenseLineDetail") {
                                    if(result.account) {                                    
                                        $.each(result.account, function(k6,v6) {
                                            var accountIdRow = v3.AccountBasedExpenseLineDetail.AccountRef ? v3.AccountBasedExpenseLineDetail.AccountRef.value : '';
                                            var selected = v6.Id == accountIdRow ? 'selected' : '';
                                            accounts += `<option value="${v6.Id}" ${selected}>${v6.Name}</option>`;                                        
                                        });
                                    }
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.AccountBasedExpenseLineDetail.CustomerRef ? v3.AccountBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    var billableCategory = v3.AccountBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxableCategory = v3.AccountBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $('#category_list_check').append(`
                                        <tr>
                                            <td>${index_category+1}</td>
                                            <td><select class="form-control select2" id="categoryName${index_category+1}" name="Category[][CategoryName]">${accounts}</select></td>
                                            <td><input type="text" class="form-control" id="categoryDescription${index_category+1}" name="Category[][Description]" value="${v3.Description ? v3.Description : ''}" ></td>
                                            <td><input type="text" id="totalAmountCategory${index_category+1}" class="form-control" value="${v3.Amount}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="checkbox" id="billableCategory${index_category+1}" value="1" ${billableCategory}></td>
                                            <td><input type="checkbox" id="taxableCategory${index_category+1}" value="1" ${taxableCategory}></td>
                                            <td><select class="form-control select2" id="customerCategory${index_category+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_category++;
                                }


                            })
                            $('.select2').select2({
                                dropdownParent: $('#modal_edit_check')
                            });                            
                            setTimeout(() => {
                                $('.select2.select2-container').css('width', '100%');
                            }, 200);
                        }

                        $('#modal_edit_check').modal({backdrop: 'static', keyboard: false});
                    } else if(type == 'Bill') {
                        bill_json = result.bill;

                        $('#transaction_type').val('Bill');                        
                        $('#vendor_bill').html('');
                        if(result.vendor) {                                                        
                            $.each(result.vendor, function(k,v) {
                                var vendorId = bill_json.VendorRef ? bill_json.VendorRef.value : '';                                
                                var selected = v.Id == vendorId ? 'selected' : '';                                
                                $('#vendor_bill').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        var address = bill_json.hasOwnProperty('VendorAddr') ? bill_json.VendorAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 : '') + '\n' + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#mailing_address_bill').val(full_address);
                        }

                        $('#term_bill').html('');
                        if(result.term) {
                            var term = result.term;
                            $.each(term, function(k,v) {
                                var salesterm = bill_json.SalesTermRef ? bill_json.SalesTermRef.value : '';
                                var selected = v.Id == salesterm ? 'selected' : '';
                                $('#term_bill').append(`
                                    <option value="${v.Id}" ${selected}>${v.Name}</option>
                                `)
                            });
                        }

                        $('#bill_date').val(format_date(bill_json.TxnDate));
                        $('#due_date_bill').val(format_date(bill_json.DueDate));
                        var doc_number = bill_json.hasOwnProperty('DocNumber') ? bill_json.DocNumber : '';
                        $('#bill_no').val(doc_number)
                        $('#balance_old').val(bill_json.Balance);
                        if(doc_number) {
                            $('#doc_number').html('Bill #' + bill_json.DocNumber);
                        } else {
                            $('#doc_number').html('Bill');
                        }

                        $('#memo_bill').val(bill_json.hasOwnProperty('PrivateNote') ? bill_json.PrivateNote : '');
                        $('#span_subtotal_bill').html(bill_json.TotalAmt);
                        if(bill_json.Balance == 0) {
                            $('#subtotal_bill_old').html('<br> Have payment made ' +__currency_trans_from_en(bill_json.TotalAmt, true));
                            $('#subtotal_balance_old').val(bill_json.TotalAmt);
                        } else if(bill_json.Balance > bill_json.TotalAmt) {
                            var amount = bill_json.TotalAmt - bill_json.Balance;
                            $('#subtotal_bill_old').html('<br> Have payment made ' +__currency_trans_from_en(amount, true));                        
                            $('#subtotal_balance_old').val(amount);
                        } else if((bill_json.Balance != 0) < bill_json.TotalAmt) {
                            $('#subtotal_bill_old').html('<br> Have payment made ' +__currency_trans_from_en(bill_json.Balance, true));                        
                            $('#subtotal_balance_old').val(bill_json.Balance);
                        } else {
                            $('#subtotal_bill_old').html(0);                        
                            $('#subtotal_balance_old').val(0);
                        }

                        if(bill_json.Balance == 0) {
                            $('#balance_status_bill').html('Payment Status');
                            $('#amount_bill').html('Paid');
                        } else {
                            $('#balance_status_bill').html('Balance due');
                            $('#amount_bill').html(__currency_trans_from_en(bill_json.TotalAmt, true));
                        }

                        $('#product_service_bill').html('');
                        $('#category_list_bill').html('');
                        if(bill_json.Line) {
                            var index_product = 0;
                            var index_category = 0;
                            $.each(bill_json.Line, function(k3,v3) {                                                                
                                var products = '';                                
                                var vendors = '';                                
                                var accounts = '';                                
                                var customers = `<option value="">None</option>`;                                
                                
                                
                                if(v3.DetailType == 'ItemBasedExpenseLineDetail') {
                                    var billable = v3.ItemBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxable = v3.ItemBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v3.ItemBasedExpenseLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.ItemBasedExpenseLineDetail.CustomerRef ? v3.ItemBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    $('#product_service_bill').append(`
                                        <tr>
                                            <td>${index_product+1}</td>
                                            <td><select class="form-control select2" id="ItemExpense${index_product+1}" name="Expense[][ProductName]">${products}</select></td>
                                            <td><input type="text" class="form-control" id="DescriptionExpense${index_product+1}" name="Expense[][Description]" value="${v3.Description ? v3.Description : ''}"></td>
                                            <td><input type="text" class="form-control" id="QtyExpense${index_product+1}" name="Expense[][Qty]" value="${v3.ItemBasedExpenseLineDetail.Qty}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceExpense${index_product+1}" name="Expense[][UnitPrice]" value="${v3.ItemBasedExpenseLineDetail.UnitPrice == undefined ? 0 : v3.ItemBasedExpenseLineDetail.UnitPrice}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td id="totalAmountExpense${index_product+1}">${v3.Amount}</td>
                                            <td><input type="checkbox" id="billable${index_product+1}" value="1" ${billable}></td>
                                            <td><input type="checkbox" id="taxable${index_product+1}" value="1" ${taxable}></td>
                                            <td><select class="form-control select2" id="customerExpense${index_product+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_product++;
                                } else if(v3.DetailType == "AccountBasedExpenseLineDetail") {
                                    if(result.account) {                                    
                                        $.each(result.account, function(k6,v6) {
                                            var accountIdRow = v3.AccountBasedExpenseLineDetail.AccountRef ? v3.AccountBasedExpenseLineDetail.AccountRef.value : '';
                                            var selected = v6.Id == accountIdRow ? 'selected' : '';
                                            accounts += `<option value="${v6.Id}" ${selected}>${v6.Name}</option>`;                                        
                                        });
                                    }
                                    if(result.customer) {                                    
                                        $.each(result.customer, function(k5,v5) {
                                            var customerIdRow = v3.AccountBasedExpenseLineDetail.CustomerRef ? v3.AccountBasedExpenseLineDetail.CustomerRef.value : '';
                                            var selected = v5.Id == customerIdRow ? 'selected' : '';
                                            customers += `<option value="${v5.Id}" ${selected}>${v5.DisplayName}</option>`;                                        
                                        });
                                    }
                                    var billableCategory = v3.AccountBasedExpenseLineDetail.BillableStatus == 'Billable' ? 'checked' : '';
                                    var taxableCategory = v3.AccountBasedExpenseLineDetail.TaxCodeRef.value == 'TAX' ? 'checked' : '';
                                    $('#category_list_bill').append(`
                                        <tr>
                                            <td>${index_category+1}</td>
                                            <td><select class="form-control select2" id="categoryName${index_category+1}" name="Category[][CategoryName]">${accounts}</select></td>
                                            <td><input type="text" class="form-control" id="categoryDescription${index_category+1}" name="Category[][Description]" value="${v3.Description ? v3.Description : ''}" ></td>
                                            <td><input type="text" id="totalAmountCategory${index_category+1}" class="form-control" value="${v3.Amount}" onchange="calculate_subtotal_expense(this, '${type}')"></td>
                                            <td><input type="checkbox" id="billableCategory${index_category+1}" value="1" ${billableCategory}></td>
                                            <td><input type="checkbox" id="taxableCategory${index_category+1}" value="1" ${taxableCategory}></td>
                                            <td><select class="form-control select2" id="customerCategory${index_category+1}" name="Expense[][Customer]">${customers}</select></td>
                                        </tr>
                                    `);
                                    index_category++;
                                }


                            })
                            $('.select2').select2({
                                dropdownParent: $('#modal_edit_bill')
                            });                            
                            setTimeout(() => {
                                $('.select2.select2-container').css('width', '100%');
                            }, 200);
                        }
                        
                        $('#modal_edit_bill').modal('show');
                    } else if(type == 'Bill Payment') {
                        bill_payment_json = result.bill;

                        $('#transaction_type').val('Bill Payment');                        
                        $('#vendor_bill_payment').html('');
                        if(result.vendor) {                                                        
                            $.each(result.vendor, function(k,v) {
                                var vendorId = bill_payment_json.VendorRef ? bill_payment_json.VendorRef.value : '';                                
                                var selected = v.Id == vendorId ? 'selected' : '';                                
                                $('#vendor_bill_payment').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        $('#bank_account_bill_payment').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 42 || v1.Id == 41 || v1.Id == 4) {
                                    var accountId = bill_payment_json.CheckPayment ? bill_payment_json.CheckPayment.BankAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#bank_account_bill_payment').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        var address = bill_payment_json.hasOwnProperty('VendorAddr') ? bill_payment_json.VendorAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 + '\n' : '') + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#mailing_address_bill_payment').val(full_address);
                        }
                        
                        // $('#due_date_bill').val(format_date(bill_json.DueDate));
                        var doc_number = bill_payment_json.hasOwnProperty('DocNumber') ? bill_payment_json.DocNumber : '';
                        $('#bill_no').val(doc_number)                        
                        if(doc_number) {
                            $('#doc_number').html('Bill Payment #' + bill_payment_json.DocNumber);
                        } else {
                            $('#doc_number').html('Bill Payment');
                        }

                        $('#amount_bill_payment').html(__currency_trans_from_en(bill_payment_json.Balance, true));
                        $('#amount_to_apply').html(bill_payment_json.Balance);

                        $('#bill_payment_list').html('');
                        $('#bill_payment_list').append(`
                            <tr>
                                <td>1</td>
                                <td>Bill #${bill_payment_json.DocNumber} (${format_date(bill_payment_json.TxnDate)})</td>
                                <td>${format_date(bill_payment_json.DueDate)}</td>
                                <td>${__currency_trans_from_en(bill_payment_json.TotalAmt, false)}</td>
                                <td>${__currency_trans_from_en(bill_payment_json.Balance, false)}</td>
                                <td><input type="text" id="amount_payment" name="amount_payment" class="form-control" value="${__currency_trans_from_en(bill_payment_json.Balance, false)}"></td>
                            </tr>
                        `);
                        $('.select2').select2({
                            dropdownParent: $('#modal_edit_bill_payment')
                        });                            
                        setTimeout(() => {
                            $('.select2.select2-container').css('width', '100%');
                        }, 200);
                        $('#modal_edit_bill_payment').modal('show');
                    } else if(type == 'Payment') {
                        payment_json = result.payment;
                        $("#customer_payment").html('');
                        if(result.customer) {                                                        
                            $.each(result.customer, function(k,v) {
                                var customerId = payment_json.hasOwnProperty('CustomerRef') ? payment_json.CustomerRef.value : '';                                
                                var selected = v.Id == customerId ? 'selected' : '';                                
                                $('#customer_payment').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        $('#transaction_type').val('Payment');
                        $('#payment_date_payment').val(format_date(payment_json.TxnDate));

                        if(result.payment_method) {                            
                            $('#payment_method_payment').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = payment_json.hasOwnProperty('PaymentMethodRef') ? payment_json.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method_payment').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        }

                        $('#deposit_payment_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 81 || v1.Id == 3 || v1.Id == 32 || v1.Id == 4) {
                                    var accountId = payment_json.hasOwnProperty('DepositToAccountRef') ? payment_json.DepositToAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#deposit_payment_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        var doc_number = payment_json.hasOwnProperty('PaymentRefNum') ? payment_json.PaymentRefNum : null;                        
                        if(doc_number) {
                            $('#doc_number_payment').html('Payment #' +doc_number);
                        } else {
                            $('#doc_number_payment').html('Payment');
                        }

                        var memo = payment_json.hasOwnProperty('PrivateNote') ? payment_json.PrivateNote : null;
                        if(memo == 'Voided') {
                            $('#amount_status_payment').html("Payment Status")
                            $('#amount_to_apply_payment').html(__currency_trans_from_en(0, true));
                            $('#amount_to_credit_payment').html(__currency_trans_from_en(0, true));
                            $('#amount_received_payment_html').html('Void');
                            $('#amount_received_payment_input').val(__currency_trans_from_en(0));
                        } else {
                            $('#amount_to_apply_payment').html(__currency_trans_from_en(payment_json.TotalAmt, true));
                            $('#amount_to_credit_payment').html(__currency_trans_from_en(payment_json.UnappliedAmt, true));
                            $('#amount_received_payment_html').html(__currency_trans_from_en(payment_json.TotalAmt, true));
                            $('#amount_received_payment_input').val(__currency_trans_from_en(payment_json.TotalAmt, false));
                        }
                        $('#reference_no_payment').val(doc_number);

                        $('#memo_payment').val(memo);

                        $('#payment_list').html('');
                        if(payment_json.Line) {
                            $.each(payment_json.Line, function(k,v) {                                       
                                var due_date = '';
                                var invoice_no = '';
                                var invoice_id = null;
                                var original_amount = 0;
                                $.each(result.invoice, function(ki,vi) {
                                    if(vi.invoice_id == v.LinkedTxn[0].TxnId) {
                                        due_date = format_date(vi.due_date);
                                        invoice_id = vi.invoice_id;
                                        invoice_no = 'Invoice # ' + vi.invoice_no + '( '+ format_date(vi.txn_date) +' )';
                                        original_amount = vi.total_amt;
                                    }
                                });                       
                                $('#payment_list').append(`
                                    <tr>
                                        <td>${k+1}
                                            <input type="hidden" id="invoice_id${k+1}" value="${invoice_id}">
                                        </td>
                                        <td>${invoice_no}</td>
                                        <td>${due_date}</td>
                                        <td>${__currency_trans_from_en(original_amount, false)}</td>
                                        <td>${__currency_trans_from_en(v.LineEx.any[1].value.Value, false)}</td>
                                        <td><input type="text" id="amount_payment${k+1}" name="amount_payment${k+1}" class="form-control" onchange="calculate_subtotal_expense(this, 'Payment')" value="${__currency_trans_from_en(v.Amount, false)}"></td>
                                    </tr>
                                `);
                            })
                            $('.select2').select2({
                                dropdownParent: $('#modal_edit_payment')
                            });                            
                            setTimeout(() => {
                                $('.select2.select2-container').css('width', '100%');
                            }, 200);
                        }
                        $('#modal_edit_payment').modal('show');
                    } else if(type == 'Sales Receipt') {
                        sales_receipt_json = result.sales_receipt;
                        $('#transaction_type').val('Sales Receipt');
                        var doc_number = sales_receipt_json.hasOwnProperty('DocNumber') ? sales_receipt_json.DocNumber : null;
                        $('#doc_number_sales_receipt').html(doc_number);

                        var memo = sales_receipt_json.hasOwnProperty('CustomerMemo') ? sales_receipt_json.CustomerMemo.value: null;
                        $("#customer_memo_sales_receipt").val(memo);
                        $("#customer_sales_receipt").val('');
                        if(result.customer) {                                                        
                            $.each(result.customer, function(k,v) {
                                var customerId = sales_receipt_json.hasOwnProperty('CustomerRef') ? sales_receipt_json.CustomerRef.value : '';
                                var selected = v.Id == customerId ? 'selected' : '';                                
                                $('#customer_sales_receipt').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        var private_note = sales_receipt_json.hasOwnProperty('PrivateNote') ? sales_receipt_json.PrivateNote : null;
                        $('#private_note_sales_receipt').val(private_note)
                        if(private_note) {
                            $('#balance_status_sales_receipt').html('Payment Status');
                            $('#balance_due_html_sales_receipt').html('Void');
                        } else {
                            $('#balance_status_sales_receipt').html('Amount');
                            $('#balance_due_html_sales_receipt').html(__currency_trans_from_en(sales_receipt_json.TotalAmt, true));
                        }

                        var bill_address = sales_receipt_json.hasOwnProperty('BillAddr') ? sales_receipt_json.BillAddr : null;
                        if(bill_address) {
                            var full_address = '';
                            var no = 0;
                            $.each(bill_address, function(k,v) {                            
                                if(no == bill_address.length) {
                                    if(k.includes('Line')) {
                                        full_address += v;   
                                    }
                                } else {
                                    if(k.includes('Line')) {
                                        full_address += v + '\n';                                           
                                    }
                                }
                                no++;
                            })

                            $('#billing_address_sales_receipt').val(full_address)
                        }

                        $('#sales_receipt_date').val(format_date(sales_receipt_json.TxnDate));

                        if(result.payment_method) {                            
                            $('#payment_method_sales_receipt').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = sales_receipt_json.hasOwnProperty('PaymentMethodRef') ? sales_receipt_json.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method_sales_receipt').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        }

                        $('#reference_no_sales_receipt').val(doc_number);

                        $('#sales_receipt_date').val(format_date(sales_receipt_json.TxnDate));

                        $('#deposit_sales_receipt_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 81 || v1.Id == 3 || v1.Id == 32 || v1.Id == 4) {
                                    var accountId = sales_receipt_json.hasOwnProperty('DepositToAccountRef') ? sales_receipt_json.DepositToAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#deposit_sales_receipt_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        var email = sales_receipt_json.hasOwnProperty('BillEmail') ? sales_receipt_json.BillEmail.Address : null; 
                        $('#customer_email_sales_receipt').val(email);

                        $('#tax_rate_sales_receipt').html(`<option value="" data-rate="0">None</option>`);
                        if(result.taxrate) {
                            var taxrate = result.taxrate;                        
                            $.each(taxrate, function(k,v) {
                                var tax_id = sales_receipt_json.hasOwnProperty('TxnTaxDetail') ? sales_receipt_json.TxnTaxDetail.TaxLine : null;
                                var taxId = null;
                                if(tax_id) {
                                    taxId = sales_receipt_json.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value;
                                }
                                var selected = v.Id == taxId ? 'selected' : '';
                                $('#tax_rate_sales_receipt').append(`
                                    <option value="${v.Id}" ${selected} data-rate="${v.RateValue}">${v.Name}</option>
                                `)
                                if(selected) {                                
                                    $('span#tax_rate_html_sales_receipt').html(v.RateValue + '%');
                                    $('#tax_rate_sales_receipt').find('option:selected').trigger('change.select2');                                
                                }
                            });
                        }

                        var tax_amount = sales_receipt_json.TxnTaxDetail.TotalTax;
                        $('#tax_amount_sales_receipt').val(tax_amount);

                        if(sales_receipt_json.Line) {
                            $('#product_service_sales_receipt').html('');
                            $.each(sales_receipt_json.Line, function(k,v) {
                                if(v.DetailType == 'SalesItemLineDetail') {
                                    var products = '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v.SalesItemLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    $('#product_service_sales_receipt').append(`
                                        <tr>
                                            <td>${k+1}</td>
                                            <td><select class="form-control select2" id="ItemNameSalesReceipt${k+1}" name="Line[][ProductName]" onchange="get_product_data(${k+1}, 'select', 'SalesReceipt')">
                                                ${products}
                                            </select></td>
                                            <td><input type="text" class="form-control" id="DescriptionSalesReceipt${k+1}" name="Line[][Description]" value="${v.Description}"></td>
                                            <td><input type="text" class="form-control" id="QtySalesReceipt${k+1}" name="Line[][Qty]" value="${v.SalesItemLineDetail.Qty}" onchange="get_product_data(${k+1}, 'input', 'SalesReceipt')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceSalesReceipt${k+1}" name="Line[][UnitPrice]" value="${v.SalesItemLineDetail.UnitPrice == undefined ? 0 : v.SalesItemLineDetail.UnitPrice}" onchange="get_product_data(${k+1}, 'input', 'SalesReceipt')"></td>
                                            <td id="totalAmountSalesReceipt${k+1}">${v.Amount}</td>
                                            <td><a href="javascript:void(0)" id="delete${k+1}"></a></td>
                                        </tr>
                                    `);
                                    // icon trash for delete
                                    // <i class="fa fa-trash" style="color: red;"></i>
                                    $('.select2').select2({
                                        dropdownParent: $('#modal_edit_sales_receipt')
                                    });
                                    setTimeout(() => {
                                        $('.select2.select2-container').css('width', '100%');
                                    }, 200);
                                } else if(v.DetailType == 'SubTotalLineDetail') {
                                    $('#span_subtotal_sales_receipt').html(v.Amount);
                                } else if(v.DetailType == 'DiscountLineDetail') {
                                    var percent = v.DiscountLineDetail.PercentBased ? 'percent' : 'value';
                                    $('#discount_type_sales_receipt').val(percent);
                                    $('#percent_amount_sales_receipt').val(v.DiscountLineDetail.DiscountPercent);
                                    $('#total_discount_sales_receipt').val(v.Amount);
                                }
                            })
                        }

                        // $('#span_subtotal').html(result.invoice.TotalAmt);
                        // $('#total_discount').html(result.invoice.TotalAmt);
                        var amount_received = parseFloat(sales_receipt_json.TotalAmt) - parseFloat(sales_receipt_json.Balance); 
                        console.log(amount_received)                                   
                        amount_received = parseFloat(amount_received).toFixed(2);
                        $('span#amount_received_sales_receipt').html(amount_received);                    
                        $('#total_amt_sales_receipt').html(sales_receipt_json.TotalAmt);
                        $('#total_amt_old_sales_receipt').val(sales_receipt_json.TotalAmt);
                        $('#balance_due_sales_receipt').html(sales_receipt_json.Balance);
                        $('#balance_due_old_sales_receipt').val(sales_receipt_json.Balance);
                        
                        get_discount('Sales Receipt');

                        $('#modal_edit_sales_receipt').modal({backdrop: 'static', keyboard: false});
                    } else if(type == 'Credit Memo') {
                        creditmemo_json = result.creditmemo;
                        $('#transaction_type').val('Credit Memo');
                        var doc_number = creditmemo_json.hasOwnProperty('DocNumber') ? creditmemo_json.DocNumber : null;
                        $('#doc_number_credit_memo').html(doc_number);

                        var memo = creditmemo_json.hasOwnProperty('CustomerMemo') ? creditmemo_json.CustomerMemo.value: null;
                        $("#customer_memo_credit_memo").html(memo);
                        $("#customer_credit_memo").html('');
                        if(result.customer) {                                                        
                            $.each(result.customer, function(k,v) {
                                var customerId = creditmemo_json.hasOwnProperty('CustomerRef') ? creditmemo_json.CustomerRef.value : '';
                                var selected = v.Id == customerId ? 'selected' : '';                                
                                $('#customer_credit_memo').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        var private_note = creditmemo_json.hasOwnProperty('PrivateNote') ? creditmemo_json.PrivateNote : null;
                        $('#private_note_credit_memo').val(private_note);
                        if(private_note) {
                            $('#balance_status_credit_memo').html('Payment Status');
                            $('#balance_due_html_credit_memo').html('Void');
                        } else {
                            $('#balance_status_credit_memo').html('Amount');
                            $('#balance_due_html_credit_memo').html(__currency_trans_from_en(creditmemo_json.TotalAmt, true));
                        }

                        var bill_address = creditmemo_json.hasOwnProperty('BillAddr') ? creditmemo_json.BillAddr : null;
                        if(bill_address) {
                            var full_address = '';
                            var no = 0;
                            $.each(bill_address, function(k,v) {                            
                                if(no == bill_address.length) {
                                    if(k.includes('Line')) {
                                        full_address += v;   
                                    }
                                } else {
                                    if(k.includes('Line')) {
                                        full_address += v + '\n';                                           
                                    }
                                }
                                no++;
                            })

                            $('#billing_address_credit_memo').val(full_address)
                        }

                        $('#credit_memo_date').val(format_date(creditmemo_json.TxnDate));
                        /* 
                        if(result.payment_method) {                            
                            $('#payment_method_credit_memo').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = creditmemo_json.hasOwnProperty('PaymentMethodRef') ? creditmemo_json.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method_credit_memo').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        } */

                        $('#reference_no_credit_memo').val(doc_number);

                        $('#credit_memo_date').val(format_date(creditmemo_json.TxnDate));

                       /*  $('#deposit_credit_memo_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 81 || v1.Id == 3 || v1.Id == 32 || v1.Id == 4) {
                                    var accountId = creditmemo_json.hasOwnProperty('DepositToAccountRef') ? creditmemo_json.DepositToAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#deposit_credit_memo_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        } */

                        var email = creditmemo_json.hasOwnProperty('BillEmail') ? creditmemo_json.BillEmail.Address : null; 
                        $('#customer_email_credit_memo').val(email);

                        $('#tax_rate_credit_memo').html(`<option value="" data-rate="0">None</option>`);
                        if(result.taxrate) {
                            var taxrate = result.taxrate;                        
                            $.each(taxrate, function(k,v) {
                                var tax_id = creditmemo_json.hasOwnProperty('TxnTaxDetail') ? creditmemo_json.TxnTaxDetail.TaxLine : null;
                                var taxId = null;
                                if(tax_id) {
                                    taxId = creditmemo_json.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value;
                                }
                                var selected = v.Id == taxId ? 'selected' : '';
                                $('#tax_rate_credit_memo').append(`
                                    <option value="${v.Id}" ${selected} data-rate="${v.RateValue}">${v.Name}</option>
                                `)
                                if(selected) {                                
                                    $('span#tax_rate_html_credit_memo').html(v.RateValue + '%');
                                    $('#tax_rate_credit_memo').find('option:selected').trigger('change.select2');                                
                                }
                            });
                        }

                        var tax_amount = creditmemo_json.TxnTaxDetail.TotalTax;
                        $('#tax_amount_credit_memo').val(tax_amount);

                        if(creditmemo_json.Line) {
                            $('#product_service_credit_memo').html('');
                            $.each(creditmemo_json.Line, function(k,v) {
                                if(v.DetailType == 'SalesItemLineDetail') {
                                    var products = '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v.SalesItemLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    $('#product_service_credit_memo').append(`
                                        <tr>
                                            <td>${k+1}</td>
                                            <td><select class="form-control select2" id="ItemNameCreditMemo${k+1}" name="Line[][ProductName]" onchange="get_product_data(${k+1}, 'select', 'CreditMemo')">
                                                ${products}
                                            </select></td>
                                            <td><input type="text" class="form-control" id="DescriptionCreditMemo${k+1}" name="Line[][Description]" value="${v.Description}"></td>
                                            <td><input type="text" class="form-control" id="QtyCreditMemo${k+1}" name="Line[][Qty]" value="${v.SalesItemLineDetail.Qty}" onchange="get_product_data(${k+1}, 'input', 'CreditMemo')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceCreditMemo${k+1}" name="Line[][UnitPrice]" value="${v.SalesItemLineDetail.UnitPrice == undefined ? 0 : v.SalesItemLineDetail.UnitPrice}" onchange="get_product_data(${k+1}, 'input', 'CreditMemo')"></td>
                                            <td id="totalAmountCreditMemo${k+1}">${v.Amount}</td>
                                            <td><a href="javascript:void(0)" id="delete${k+1}"></a></td>
                                        </tr>
                                    `);
                                    // icon trash for delete
                                    // <i class="fa fa-trash" style="color: red;"></i>
                                    $('.select2').select2({
                                        dropdownParent: $('#modal_edit_credit_memo')
                                    });
                                    setTimeout(() => {
                                        $('.select2.select2-container').css('width', '100%');
                                    }, 200);
                                } else if(v.DetailType == 'SubTotalLineDetail') {
                                    $('#span_subtotal_credit_memo').html(v.Amount);
                                } else if(v.DetailType == 'DiscountLineDetail') {
                                    var percent = v.DiscountLineDetail.PercentBased ? 'percent' : 'value';
                                    $('#discount_type_credit_memo').val(percent);
                                    $('#percent_amount_credit_memo').val(v.DiscountLineDetail.DiscountPercent);
                                    $('#total_discount_credit_memo').val(v.Amount);
                                }
                            })
                        }

                        // $('#span_subtotal').html(result.invoice.TotalAmt);
                        // $('#total_discount').html(result.invoice.TotalAmt);
                        var amount_received = parseFloat(creditmemo_json.TotalAmt) - parseFloat(creditmemo_json.Balance); 
                        console.log(amount_received)                                   
                        amount_received = parseFloat(amount_received).toFixed(2);
                        $('span#amount_received_credit_memo').html(amount_received);                    
                        $('#total_amt_credit_memo').html(creditmemo_json.TotalAmt);
                        $('#total_amt_old_credit_memo').val(creditmemo_json.TotalAmt);
                        $('#balance_due_credit_memo').html(creditmemo_json.Balance);
                        $('#balance_due_old_credit_memo').val(creditmemo_json.Balance);
                        
                        get_discount('Credit Memo');

                        $('#modal_edit_credit_memo').modal({backdrop: 'static', keyboard: false});
                    } else if(type == 'Estimate') {
                        estimate_json = result.estimate;
                        $('#transaction_type').val('Estimate');
                        var doc_number = estimate_json.hasOwnProperty('DocNumber') ? estimate_json.DocNumber : null;
                        $('#doc_number_estimate').html(doc_number);

                        var memo = estimate_json.hasOwnProperty('CustomerMemo') ? estimate_json.CustomerMemo.value: null;
                        $("#customer_memo_estimate").html(memo);
                        
                        $("#customer_estimate").html('');
                        if(result.customer) {                                                        
                            $.each(result.customer, function(k,v) {
                                var customerId = estimate_json.hasOwnProperty('CustomerRef') ? estimate_json.CustomerRef.value : '';
                                var selected = v.Id == customerId ? 'selected' : '';                                
                                $('#customer_estimate').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        var private_note = estimate_json.hasOwnProperty('PrivateNote') ? estimate_json.PrivateNote : null;
                        $('#private_note_estimate').val(private_note);
                        if(private_note) {
                            $('#balance_status_estimate').html('Payment Status');
                            $('#balance_due_html_estimate').html('Void');
                        } else {
                            $('#balance_status_estimate').html('Amount');
                            $('#balance_due_html_credit_memo').html(__currency_trans_from_en(estimate_json.TotalAmt, true));
                        }

                        var address = estimate_json.hasOwnProperty('BillAddr') ? estimate_json.BillAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 : '') + '\n' + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#billing_address_estimate').val(full_address);
                        }

                        $('#estimate_date').val(format_date(estimate_json.TxnDate));
                        /* 
                        if(result.payment_method) {                            
                            $('#payment_method_credit_memo').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = estimate_json.hasOwnProperty('PaymentMethodRef') ? estimate_json.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method_credit_memo').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        } */

                        // $('#reference_no_credit_memo').val(doc_number);                        

                       /*  $('#deposit_credit_memo_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 81 || v1.Id == 3 || v1.Id == 32 || v1.Id == 4) {
                                    var accountId = estimate_json.hasOwnProperty('DepositToAccountRef') ? estimate_json.DepositToAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#deposit_credit_memo_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        } */

                        var email = estimate_json.hasOwnProperty('BillEmail') ? estimate_json.BillEmail.Address : null; 
                        $('#customer_email_estimate').val(email);

                        $('#tax_rate_credit_memo').html(`<option value="" data-rate="0">None</option>`);

                        var send_later = estimate_json.hasOwnProperty('PrintStatus') ? estimate_json.PrintStatus : '';
                        if(send_later) {
                            if(send_later == 'NeedToPrint') {
                                $('#send_later_estimate').attr('checked');
                            } else {
                                $('#send_later_estimate').removeAttr('checked');
                            }
                        }

                        var txn_status = estimate_json.hasOwnProperty('TxnStatus') ? estimate_json.TxnStatus : 'Pending';
                        if(txn_status) {
                            $('#txn_status_estimate').val(txn_status);
                            if(txn_status == 'Pending') {
                                $('#estimate_by').addClass('hide');
                                $('#update_status_estimate_by').val('');

                                $('#estimate_date_div').addClass('hide');
                                $('#update_status_estimate_date').val('');
                            } else {
                                $('#estimate_by').removeClass('hide');
                                $('#update_status_estimate_by').val(estimate_json.AcceptedBy);

                                $('#estimate_date_div').removeClass('hide');
                                $('#update_status_estimate_date').val(format_date(estimate_json.AcceptedDate));
                            }
                        }

                        $('#estimate_date').val(format_date(estimate_json.TxnDate));

                        var expiration_date = estimate_json.hasOwnProperty('ExpirationDate') ? format_date(estimate_json.ExpirationDate) : null;
                        if(expiration_date) {
                            $('#estimate_expiration_date').val(format_date(expiration_date));
                        } else {
                            $('#estimate_expiration_date').val(format_date(new Date()));                            
                        }

                        if(result.taxrate) {
                            var taxrate = result.taxrate;                        
                            $.each(taxrate, function(k,v) {
                                var tax_id = estimate_json.hasOwnProperty('TxnTaxDetail') ? estimate_json.TxnTaxDetail.TaxLine : null;
                                var taxId = null;
                                if(tax_id) {
                                    taxId = estimate_json.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value;
                                }
                                var selected = v.Id == taxId ? 'selected' : '';
                                $('#tax_rate_estimate').append(`
                                    <option value="${v.Id}" ${selected} data-rate="${v.RateValue}">${v.Name}</option>
                                `)
                                if(selected) {                                
                                    $('span#tax_rate_html_estimate').html(v.RateValue + '%');
                                    $('#tax_rate_estimate').find('option:selected').trigger('change.select2');                                
                                }
                            });
                        }

                        var tax_amount = estimate_json.TxnTaxDetail.TotalTax;
                        $('#tax_amount_estimate').val(tax_amount);

                        if(estimate_json.Line) {
                            $('#product_service_estimate').html('');
                            $.each(estimate_json.Line, function(k,v) {
                                if(v.DetailType == 'SalesItemLineDetail') {
                                    var products = '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v.SalesItemLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    $('#product_service_estimate').append(`
                                        <tr>
                                            <td>${k+1}</td>
                                            <td><select class="form-control select2" id="ItemNameEstimate${k+1}" name="Line[][ProductName]" onchange="get_product_data(${k+1}, 'select', 'Estimate')">
                                                ${products}
                                            </select></td>
                                            <td><input type="text" class="form-control" id="DescriptionEstimate${k+1}" name="Line[][Description]" value="${v.Description}"></td>
                                            <td><input type="text" class="form-control" id="QtyEstimate${k+1}" name="Line[][Qty]" value="${v.SalesItemLineDetail.Qty}" onchange="get_product_data(${k+1}, 'input', 'Estimate')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceEstimate${k+1}" name="Line[][UnitPrice]" value="${v.SalesItemLineDetail.UnitPrice == undefined ? 0 : v.SalesItemLineDetail.UnitPrice}" onchange="get_product_data(${k+1}, 'input', 'Estimate')"></td>
                                            <td id="totalAmountEstimate${k+1}">${v.Amount}</td>
                                            <td><a href="javascript:void(0)" id="delete${k+1}"></a></td>
                                        </tr>
                                    `);
                                    // icon trash for delete
                                    // <i class="fa fa-trash" style="color: red;"></i>
                                    $('.select2').select2({
                                        dropdownParent: $('#modal_edit_estimate')
                                    });
                                    setTimeout(() => {
                                        $('.select2.select2-container').css('width', '100%');
                                    }, 200);
                                } else if(v.DetailType == 'SubTotalLineDetail') {
                                    $('#span_subtotal_estimate').html(v.Amount);
                                } else if(v.DetailType == 'DiscountLineDetail') {
                                    var percent = v.DiscountLineDetail.PercentBased ? 'percent' : 'value';
                                    $('#discount_type_estimate').val(percent);
                                    $('#percent_amount_estimate').val(v.DiscountLineDetail.DiscountPercent);
                                    $('#total_discount_estimate').val(v.Amount);
                                }
                            })
                        }

                        // $('#span_subtotal').html(result.invoice.TotalAmt);
                        // $('#total_discount').html(result.invoice.TotalAmt);
                        var amount_received = parseFloat(estimate_json.TotalAmt);                                     
                        amount_received = parseFloat(amount_received).toFixed(2);
                        $('span#amount_received_estimate').html(amount_received);                    
                        $('#total_amt_estimate').html(estimate_json.TotalAmt);
                        $('#total_amt_old_estimate').val(estimate_json.TotalAmt);
                        $('#balance_due_estimate').html(0);
                        $('#balance_due_old_estimate').val(0);
                        
                        get_discount('Estimate');

                        $('#modal_edit_estimate').modal({backdrop: 'static', keyboard: false});
                    } else if(type == 'Refund') {
                        refund_json = result.refund;
                        $('#transaction_type').val('Refund');
                        var doc_number = refund_json.hasOwnProperty('DocNumber') ? refund_json.DocNumber : null;
                        $('#doc_number_refund').html(doc_number);

                        var memo = refund_json.hasOwnProperty('CustomerMemo') ? refund_json.CustomerMemo.value: null;
                        $("#customer_memo_refund").html(memo);
                        
                        $("#customer_refund").html('');
                        if(result.customer) {                                                        
                            $.each(result.customer, function(k,v) {
                                var customerId = refund_json.hasOwnProperty('CustomerRef') ? refund_json.CustomerRef.value : '';
                                var selected = v.Id == customerId ? 'selected' : '';                                
                                $('#customer_refund').append(`
                                    <option value="${v.Id}" ${selected}>${v.DisplayName}</option>
                                `)
                            });
                        }

                        var private_note = refund_json.hasOwnProperty('PrivateNote') ? refund_json.PrivateNote : null;
                        $('#private_note_refund').val(private_note);
                        if(private_note) {
                            $('#balance_status_refund').html('Payment Status');
                            $('#balance_due_html_refund').html('Void');
                        } else {
                            $('#balance_status_refund').html('Amount');
                            $('#balance_due_html_refund').html(__currency_trans_from_en(refund_json.TotalAmt, true));
                        }

                        var address = refund_json.hasOwnProperty('BillAddr') ? refund_json.BillAddr : null;
                        if(address) {
                            var city = address.hasOwnProperty('City') ? address.City : '';
                            var CountrySubDivisionCode = address.hasOwnProperty('CountrySubDivisionCode') ? address.CountrySubDivisionCode : '';
                            var postalCode = address.hasOwnProperty('PostalCode') ? address.PostalCode : '';
                            var full_address = ((address.hasOwnProperty('Line1')) ? address.Line1 : '') + '\n' + city + ', ' + CountrySubDivisionCode + ' ' + postalCode;

                            $('#billing_address_refund').val(full_address);
                        }

                        $('#refund_date').val(format_date(refund_json.TxnDate));

                        if(result.payment_method) {                            
                            $('#payment_method_refund').html(`
                                <option value="">None</option>
                            `);
                        
                            $.each(result.payment_method, function(k2,v2) {                                
                                var paymentMethodId = refund_json.hasOwnProperty('PaymentMethodRef') ? refund_json.PaymentMethodRef.value : '';
                                var selected = v2.Id == paymentMethodId ? 'selected' : '';
                                
                                $('#payment_method_refund').append(`
                                    <option value="${v2.Id}" ${selected}>${v2.Name}</option>
                                `)
                            })
                        }

                        $('#deposit_refund_account').html('');
                        if(result.account) {                            
                            $.each(result.account, function(k1,v1) {
                                if(v1.Id == 35 || v1.Id == 36 || v1.Id == 81 || v1.Id == 3 || v1.Id == 32 || v1.Id == 4) {
                                    var accountId = refund_json.hasOwnProperty('DepositToAccountRef') ? refund_json.DepositToAccountRef.value : '';
                                    var selected = v1.Id == accountId ? 'selected' : '';
                                    $('#deposit_refund_account').append(`
                                        <option value="${v1.Id}" ${selected}>${v1.Name}</option>
                                    `)
                                }
                            })
                        }

                        var email = refund_json.hasOwnProperty('BillEmail') ? refund_json.BillEmail.Address : null; 
                        $('#customer_email_refund').val(email);

                        $('#tax_rate_refund').html(`<option value="" data-rate="0">None</option>`);
                        if(result.taxrate) {
                            var taxrate = result.taxrate;                        
                            $.each(taxrate, function(k,v) {
                                var tax_id = refund_json.hasOwnProperty('TxnTaxDetail') ? refund_json.TxnTaxDetail.TaxLine : null;
                                var taxId = null;
                                if(tax_id) {
                                    taxId = refund_json.TxnTaxDetail.TaxLine[0].TaxLineDetail.TaxRateRef.value;
                                }
                                var selected = v.Id == taxId ? 'selected' : '';
                                $('#tax_rate_refund').append(`
                                    <option value="${v.Id}" ${selected} data-rate="${v.RateValue}">${v.Name}</option>
                                `)
                                if(selected) {                                
                                    $('span#tax_rate_html_refund').html(v.RateValue + '%');
                                    $('#tax_rate_refund').find('option:selected').trigger('change.select2');                                
                                }
                            });
                        }

                        var tax_amount = refund_json.TxnTaxDetail.TotalTax;
                        $('#tax_amount_refund').val(tax_amount);

                        if(refund_json.Line) {
                            $('#product_service_refund').html('');
                            $.each(refund_json.Line, function(k,v) {
                                if(v.DetailType == 'SalesItemLineDetail') {
                                    var products = '';
                                    $.each(result.product, function(kp, vp) {
                                        var selected = vp.quickbooks_id == v.SalesItemLineDetail.ItemRef.value ? 'selected' : '';
                                        products += `<option value="${vp.quickbooks_id}" ${selected} data-unitprice="${vp.default_sell_price}" data-description="${vp.product_description}">${vp.name}</option>`;
                                    });
                                    $('#product_service_refund').append(`
                                        <tr>
                                            <td>${k+1}</td>
                                            <td><select class="form-control select2" id="ItemNameRefund${k+1}" name="Line[][ProductName]" onchange="get_product_data(${k+1}, 'select', 'Refund')">
                                                ${products}
                                            </select></td>
                                            <td><input type="text" class="form-control" id="DescriptionRefund${k+1}" name="Line[][Description]" value="${v.Description}"></td>
                                            <td><input type="text" class="form-control" id="QtyRefund${k+1}" name="Line[][Qty]" value="${v.SalesItemLineDetail.Qty}" onchange="get_product_data(${k+1}, 'input', 'Refund')"></td>
                                            <td><input type="text" class="form-control" id="UnitPriceRefund${k+1}" name="Line[][UnitPrice]" value="${v.SalesItemLineDetail.UnitPrice == undefined ? 0 : v.SalesItemLineDetail.UnitPrice}" onchange="get_product_data(${k+1}, 'input', 'Refund')"></td>
                                            <td id="totalAmountRefund${k+1}">${v.Amount}</td>
                                            <td><a href="javascript:void(0)" id="delete${k+1}"></a></td>
                                        </tr>
                                    `);
                                    // icon trash for delete
                                    // <i class="fa fa-trash" style="color: red;"></i>
                                    $('.select2').select2({
                                        dropdownParent: $('#modal_edit_refund')
                                    });
                                    setTimeout(() => {
                                        $('.select2.select2-container').css('width', '100%');
                                    }, 200);
                                } else if(v.DetailType == 'SubTotalLineDetail') {
                                    $('#span_subtotal_refund').html(v.Amount);
                                } else if(v.DetailType == 'DiscountLineDetail') {
                                    var percent = v.DiscountLineDetail.PercentBased ? 'percent' : 'value';
                                    $('#discount_type_refund').val(percent);
                                    $('#percent_amount_refund').val(v.DiscountLineDetail.DiscountPercent);
                                    $('#total_discount_refund').val(v.Amount);
                                }
                            })
                        }

                        // $('#span_subtotal').html(result.invoice.TotalAmt);
                        // $('#total_discount').html(result.invoice.TotalAmt);
                        var amount_received = parseFloat(refund_json.TotalAmt) - parseFloat(refund_json.Balance); 
                        console.log(amount_received)                                   
                        amount_received = parseFloat(amount_received).toFixed(2);
                        $('span#amount_received_refund').html(amount_received);                    
                        $('#total_amt_refund').html(refund_json.TotalAmt);
                        $('#total_amt_old_refund').val(refund_json.TotalAmt);
                        $('#balance_due_refund').html(refund_json.Balance);
                        $('#balance_due_old_refund').val(refund_json.Balance);

                        get_discount('Refund');
                        
                        $('#modal_edit_refund').modal({backdrop: 'static', keyboard: false});
                    }

                    $(document).on('shown.bs.modal', '#modal_edit_invoice, #modal_edit_expense, #modal_edit_check, #modal_edit_purchase_order, #modal_edit_bill, #modal_edit_bill_payment, #modal_edit_payment, #modal_edit_sales_receipt, #modal_edit_credit_memo, #modal_edit_estimate, #modal_edit_refund', function(e) {
                        $('.dob-date-picker').datepicker({
                            autoclose: true,
                            // endDate: 'today',
                        });
                    });
                } else {                    
                    swal({
                        title: 'Information',
                        text: result.message ? result.message : result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        }); 

        // for look modal only
        // $('#modal_edit_expense').modal('show');
        // $('#modal_edit_purchase_order').modal('show');
        // $('#modal_edit_bill').modal('show');
        // $('#modal_edit_payment').modal('show');
        // $('#modal_edit_sales_receipt').modal('show');
    }

    function get_product_data(row, type, transaction_type = 'Invoice') {
        if(transaction_type == 'Invoice') {
            if(type == 'select') {
                var data = $('select#ItemName' + row).find('option:selected').data();
                $('input#Description' + row).val(data.description);
                $('input#UnitPrice' + row).val(parseFloat(data.unitprice).toFixed(2));
                $('input#Qty' + row).val(1);
            }
            var qty = $('input#Qty' + row).val();
            var unitprice = $('input#UnitPrice' + row).val();
            var total = parseFloat(qty) * parseFloat(unitprice);
            $('#totalAmount' + row).html(parseFloat(total).toFixed(2));
    
            var subtotal = 0;
            $('td[id^=totalAmount]').each(function() {
                var amount = $(this).html();
                // console.log(amount)
                subtotal += parseFloat(amount);
            })
            $('#span_subtotal').html(subtotal);
            // console.log(subtotal)
            var total_amt_old = $('input#total_amt_old').val();
            var balance_due_old = $('input#balance_due_old').val();
            var tax_amount = $('input#tax_amount').val();
            var total_discount = $('span#total_discount').html();
            var amount_received = parseFloat(total_amt_old) - parseFloat(balance_due_old);          
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax_amount) - parseFloat(total_discount);
            // console.log(amount_received);
            if(amount_received == 0) {
                $('span#total_amt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_invoice').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received').html(0);        
            } else {            
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_invoice').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }

            get_rate_data('#tax_rate', transaction_type);
            get_discount(transaction_type);
        } else if(transaction_type == 'SalesReceipt') {
            if(type == 'select') {
                var data = $('select#ItemNameSalesReceipt' + row).find('option:selected').data();
                $('input#DescriptionSalesReceipt' + row).val(data.description);
                $('input#UnitPriceSalesReceipt' + row).val(parseFloat(data.unitprice).toFixed(2));
                $('input#QtySalesReceipt' + row).val(1);
            }
            var qty = $('input#QtySalesReceipt' + row).val();
            var unitprice = $('input#UnitPriceSalesReceipt' + row).val();
            var total = parseFloat(qty) * parseFloat(unitprice);
            $('#totalAmountSalesReceipt' + row).html(parseFloat(total).toFixed(2));
    
            var subtotal = 0;
            $('td[id^=totalAmountSalesReceipt]').each(function() {
                var amount = $(this).html();
                // console.log(amount)
                subtotal += parseFloat(amount);
            })
            $('#span_subtotal_sales_receipt').html(subtotal);
            // console.log(subtotal)
            var total_amt_old = $('input#total_amt_old_sales_receipt').val();
            var balance_due_old = $('input#balance_due_old_sales_receipt').val();
            var tax_amount = $('input#tax_amount_sales_receipt').val();
            var total_discount = $('span#total_discount_sales_receipt').html();
            var amount_received = parseFloat(total_amt_old) - parseFloat(balance_due_old);          
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax_amount) - parseFloat(total_discount);
            // console.log(amount_received);
            if(amount_received == 0) {
                $('span#total_amt_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_sales_receipt').html(0);        
            } else {            
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_sales_receipt').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_sales_receipt').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }

            get_rate_data('#tax_rate_sales_receipt', transaction_type);
            get_discount(transaction_type);
        } else if(transaction_type == 'Estimate') {
            if(type == 'select') {
                var data = $('select#ItemNameEstimate' + row).find('option:selected').data();
                $('input#DescriptionEstimate' + row).val(data.description);
                $('input#UnitPriceEstimate' + row).val(parseFloat(data.unitprice).toFixed(2));
                $('input#QtyEstimate' + row).val(1);
            }
            var qty = $('input#QtyEstimate' + row).val();
            var unitprice = $('input#UnitPriceEstimate' + row).val();
            var total = parseFloat(qty) * parseFloat(unitprice);
            $('#totalAmountEstimate' + row).html(parseFloat(total).toFixed(2));
    
            var subtotal = 0;
            $('td[id^=totalAmountEstimate]').each(function() {
                var amount = $(this).html();
                // console.log(amount)
                subtotal += parseFloat(amount);
            })
            $('#span_subtotal_estimate').html(subtotal);
            // console.log(subtotal)
            var total_amt_old = $('input#total_amt_old_estimate').val();
            var balance_due_old = $('input#balance_due_old_estimate').val();
            var tax_amount = $('input#tax_amount_estimate').val();
            var total_discount = $('span#total_discount_estimate').html();
            var amount_received = parseFloat(total_amt_old) - parseFloat(balance_due_old);          
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax_amount) - parseFloat(total_discount);
            // console.log(amount_received);
            if(amount_received == 0) {
                $('span#total_amt_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_estimate').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_estimate').html(0);        
            } else {            
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_estimate').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_estimate').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_estimate').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }

            get_rate_data('#tax_rate_estimate', transaction_type);
            get_discount(transaction_type);
        } else if(transaction_type == 'Refund') {
            if(type == 'select') {
                var data = $('select#ItemNameRefund' + row).find('option:selected').data();
                $('input#DescriptionRefund' + row).val(data.description);
                $('input#UnitPriceRefund' + row).val(parseFloat(data.unitprice).toFixed(2));
                $('input#QtyRefund' + row).val(1);
            }
            var qty = $('input#QtyRefund' + row).val();
            var unitprice = $('input#UnitPriceRefund' + row).val();
            var total = parseFloat(qty) * parseFloat(unitprice);
            $('#totalAmountRefund' + row).html(parseFloat(total).toFixed(2));
    
            var subtotal = 0;
            $('td[id^=totalAmountRefund]').each(function() {
                var amount = $(this).html();
                // console.log(amount)
                subtotal += parseFloat(amount);
            })
            $('#span_subtotal_refund').html(subtotal);
            // console.log(subtotal)
            var total_amt_old = $('input#total_amt_old_refund').val();
            var balance_due_old = $('input#balance_due_old_refund').val();
            var tax_amount = $('input#tax_amount_refund').val();
            var total_discount = $('span#total_discount_refund').html();
            var amount_received = parseFloat(total_amt_old) - parseFloat(balance_due_old);          
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax_amount) - parseFloat(total_discount);
            // console.log(amount_received);
            if(amount_received == 0) {
                $('span#total_amt_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_refund').html(0);        
            } else {            
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_refund').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_refund').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }

            get_rate_data('#tax_rate_refund', transaction_type);
            get_discount(transaction_type);
        } else {
            if(type == 'select') {
                var data = $('select#ItemNameCreditMemo' + row).find('option:selected').data();
                $('input#DescriptionCreditMemo' + row).val(data.description);
                $('input#UnitPriceCreditMemo' + row).val(parseFloat(data.unitprice).toFixed(2));
                $('input#QtyCreditMemo' + row).val(1);
            }
            var qty = $('input#QtyCreditMemo' + row).val();
            var unitprice = $('input#UnitPriceCreditMemo' + row).val();
            var total = parseFloat(qty) * parseFloat(unitprice);
            $('#totalAmountCreditMemo' + row).html(parseFloat(total).toFixed(2));
    
            var subtotal = 0;
            $('td[id^=totalAmountCreditMemo]').each(function() {
                var amount = $(this).html();
                // console.log(amount)
                subtotal += parseFloat(amount);
            })
            $('#span_subtotal_credit_memo').html(subtotal);
            // console.log(subtotal)
            var total_amt_old = $('input#total_amt_old_credit_memo').val();
            var balance_due_old = $('input#balance_due_old_credit_memo').val();
            var tax_amount = $('input#tax_amount_credit_memo').val();
            var total_discount = $('span#total_discount_credit_memo').html();
            var amount_received = parseFloat(total_amt_old) - parseFloat(balance_due_old);          
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax_amount) - parseFloat(total_discount);
            // console.log(amount_received);
            if(amount_received == 0) {
                $('span#total_amt_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_credit_memo').html(0);        
            } else {            
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_credit_memo').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_credit_memo').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }

            get_rate_data('#tax_rate_credit_memo', transaction_type);
            get_discount(transaction_type);
        }
    }

    function get_rate_data(element, transaction_type = 'Invoice') { 
        if(transaction_type == 'Invoice') {
            var data = $(element).find('option:selected').data();
            $('span#tax_rate').html(data.rate + '%');
            var taxrate = parseFloat(data.rate) / 100;
            var subtotal = $('#span_subtotal').html();
            var tax = taxrate * parseFloat(subtotal);
            var total_discount = $('span#total_discount').html();
            $('input#tax_amount').val(parseFloat(tax).toFixed(2));
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
            var amount_received = $('span#amount_received').html();
            if(amount_received == 0) {
                $('span#total_amt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_invoice').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received').html(0);
            } else {
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_invoice').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }
        } else if(transaction_type == 'Estimate') {
            var data = $(element).find('option:selected').data();
            $('span#tax_rate_html_estimate').html(data.rate + '%');
            var taxrate = parseFloat(data.rate) / 100;
            var subtotal = $('#span_subtotal_estimate').html();
            var tax = taxrate * parseFloat(subtotal);
            var total_discount = $('span#total_discount_estimate').html();
            $('input#tax_amount_estimate').val(parseFloat(tax).toFixed(2));
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
            var amount_received = $('span#amount_received_estimate').html();
            if(amount_received == 0) {
                $('span#total_amt_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_estimate').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_estimate').html(0);
            } else {
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_estimate').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_estimate').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_estimate').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_estimate').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }
        } else if(transaction_type == 'Refund') {
            var data = $(element).find('option:selected').data();
            $('span#tax_rate_html_refund').html(data.rate + '%');
            var taxrate = parseFloat(data.rate) / 100;
            var subtotal = $('#span_subtotal_refund').html();
            var tax = taxrate * parseFloat(subtotal);
            var total_discount = $('span#total_discount_refund').html();
            $('input#tax_amount_refund').val(parseFloat(tax).toFixed(2));
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
            var amount_received = $('span#amount_received_refund').html();
            if(amount_received == 0) {
                $('span#total_amt_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_refund').html(0);
            } else {
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_refund').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_refund').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_refund').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }
        } else if(transaction_type == 'SalesReceipt') {
            var data = $(element).find('option:selected').data();
            $('span#tax_rate_html_sales_receipt').html(data.rate + '%');
            var taxrate = parseFloat(data.rate) / 100;
            var subtotal = $('#span_subtotal_sales_receipt').html();
            var tax = taxrate * parseFloat(subtotal);
            var total_discount = $('span#total_discount_sales_receipt').html();
            $('input#tax_amount_sales_receipt').val(parseFloat(tax).toFixed(2));
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
            var amount_received = $('span#amount_received_sales_receipt').html();
            if(amount_received == 0) {
                $('span#total_amt_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_sales_receipt').html(0);
            } else {
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_sales_receipt').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_sales_receipt').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_sales_receipt').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }
        } else {
            var data = $(element).find('option:selected').data();
            $('span#tax_rate_html_credit_memo').html(data.rate + '%');
            var taxrate = parseFloat(data.rate) / 100;
            var subtotal = $('#span_subtotal_credit_memo').html();
            var tax = taxrate * parseFloat(subtotal);
            var total_discount = $('span#total_discount_credit_memo').html();
            $('input#tax_amount_credit_memo').val(parseFloat(tax).toFixed(2));
            var total_amt_after_calculate = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
            var amount_received = $('span#amount_received_credit_memo').html();
            if(amount_received == 0) {
                $('span#total_amt_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));            
                $('span#balance_due_balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(total_amt_after_calculate).toFixed(2), true));            
                $('span#amount_received_credit_memo').html(0);
            } else {
                var balance_due_after_deduct = parseFloat(total_amt_after_calculate) - parseFloat(amount_received);
                $('span#amount_received_credit_memo').html(parseFloat(amount_received).toFixed(2));        
                $('span#total_amt_credit_memo').html(parseFloat(total_amt_after_calculate).toFixed(2));
                $('span#balance_due_credit_memo').html(parseFloat(balance_due_after_deduct).toFixed(2));
                $('span#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(balance_due_after_deduct).toFixed(2), true));
            }
        }
    }

    function get_discount(transaction_type = 'Invoice') {
        if(transaction_type == 'Invoice') {
            var discount_type = $('select#discount_type').find('option:selected').val();
            var subtotal = $('#span_subtotal').html();
            var discount = $('#percent_amount').val();
            var tax = $('input#tax_amount').val();
            var amount_received = $('span#amount_received').html();        
            if(discount_type == 'value') {
                var total_discount = parseFloat(discount);
                $('span#total_discount').html('-'+parseFloat(total_discount).toFixed(2));
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt').html(parseFloat(total).toFixed(2));
                if(amount_received == 0) {
                    $('#balance_due').html(parseFloat(total).toFixed(2));
                    $('#balance_due_invoice').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_invoice').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }
            } else {
                var total_discount = parseFloat(subtotal) * (parseFloat(discount)/100);  
                $('span#total_discount').html('-'+parseFloat(total_discount).toFixed(2));          
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt').html(parseFloat(total).toFixed(2));    
                if(amount_received == 0) {
                    $('#balance_due').html(parseFloat(total).toFixed(2));
                    $('#balance_due_invoice').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_invoice').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }        
            }
        } else if(transaction_type == 'SalesReceipt') {
            var discount_type = $('select#discount_type_sales_receipt').find('option:selected').val();
            var subtotal = $('#span_subtotal_sales_receipt').html();
            var discount = $('#percent_amount_sales_receipt').val();
            var tax =  $('input#tax_amount_sales_receipt').val();
            var amount_received = $('span#amount_received_sales_receipt').html();        
            if(discount_type == 'value') {
                var total_discount = parseFloat(discount);
                $('span#total_discount_sales_receipt').html('-'+parseFloat(total_discount).toFixed(2));
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_sales_receipt').html(parseFloat(total).toFixed(2));
                if(amount_received == 0) {
                    $('#balance_due_sales_receipt').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_sales_receipt').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }
            } else {
                var total_discount = parseFloat(subtotal) * (parseFloat(discount)/100);  
                $('span#total_discount_sales_receipt').html('-'+parseFloat(total_discount).toFixed(2));          
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_sales_receipt').html(parseFloat(total).toFixed(2));    
                if(amount_received == 0) {
                    $('#balance_due_sales_receipt').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_sales_receipt').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_sales_receipt').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }        
            }
        } else if(transaction_type == "Estimate") {
            var discount_type = $('select#discount_type_estimate').find('option:selected').val();
            var subtotal = $('#span_subtotal_estimate').html();
            var discount = $('#percent_amount_estimate').val();
            var tax =  $('input#tax_amount_estimate').val();
            var amount_received = $('span#amount_received_estimate').html();        
            if(discount_type == 'value') {
                var total_discount = parseFloat(discount);
                $('span#total_discount_estimate').html('-'+parseFloat(total_discount).toFixed(2));
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_estimate').html(parseFloat(total).toFixed(2));
                $('#amount_received_estimate').html(parseFloat(total).toFixed(2));
                if(amount_received == 0) {
                    // $('#balance_due_estimate').html(parseFloat(total).toFixed(2));
                    $('#balance_due_estimate_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    // $('#balance_due_estimate').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_estimate_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                }
            } else {
                var total_discount = parseFloat(subtotal) * (parseFloat(discount)/100);  
                $('span#total_discount_estimate').html('-'+parseFloat(total_discount).toFixed(2));          
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_estimate').html(parseFloat(total).toFixed(2)); 
                $('#amount_received_estimate').html(parseFloat(total).toFixed(2));   
                if(amount_received == 0) {
                    // $('#balance_due_estimate').html(parseFloat(total).toFixed(2));
                    $('#balance_due_estimate_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    // $('#balance_due_estimate').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_estimate_receipt').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));            
                }        
            }
        } else if(transaction_type == 'Refund') {
            var discount_type = $('select#discount_type_refund').find('option:selected').val();
            var subtotal = $('#span_subtotal_refund').html();
            var discount = $('#percent_amount_refund').val();
            var tax =  $('input#tax_amount_refund').val();
            var amount_received = $('span#amount_received_refund').html();        
            if(discount_type == 'value') {
                var total_discount = parseFloat(discount);
                $('span#total_discount_refund').html('-'+parseFloat(total_discount).toFixed(2));
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_refund').html(parseFloat(total).toFixed(2));
                $('#amount_received_refund').html(parseFloat(total).toFixed(2));
                if(amount_received == 0) {
                    $('#balance_due_refund').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_refund').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                }
            } else {
                var total_discount = parseFloat(subtotal) * (parseFloat(discount)/100);  
                $('span#total_discount_refund').html('-'+parseFloat(total_discount).toFixed(2));          
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_refund').html(parseFloat(total).toFixed(2)); 
                $('#amount_received_refund').html(parseFloat(total).toFixed(2));   
                if(amount_received == 0) {
                    $('#balance_due_refund').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_refund').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_refund').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));            
                }        
            }
        } else {
            var discount_type = $('select#discount_type_credit_memo').find('option:selected').val();
            var subtotal = $('#span_subtotal_credit_memo').html();
            var discount = $('#percent_amount_credit_memo').val();
            var tax =  $('input#tax_amount_credit_memo').val();
            var amount_received = $('span#amount_received_credit_memo').html();        
            if(discount_type == 'value') {
                var total_discount = parseFloat(discount);
                $('span#total_discount_credit_memo').html('-'+parseFloat(total_discount).toFixed(2));
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_credit_memo').html(parseFloat(total).toFixed(2));
                if(amount_received == 0) {
                    $('#balance_due_credit_memo').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_credit_memo').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }
            } else {
                var total_discount = parseFloat(subtotal) * (parseFloat(discount)/100);  
                $('span#total_discount_credit_memo').html('-'+parseFloat(total_discount).toFixed(2));          
                var total = parseFloat(subtotal) + parseFloat(tax) - parseFloat(total_discount);
                $('#total_amt_credit_memo').html(parseFloat(total).toFixed(2));    
                if(amount_received == 0) {
                    $('#balance_due_credit_memo').html(parseFloat(total).toFixed(2));
                    $('#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));
                } else {
                    var balance = parseFloat(total) - parseFloat(amount_received);
                    $('#balance_due_credit_memo').html(parseFloat(balance).toFixed(2));            
                    $('#balance_due_html_credit_memo').html(__currency_trans_from_en(parseFloat(balance).toFixed(2), true));            
                }        
            }
        }
    }

    function void_or_delete_all_sales_qb(id, sync_token, type, voidordelete, data = []) {
        $.ajax({
            method: 'POST',
            url: '/void_or_delete_all_sales_qb/' + id + '/' + sync_token + '?type=' + type + '&voidordelete=' + voidordelete,
            data: {
                data: data,
            },
            beforeSend: function() {         
                $('#pos-loader').css('display', 'inline-flex');       
            }, 
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {                 
                    swal({
                        title: 'Success',
                        text: result.msg,
                        icon: 'success'
                    })   
                    invoice_qb_table.ajax.reload();
                    all_sales_qb_table.ajax.reload();
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        });
    }

    function get_data_all_sales_qb(id, sync_token, type) {
        $.ajax({
            method: 'GET',
            url: '/get_data_all_sales_qb/' + id + '/' + sync_token + '?type=' + type,
            beforeSend: function() {         
                $('#pos-loader').css('display', 'inline-flex');       
            }, 
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {                 
                    void_or_delete_all_sales_qb(id, sync_token, type, 'void', JSON.parse(result.data));
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        });
    }

    function update_invoice() {
        var line = [];        
        $('#product_service tr').each(function(index, value) {
            line.push({
                LineNum: invoice_json.Line[index].LineNum,
                Amount: $('#totalAmount' + (index+1)).html(),
                Description: $('#Description' + (index+1)).val(),
                SalesItemLineDetail: {
                    TaxCodeRef: {
                        value: 'TAX'
                    },
                    ItemRef: {
                        name: $('#ItemName' + (index+1)).find('option:selected').text(),
                        value: $('#ItemName' + (index+1)).find('option:selected').val()
                    },
                    UnitPrice: $('#UnitPrice' + (index+1)).val(),
                    Qty: $('#Qty' + (index+1)).val(),
                },
                Id: invoice_json.Line[index].Id,
                DetailType: "SalesItemLineDetail"
            });         
        });
        line.push({
            DetailType: "SubTotalLineDetail",
            Amount: $('#span_subtotal').html(),
            SubTotalLineDetail: {}
        })
        if(parseFloat($('#total_discount').html())) {
            line.push({
                Amount: $('#total_discount').html(),
                DetailType: "DiscountLineDetail",
                DiscountLineDetail: {
                    PercentBased: $('#discount_type').val() == 'percent' ? true : false,
                    DiscountPercent: $('#percent_amount').val(),
                    DiscountAccountRef: {
                        value: "86",
                        name: "Discounts given"
                    }
                }
            })
        }

        var TxnTaxDetail = {
            TxnTaxCodeRef: {
                value: $('#tax_rate_invoice').val() == 3 ? "2" : "3"
            },
            TotalTax: $('#tax_amount').val(),
            TaxLine: [
                {
                    Amount: $('#tax_amount').val(),
                    DetailType: "TaxLineDetail",
                    TaxLineDetail: {
                        TaxRateRef: {
                            value: $('#tax_rate_invoice').val(),

                        },
                        PercentBased: true,
                        TaxPercent: $('#tax_rate_invoice').data('rate'),
                        NetAmountTaxable: $('#span_subtotal').html()
                    }
                }
            ]
        };
        var txn_date = new Date($('#invoice_date').val());
        var due_date = new Date($('#invoice_due_date').val());
        var address = $('#billing_address_invoice').val().split(/[\n]+/);        
        var bill_address = {};
        if(address) {
            bill_address = invoice_json.BillAddr;
            bill_address.Line1 = address.hasOwnProperty(0) ? address[0] : null;
            bill_address.Line2 = address.hasOwnProperty(1) ? address[1] : null;
            bill_address.Line3 = address.hasOwnProperty(2) ? address[2] : null;
            if(bill_address.hasOwnProperty('Line4')) {
                bill_address.Line4 = address.hasOwnProperty(3) ? address[3] : null;
            }
        }
             
        $.ajax({
            method: 'POST',
            url: 'update_invoice_qb',
            data: {   
                data: {                    
                    AllowIPNPayment: false,
                    AllowOnlinePayment: false,
                    AllowOnlineCreditCardPayment: false,
                    AllowOnlineACHPayment: false,
                    DocNumber: $('span#invoice_no').html(),
                    SyncToken: invoice_json.SyncToken,
                    domain: invoice_json.domain,
                    Balance: $('#balance_due').html(),
                    BillAddr: bill_address,
                    TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                    TotalAmt: $('#total_amt').html(),
                    HomeTotalAmt: $('#total_amt').html(),
                    CustomerRef: {
                        name: $('#customer_invoice').find('option:selected').text(),
                        value: $('#customer_invoice').find('option:selected').val()
                    },
                    CustomerMemo: {
                        value: $('#customer_memo').val()
                    },
                    ShipAddr: bill_address,
                    LinkedTxn: invoice_json.LinkedTxn,
                    DueDate: due_date.getFullYear() + '-' + ('0' + (due_date.getMonth()+1)).slice(-2) + '-' + ('0' + due_date.getDate()).slice(-2),
                    PrintStatus: invoice_json.PrintStatus,
                    EmailStatus: invoice_json.EmailStatus,
                    sparse: invoice_json.sparse,
                    Line: line,
                    ApplyTaxAfterDiscount: invoice_json.ApplyTaxAfterDiscount,
                    CustomField: invoice_json.CustomField,
                    Id: invoice_json.Id,
                    TxnTaxDetail: TxnTaxDetail,
                    MetaData: invoice_json.MetaData,
                    BillEmail: {
                        Address: $('#customer_email_invoice').val()
                    },
                    SalesTermRef: {
                        value: $('#terms_invoice').find('option:selected').val(),
                    }
                }                             
            },
            beforeSend: function() {
                $('#pos-loader').css('display', 'inline-flex'); 
            },
            success: function(result) {
                $('#pos-loader').css('display', 'none')
                if(result.rc == 1) {                 
                    swal({
                        title: 'Success',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                    invoice_qb_table.ajax.reload();
                    $('#modal_edit_invoice').modal('hide');
                } else {
                    swal({
                        title: 'Information',
                        text: result.msg,
                        icon: 'info',
                        // buttons: false,
                    })
                }
            },
            error: function() {
                $('#pos-loader').css('display', 'none')
                swal({
                    title: 'Warning',
                    text: "Something went wrong",
                    icon: 'warning',
                    // buttons: false,
                })
            }
        })
    }

    function update_all_sales() {
        var transaction_type = $('#transaction_type').val();        
        if(transaction_type == 'Expense') {
            var line = []; 
            var number = 0;       
            $('#product_service_expense tr').each(function(index, value) {
                var customerRef = $('#customerExpense' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerExpense' + (index+1)).find('option:selected').text(),
                    'value': $('#customerExpense' + (index+1)).find('option:selected').val(),
                } : {};
                // console.log('Product');                        
                var index_json = expense_json.Line.findIndex(p => p.hasOwnProperty('ItemBasedExpenseLineDetail') ? p.ItemBasedExpenseLineDetail.ItemRef.value == $('#ItemName' + (index+1)).find('option:selected').val() : -1);                                
                // console.log(line);
                // if(line.length > 0) {
                    line.push({
                        LinkedTxn: expense_json.Line[index_json].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text(),
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: expense_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });        
                    number++; 
                /* } else {
                    line.push({
                        LinkedTxn: expense_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemName' + (index+1)).find('option:selected').text(),
                                value: $('#ItemName' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            ItemRef: {
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val(),
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text()
                            },
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: expense_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });   
                } */
            });

            $('#category_list tr').each(function(index, value) {
                var customerRef = $('#customerCategory' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerCategory' + (index+1)).find('option:selected').text(),
                    'value': $('#customerCategory' + (index+1)).find('option:selected').val(),
                } : {};
                // if(line.length > 0) {
                    // console.log('category');
                    // console.log(line);
                    // var index_json = expense_json.Line.findIndex(p => p.hasOwnProperty('AccountBasedExpenseLineDetail') ? p.AccountBasedExpenseLineDetail.AccountRef.value == $('#categoryName' + (index+1)).find('option:selected').val() : -1);  
                    var index_json = expense_json.Line.findIndex(function(item, i){
                        if(item.DetailType == 'AccountBasedExpenseLineDetail') {
                            return item.AccountBasedExpenseLineDetail.AccountRef.value === $('#categoryName' + (index+1)).find('option:selected').val()
                        }
                    });                                        
                    
                    line.push({
                        LinkedTxn: expense_json.Line[index_json].LinkedTxn,
                        Amount: $('#totalAmountCategory' + (index+1)).val(),
                        Description: $('#categoryDescription' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: expense_json.Line[index_json].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });        
                /* } else {
                    line.push({
                        LinkedTxn: expense_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: expense_json.Line[index].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });   
                } */
            });

            // console.log(line);
            // swal('Mantap');
            var txn_date = new Date($('#payment_date').val());                                   
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        AccountRef: {
                            value: $('#payment_account').find('option:selected').val(),
                            name: $('#payment_account').find('option:selected').text(),
                        },
                        PaymentType: expense_json.PaymentType,
                        Credit: expense_json.Credit,
                        TotalAmt: __currency_trans_from_en($('#span_subtotal_expense').html(), false),
                        PurchaseEx: expense_json.PurchaseEx,
                        domain: expense_json.domain,
                        sparse: expense_json.sparse,
                        Id: expense_json.Id,
                        SyncToken: expense_json.SyncToken,
                        MetaData: expense_json.MetaData,
                        CustomField: expense_json.CustomField,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        Line: line,
                        PrivateNote: $('#memo').val(),
                        PaymentMethodRef: {
                            value: $('#payment_method').find('option:selected').val(),
                            name: $('#payment_method').find('option:selected').text()
                        },
                        EntityRef: {
                            value: $('#payee').find('option:selected').val(),
                            name: $('#payee').find('option:selected').text(),
                            type: 'Vendor'
                        },
                        DocNumber: $('#ref_no').val(),
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        expense_qb_table.ajax.reload();
                        $('#modal_edit_expense').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Purchase Order') {
            var line = []; 
            var number = 0;       
            $('#product_service_purchase_order tr').each(function(index, value) {
                var customerRef = $('#customerExpense' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerExpense' + (index+1)).find('option:selected').text(),
                    'value': $('#customerExpense' + (index+1)).find('option:selected').val(),
                } : {};
                // console.log('Product');                        
                var index_json = purchase_order_json.Line.findIndex(p => p.hasOwnProperty('ItemBasedExpenseLineDetail') ? p.ItemBasedExpenseLineDetail.ItemRef.value == $('#ItemName' + (index+1)).find('option:selected').val() : -1);                                
                // console.log(line);
                // if(line.length > 0) {
                    line.push({
                        // LinkedTxn: purchase_order_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text(),
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });        
                    number++; 
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemName' + (index+1)).find('option:selected').text(),
                                value: $('#ItemName' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            ItemRef: {
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val(),
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text()
                            },
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });   
                } */
            });

            $('#category_list_purchase_order tr').each(function(index, value) {
                var customerRef = $('#customerCategory' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerCategory' + (index+1)).find('option:selected').text(),
                    'value': $('#customerCategory' + (index+1)).find('option:selected').val(),
                } : {};
                // if(line.length > 0) {
                    // console.log('category');
                    // console.log(line);
                    // var index_json = purchase_order_json.Line.findIndex(p => p.hasOwnProperty('AccountBasedExpenseLineDetail') ? p.AccountBasedExpenseLineDetail.AccountRef.value == $('#categoryName' + (index+1)).find('option:selected').val() : -1);  
                    var index_json = purchase_order_json.Line.findIndex(function(item, i){
                        if(item.DetailType == 'AccountBasedExpenseLineDetail') {
                            return item.AccountBasedExpenseLineDetail.AccountRef.value === $('#categoryName' + (index+1)).find('option:selected').val()
                        }
                    });                                        
                    
                    line.push({
                        // LinkedTxn: purchase_order_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountCategory' + (index+1)).val(),
                        Description: $('#categoryDescription' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: purchase_order_json.Line[index_json].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });        
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });   
                } */
            });

            $.each(purchase_order_json.CustomField, function(k,v) {
                purchase_order_json.CustomField[k].StringValue = $('#' + v.Name.replace(/\s/, '').replace('#', '')).val();
            })

            // console.log(purchase_order_json.CustomField);

            var doc_number = $('#doc_number_purchase_order').html().split(' #');
            if(doc_number.length > 1) {
                doc_number = doc_number[1];
            } else {
                doc_number = null;
            }

            // console.log(doc_number);
            var vendor_address = $('#mailing_address').val().split('\n');
            var vendor_address_1 = vendor_address.hasOwnProperty('1') ? vendor_address[1].split(', ') : '';
            var vendorAddr = {};
            if(purchase_order_json.hasOwnProperty("VendorAddr")) {
                vendorAddr = {
                    Id: purchase_order_json.VendorAddr.Id,
                    Line1: vendor_address.hasOwnProperty('0') ? vendor_address[0] : purchase_order_json.VendorAddr.Line1,
                    City: vendor_address.hasOwnProperty('1') ? vendor_address[1] : purchase_order_json.VendorAddr.City,
                    CountrySubDivisionCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[0] : purchase_order_json.VendorAddr.CountrySubDivisionCode,
                    PostalCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[1] : purchase_order_json.VendorAddr.PostalCode,
                    Lat: purchase_order_json.VendorAddr.Lat,
                    Long: purchase_order_json.VendorAddr.Long
                }
            }

            var ship_address = $('#shipping_address').val().split('\n');
            var shipAddr = {
                Id: purchase_order_json.ShipAddr.Id,
                Line1: ship_address.hasOwnProperty(0) ? ship_address[0] : purchase_order_json.ShipAddr.Line1,
                Line2: ship_address.hasOwnProperty(1) ? ship_address[1] : purchase_order_json.ShipAddr.Line2,
                Line3: ship_address.hasOwnProperty(2) ? ship_address[2] : purchase_order_json.ShipAddr.Line3,                
            };
            // console.log(line);
            // swal('Mantap');
            var txn_date = new Date($('#purchase_order_date').val());            
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        domain: purchase_order_json.domain,
                        sparse: purchase_order_json.sparse,
                        Id: purchase_order_json.Id,
                        SyncToken: purchase_order_json.SyncToken,
                        MetaData: purchase_order_json.MetaData,
                        CustomField: purchase_order_json.CustomField,
                        DocNumber: doc_number,
                        CurrencyRef: purchase_order_json.CurrencyRef,
                        Line: line,
                        VendorRef: {
                            value: $('#vendor_purchase_order').find('option:selected').val(),
                            name: $('#vendor_purchase_order').find('option:selected').text(),
                        },                        
                        TotalAmt: __currency_trans_from_en($('#span_subtotal_purchase_order').html(), false),                        
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        PrivateNote: $('#memo_purchase_order').val(),
                        Memo: $('#privateNote_purchase_order').val(),
                        APAccountRef: {
                            value: "33",
                            name: "Accounts Payable (A/P)"
                        },
                        VendorAddr: vendorAddr,
                        ShipAddr: shipAddr,
                        POStatus: 'Open',
                        LinkedTxn: purchase_order_json.LinkedTxn,
                        ShipMethodRef: {
                            value: $('#ship_via').val(),
                            name: $('#ship_via').val()
                        },
                        POEmail: {
                            Address: $('#email_purchase_order').val(),
                        }
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        expense_qb_table.ajax.reload();
                        $('#modal_edit_purchase_order').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Check') {
            var line = []; 
            var number = 0;       
            $('#product_service_check tr').each(function(index, value) {
                var customerRef = $('#customerExpense' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerExpense' + (index+1)).find('option:selected').text(),
                    'value': $('#customerExpense' + (index+1)).find('option:selected').val(),
                } : {};
                // console.log('Product');                        
                var index_json = check_json.Line.findIndex(p => p.hasOwnProperty('ItemBasedExpenseLineDetail') ? p.ItemBasedExpenseLineDetail.ItemRef.value == $('#ItemName' + (index+1)).find('option:selected').val() : -1);                                
                // console.log(line);
                // if(line.length > 0) {
                    line.push({
                        // LinkedTxn: check_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text(),
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: check_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });        
                    number++; 
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemName' + (index+1)).find('option:selected').text(),
                                value: $('#ItemName' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            ItemRef: {
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val(),
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text()
                            },
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });   
                } */
            });

            $('#category_list_check tr').each(function(index, value) {
                var customerRef = $('#customerCategory' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerCategory' + (index+1)).find('option:selected').text(),
                    'value': $('#customerCategory' + (index+1)).find('option:selected').val(),
                } : {};
                // if(line.length > 0) {
                    // console.log('category');
                    // console.log(line);
                    // var index_json = purchase_order_json.Line.findIndex(p => p.hasOwnProperty('AccountBasedExpenseLineDetail') ? p.AccountBasedExpenseLineDetail.AccountRef.value == $('#categoryName' + (index+1)).find('option:selected').val() : -1);  
                    var index_json = check_json.Line.findIndex(function(item, i){
                        if(item.DetailType == 'AccountBasedExpenseLineDetail') {
                            return item.AccountBasedExpenseLineDetail.AccountRef.value === $('#categoryName' + (index+1)).find('option:selected').val()
                        }
                    });                                        
                    
                    line.push({
                        // LinkedTxn: purchase_order_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountCategory' + (index+1)).val(),
                        Description: $('#categoryDescription' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: check_json.Line[index_json].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });        
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });   
                } */
            });

            /* $.each(purchase_order_json.CustomField, function(k,v) {
                purchase_order_json.CustomField[k].StringValue = $('#' + v.Name.replace(/\s/, '').replace('#', '')).val();
            }) */

            // console.log(purchase_order_json.CustomField);

            /* var doc_number = $('#doc_number_purchase_order').html().split(' #');
            if(doc_number.length > 1) {
                doc_number = doc_number[1];
            } else {
                doc_number = null;
            } */

            // console.log(doc_number);
            var vendor_address = $('#mailing_address_check').val().split('\n');
            var vendor_address_1 = vendor_address.hasOwnProperty('1') ? vendor_address[1].split(', ') : '';
            var vendorAddr = {};
            if(check_json.hasOwnProperty('RemitToAddr')) {
                vendorAddr = {
                    Id: check_json.RemitToAddr.Id,
                    Line1: vendor_address.hasOwnProperty('0') ? vendor_address[0] : check_json.RemitToAddr.Line1,
                    City: vendor_address.hasOwnProperty('1') ? vendor_address[1] : check_json.RemitToAddr.City,
                    CountrySubDivisionCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[0] : check_json.RemitToAddr.CountrySubDivisionCode,
                    PostalCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[1] : check_json.RemitToAddr.PostalCode,
                    Lat: check_json.RemitToAddr.Lat,
                    Long: check_json.RemitToAddr.Long
                }            
            }

            // console.log(line);
            // swal('Mantap');
            var txn_date = new Date($('#payment_date_check').val());            
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        AccountRef: {
                            value: $('#bank_account_check').find('option:selected').val(),
                            name: $('#bank_account_check').find('option:selected').text(),
                        },
                        PaymentType: check_json.PaymentType,
                        Credit: check_json.Credit,
                        TotalAmt: __currency_trans_from_en($('#span_subtotal_check').html(), false),
                        PurchaseEx: check_json.PurchaseEx,
                        domain: check_json.domain,
                        sparse: check_json.sparse,
                        Id: check_json.Id,
                        SyncToken: check_json.SyncToken,
                        MetaData: check_json.MetaData,
                        CustomField: check_json.CustomField,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        Line: line,
                        PrivateNote: $('#memo_check').val(),
                        EntityRef: {
                            value: $('#payee_check').find('option:selected').val(),
                            name: $('#payee_check').find('option:selected').text(),
                            type: 'Vendor'
                        },
                        DocNumber: $('#check_no').val(),
                        RemitToAddr: vendorAddr
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        expense_qb_table.ajax.reload();
                        $('#modal_edit_check').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Bill') {
            var line = []; 
            var number = 0;       
            $('#product_service_bill tr').each(function(index, value) {
                var customerRef = $('#customerExpense' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerExpense' + (index+1)).find('option:selected').text(),
                    'value': $('#customerExpense' + (index+1)).find('option:selected').val(),
                } : {};
                // console.log('Product');                        
                var index_json = bill_json.Line.findIndex(p => p.hasOwnProperty('ItemBasedExpenseLineDetail') ? p.ItemBasedExpenseLineDetail.ItemRef.value == $('#ItemName' + (index+1)).find('option:selected').val() : -1);                                
                // console.log(line);
                // if(line.length > 0) {
                    line.push({
                        // LinkedTxn: check_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text(),
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: bill_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });        
                    number++; 
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        ItemBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },
                            ItemRef: {
                                name: $('#ItemName' + (index+1)).find('option:selected').text(),
                                value: $('#ItemName' + (index+1)).find('option:selected').val()
                            },                            
                            CustomerRef: customerRef,
                            BillableStatus: $('#billable' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            ItemRef: {
                                value: $('#ItemExpense' + (index+1)).find('option:selected').val(),
                                name: $('#ItemExpense' + (index+1)).find('option:selected').text()
                            },
                            UnitPrice: $('#UnitPriceExpense' + (index+1)).val(),
                            Qty: $('#QtyExpense' + (index+1)).val(),
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "ItemBasedExpenseLineDetail"
                    });   
                } */
            });

            $('#category_list_bill tr').each(function(index, value) {
                var customerRef = $('#customerCategory' + (index+1)).find('option:selected').val() ? {
                    'name': $('#customerCategory' + (index+1)).find('option:selected').text(),
                    'value': $('#customerCategory' + (index+1)).find('option:selected').val(),
                } : {};
                // if(line.length > 0) {
                    // console.log('category');
                    // console.log(line);
                    // var index_json = purchase_order_json.Line.findIndex(p => p.hasOwnProperty('AccountBasedExpenseLineDetail') ? p.AccountBasedExpenseLineDetail.AccountRef.value == $('#categoryName' + (index+1)).find('option:selected').val() : -1);  
                    var index_json = bill_json.Line.findIndex(function(item, i){
                        if(item.DetailType == 'AccountBasedExpenseLineDetail') {
                            return item.AccountBasedExpenseLineDetail.AccountRef.value === $('#categoryName' + (index+1)).find('option:selected').val()
                        }
                    });                                        
                    
                    line.push({
                        // LinkedTxn: purchase_order_json.Line[index_json].hasOwnProperty('LinkedTxn') ? purchase_order_json.Line[index_json].LinkedTxn : null,
                        Amount: $('#totalAmountCategory' + (index+1)).val(),
                        Description: $('#categoryDescription' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: bill_json.Line[index_json].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });        
                /* } else {
                    line.push({
                        LinkedTxn: purchase_order_json.Line[index].LinkedTxn,
                        Amount: $('#totalAmountExpense' + (index+1)).html(),
                        Description: $('#DescriptionExpense' + (index+1)).val(),
                        AccountBasedExpenseLineDetail: {
                            TaxCodeRef: {
                                value: $('#taxable' + (index+1)).is(':checked') ? 'TAX' : 'NOT'
                            },                           
                            CustomerRef: customerRef,
                            BillableStatus: $('#billableCategory' + (index+1)).is(':checked') ? 'Billable' : 'NotBillable',
                            AccountRef: {
                                value: $('#categoryName' + (index+1)).find('option:selected').val(),
                                name: $('#categoryName' + (index+1)).find('option:selected').text()
                            }
                        },
                        Id: purchase_order_json.Line[index].Id,
                        DetailType: "AccountBasedExpenseLineDetail"
                    });   
                } */
            });

            var vendor_address = $('#mailing_address_check').val().split('\n');
            var vendor_address_1 = vendor_address.hasOwnProperty('1') ? vendor_address[1].split(', ') : '';
            vendorAddr = {};
            if(bill_json.hasOwnProperty('VendorAddr')) {
                vendorAddr = {
                    Id: bill_json.VendorAddr.Id,
                    Line1: vendor_address.hasOwnProperty('0') ? vendor_address[0] : bill_json.VendorAddr.Line1,
                    City: vendor_address.hasOwnProperty('1') ? vendor_address[1] : bill_json.VendorAddr.City,
                    CountrySubDivisionCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[0] : bill_json.VendorAddr.CountrySubDivisionCode,
                    PostalCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[1] : bill_json.VendorAddr.PostalCode,
                    Lat: bill_json.VendorAddr.Lat,
                    Long: bill_json.VendorAddr.Long
                } 
            }

            var txn_date = new Date($('#bill_date').val());            
            var due_date = new Date($('#due_date_bill').val());            
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        DocNumber: $('#bill_no').val(),
                        SyncToken: bill_json.SyncToken,
                        domain: bill_json.domain,
                        APAccountRef: bill_json.APAccountRef,
                        VendorRef: {
                            value: $('#vendor_bill').find('option:selected').val(),
                            name: $('#vendor_bill').find('option:selected').text(),                            
                        },
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        DueDate: due_date.getFullYear() + '-' + ('0' + (due_date.getMonth()+1)).slice(-2) + '-' + ('0' + due_date.getDate()).slice(-2),
                        TotalAmt: __currency_trans_from_en($('#span_subtotal_bill').html(), false),
                        CurrencyRef: bill_json.CurrencyRef,
                        PrivateNote: $('#memo_bill').val(),
                        SalesTermRef: {
                            value: $('#term_bill').val()
                        },
                        sparse: bill_json.sparse,
                        Line: line,
                        Balance: __currency_trans_from_en($('#amount_bill').html(), false),
                        Id: bill_json.Id,
                        MetaData: bill_json.MetaData,
                        VendorAddr: vendorAddr,                               
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        expense_qb_table.ajax.reload();
                        $('#modal_edit_bill').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Bill Payment') {
            var pay_type = null;
            var bill_account = $('#bank_account_bill_payment').val();
            if(bill_account == '41' || bill_account == '42') {
                pay_type = 'Credit Card';
            } else if(bill_account == '36' || bill_account == '35') {
                pay_type = 'Check';
            } else {
                pay_type = 'Cash';            
            }
            var txn_date = new Date($('#bill_payment_date').val());   
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        VendorRef: {
                            value: $('#vendor_bill_payment').find('option:selected').val(),
                            name: $('#vendor_bill_payment').find('option:selected').text(),                            
                        },
                        PayType: pay_type, 
                        CheckPayment: {
                            BankAccountRef: {
                                value: $('#bank_account_bill_payment').find('option:selected').val(),
                                name: $('#bank_account_bill_payment').find('option:selected').text(),
                            }
                        },
                        TotalAmt: __currency_trans_from_en($('#amount_payment').val(), false),                        
                        Line: [
                            {
                                Amount: __currency_trans_from_en($('#amount_payment').val(), false),
                                LinkedTxn: [
                                    {
                                        TxnId: bill_payment_json.Id,
                                        TxnType: 'Bill'
                                    }
                                ]
                            }
                        ],
                        PrivateNote: $('#memo_bill_payment').val(),                                                       
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        expense_qb_table.ajax.reload();
                        $('#modal_edit_bill_payment').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Payment') {
            var line = [];
            $('#payment_list tr').each(function(k, v) {
                var index_json = payment_json.Line.findIndex(p => p.hasOwnProperty('LinkedTxn') ? p.LinkedTxn[0].TxnId == $('#invoice_id' + (k+1)).val() : -1);
                line.push({
                    Amount: $('#amount_payment' + (k+1)).val(),
                    LinkedTxn: [
                        {
                            TxnId: $('#invoice_id' + (k+1)).val(),
                            TxnType: "Invoice"
                        }
                    ],
                    LineEx: payment_json.Line[index_json].LineEx,
                })
            });

            var txn_date = new Date($('#bill_payment_date').val());

            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                    
                        CustomerRef: {
                            value: $('#customer_payment').find('option:selected').val(),
                            name: $('#customer_payment').find('option:selected').text(),                            
                        },
                        DepositToAccountRef: {                            
                            value: $('#deposit_payment_account').find('option:selected').val(),                                                        
                        },
                        PaymentMethodRef: {
                            value: $('#payment_date_payment').find('option:selected').val()
                        },
                        PaymentRefNum: $('#reference_no_payment').val(), 
                        TotalAmt: __currency_trans_from_en($('#amount_received_payment_input').val(), false),                        
                        UnappliedAmt: __currency_trans_from_en($('#amount_to_credit_payment').val(), false),
                        ProcessPayment: payment_json.ProcessPayment,
                        domain: payment_json.domain,
                        sparse: payment_json.sparse,
                        Id: payment_json.Id,
                        SyncToken: payment_json.SyncToken,
                        MetaData: payment_json.MetaData,                        
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        CurrencyRef: payment_json.CurrencyRef,
                        LinkedTxn: payment_json.LinkedTxn,                        
                        Line: line,
                        PrivateNote: $('#memo_ayment').val(),                                                       
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        all_sales_qb_table.ajax.reload();
                        $('#modal_edit_payment').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Sales Receipt') {
            var line = [];        
            $('#product_service_sales_receipt tr').each(function(index, value) {
                line.push({
                    LineNum: sales_receipt_json.Line[index].LineNum,
                    Amount: $('#totalAmountSalesReceipt' + (index+1)).html(),
                    Description: $('#DescriptionSalesReceipt' + (index+1)).val(),
                    SalesItemLineDetail: {
                        TaxCodeRef: {
                            value: 'TAX'
                        },
                        ItemRef: {
                            name: $('#ItemNameSalesReceipt' + (index+1)).find('option:selected').text(),
                            value: $('#ItemNameSalesReceipt' + (index+1)).find('option:selected').val()
                        },
                        UnitPrice: $('#UnitPriceSalesReceipt' + (index+1)).val(),
                        Qty: $('#QtySalesReceipt' + (index+1)).val(),
                    },
                    Id: sales_receipt_json.Line[index].Id,
                    DetailType: "SalesItemLineDetail"
                });         
            });
            line.push({
                DetailType: "SubTotalLineDetail",
                Amount: $('#span_subtotal_sales_receipt').html(),
                SubTotalLineDetail: {}
            })
            if(parseFloat($('#total_discount_sales_receipt').html())) {
                line.push({
                    Amount: $('#total_discount_sales_receipt').html(),
                    DetailType: "DiscountLineDetail",
                    DiscountLineDetail: {
                        PercentBased: $('#discount_type_sales_receipt').val() == 'percent' ? true : false,
                        DiscountPercent: $('#percent_amount_sales_receipt').val(),
                        DiscountAccountRef: {
                            value: "86",
                            name: "Discounts given"
                        }
                    }
                })
            }

            var TxnTaxDetail = {
                TxnTaxCodeRef: {
                    value: $('#tax_rate_sales_receipt').val() == 3 ? "2" : "3"
                },
                TotalTax: $('#tax_amount').val(),
                TaxLine: [
                    {
                        Amount: $('#tax_amount').val(),
                        DetailType: "TaxLineDetail",
                        TaxLineDetail: {
                            TaxRateRef: {
                                value: $('#tax_rate_sales_receipt').val(),
                            },
                            PercentBased: true,
                            TaxPercent: $('#tax_rate_sales_receipt').data('rate'),
                            NetAmountTaxable: $('#span_subtotal_sales_receipt').html()
                        }
                    }
                ]
            };
            var txn_date = new Date($('#sales_receipt_date').val());
            var address = $('#billing_address_sales_receipt').val().split(/[\n]+/);        
            var bill_address = {};
            if(address) {
                bill_address = sales_receipt_json.BillAddr;
                bill_address.Line1 = address.hasOwnProperty(0) ? address[0] : null;
                bill_address.Line2 = address.hasOwnProperty(1) ? address[1] : null;
                bill_address.Line3 = address.hasOwnProperty(2) ? address[2] : null;                
                if(bill_address.hasOwnProperty('Line4')) {
                    bill_address.Line4 = address.hasOwnProperty(3) ? address[3] : null;
                }
            }
                
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                                            
                        DocNumber: $('reference_no_sales_receipt').val(),
                        SyncToken: sales_receipt_json.SyncToken,
                        domain: sales_receipt_json.domain,
                        Balance: __currency_trans_from_en($('#balance_due_sales_receipt').html(), false),
                        BillAddr: bill_address,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        TotalAmt: __currency_trans_from_en($('#total_amt_sales_receipt').html(), false),                        
                        CustomerRef: {
                            value: $('#customer_sales_receipt').find('option:selected').val(),
                            name: $('#customer_sales_receipt').find('option:selected').text(),
                        },
                        CustomerMemo: {
                            value: $('#customer_memo_sales_receipt').val()
                        },
                        PrivateNote: $('#private_note_sales_receipt').val(),                        
                        ShipAddr: bill_address,
                        LinkedTxn: sales_receipt_json.LinkedTxn,                        
                        PrintStatus: sales_receipt_json.PrintStatus,
                        EmailStatus: sales_receipt_json.EmailStatus,
                        sparse: sales_receipt_json.sparse,
                        Line: line,
                        ApplyTaxAfterDiscount: sales_receipt_json.ApplyTaxAfterDiscount,
                        CustomField: sales_receipt_json.CustomField,
                        Id: sales_receipt_json.Id,
                        TxnTaxDetail: TxnTaxDetail,
                        MetaData: sales_receipt_json.MetaData,
                        BillEmail: {
                            Address: $('#customer_email_sales_receipt').val()
                        },
                        PaymentMethodRef: {
                            value: $('#payment_method_sales_receipt').find('option:selected').val(),
                            name: $('#payment_method_sales_receipt').find('option:selected').text(),
                        },
                        DepositToAccountRef: {
                            value: $('#deposit_sales_receipt_account').find('option:selected').val(),
                            name: $('#deposit_sales_receipt_account').find('option:selected').text()
                        }
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        all_sales_qb_table.ajax.reload();
                        $('#modal_edit_sales_receipt').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == "Credit Memo") {
            var line = [];        
            $('#product_service_credit_memo tr').each(function(index, value) {
                line.push({
                    LineNum: creditmemo_json.Line[index].LineNum,
                    Amount: $('#totalAmountCreditMemo' + (index+1)).html(),
                    Description: $('#DescriptionCreditMemo' + (index+1)).val(),
                    SalesItemLineDetail: {
                        TaxCodeRef: {
                            value: 'TAX'
                        },
                        ItemRef: {
                            name: $('#ItemNameCreditMemo' + (index+1)).find('option:selected').text(),
                            value: $('#ItemNameCreditMemo' + (index+1)).find('option:selected').val()
                        },
                        UnitPrice: $('#UnitPriceCreditMemo' + (index+1)).val(),
                        Qty: $('#QtyCreditMemo' + (index+1)).val(),
                    },
                    Id: creditmemo_json.Line[index].Id,
                    DetailType: "SalesItemLineDetail"
                });         
            });
            line.push({
                DetailType: "SubTotalLineDetail",
                Amount: $('#span_subtotal_credit_memo').html(),
                SubTotalLineDetail: {}
            })
            if(parseFloat($('#total_discount_credit_memo').html())) {
                line.push({
                    Amount: $('#total_discount_credit_memo').html(),
                    DetailType: "DiscountLineDetail",
                    DiscountLineDetail: {
                        PercentBased: $('#discount_type_credit_memo').val() == 'percent' ? true : false,
                        DiscountPercent: $('#percent_amount_credit_memo').val(),
                        DiscountAccountRef: {
                            value: "86",
                            name: "Discounts given"
                        }
                    }
                })
            }

            var TxnTaxDetail = {
                TxnTaxCodeRef: {
                    value: $('#tax_rate_credit_memo').val() == 3 ? "2" : "3"
                },
                TotalTax: $('#tax_amount').val(),
                TaxLine: [
                    {
                        Amount: $('#tax_amount').val(),
                        DetailType: "TaxLineDetail",
                        TaxLineDetail: {
                            TaxRateRef: {
                                value: $('#tax_rate_credit_memo').val(),
                            },
                            PercentBased: true,
                            TaxPercent: $('#tax_rate_credit_memo').data('rate'),
                            NetAmountTaxable: $('#span_subtotal_credit_memo').html()
                        }
                    }
                ]
            };
            var txn_date = new Date($('#credit_memo_date').val());
            var address = $('#billing_address_credit_memo').val().split(/[\n]+/);        
            var bill_address = {};
            if(address) {
                bill_address = creditmemo_json.BillAddr;
                bill_address.Line1 = address.hasOwnProperty(0) ? address[0] : null;
                bill_address.Line2 = address.hasOwnProperty(1) ? address[1] : null;
                bill_address.Line3 = address.hasOwnProperty(2) ? address[2] : null;                
                if(bill_address.hasOwnProperty('Line4')) {
                    bill_address.Line4 = address.hasOwnProperty(3) ? address[3] : null;
                }
            }
                
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                                            
                        // DocNumber: $('reference_no_credit_memo').val(),
                        SyncToken: creditmemo_json.SyncToken,
                        domain: creditmemo_json.domain,
                        Balance: __currency_trans_from_en($('#balance_due_credit_memo').html(), false),
                        BillAddr: bill_address,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        TotalAmt: __currency_trans_from_en($('#total_amt_credit_memo').html(), false),                        
                        CustomerRef: {
                            value: $('#customer_credit_memo').find('option:selected').val(),
                            name: $('#customer_credit_memo').find('option:selected').text(),
                        },
                        CustomerMemo: {
                            value: $('#customer_memo_credit_memo').val()
                        },
                        PrivateNote: $('#private_note_credit_memo').val(),                        
                        ShipAddr: bill_address,
                        LinkedTxn: creditmemo_json.LinkedTxn,                        
                        PrintStatus: creditmemo_json.PrintStatus,
                        EmailStatus: creditmemo_json.EmailStatus,
                        sparse: creditmemo_json.sparse,
                        Line: line,
                        ApplyTaxAfterDiscount: creditmemo_json.ApplyTaxAfterDiscount,
                        CustomField: creditmemo_json.CustomField,
                        Id: creditmemo_json.Id,
                        TxnTaxDetail: TxnTaxDetail,
                        MetaData: creditmemo_json.MetaData,
                        BillEmail: {
                            Address: $('#customer_email_credit_memo').val()
                        },
                        PaymentMethodRef: {
                            value: $('#payment_method_credit_memo').find('option:selected').val(),
                            name: $('#payment_method_credit_memo').find('option:selected').text(),
                        },
                        DepositToAccountRef: {
                            value: $('#deposit_credit_memo_account').find('option:selected').val(),
                            name: $('#deposit_credit_memo_account').find('option:selected').text()
                        }
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        all_sales_qb_table.ajax.reload();
                        $('#modal_edit_credit_memo').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == "Estimate") {
            var line = [];        
            $('#product_service_estimate tr').each(function(index, value) {
                line.push({
                    LineNum: estimate_json.Line[index].LineNum,
                    Amount: $('#totalAmountEstimate' + (index+1)).html(),
                    Description: $('#DescriptionEstimate' + (index+1)).val(),
                    SalesItemLineDetail: {
                        TaxCodeRef: {
                            value: 'TAX'
                        },
                        ItemRef: {
                            name: $('#ItemNameEstimate' + (index+1)).find('option:selected').text(),
                            value: $('#ItemNameEstimate' + (index+1)).find('option:selected').val()
                        },
                        UnitPrice: $('#UnitPriceEstimate' + (index+1)).val(),
                        Qty: $('#QtyEstimate' + (index+1)).val(),
                    },
                    Id: estimate_json.Line[index].Id,
                    DetailType: "SalesItemLineDetail"
                });         
            });
            line.push({
                DetailType: "SubTotalLineDetail",
                Amount: $('#span_subtotal_estimate').html(),
                SubTotalLineDetail: {}
            })
            if(parseFloat($('#total_discount_estimate').html())) {
                line.push({
                    Amount: $('#total_discount_estimate').html(),
                    DetailType: "DiscountLineDetail",
                    DiscountLineDetail: {
                        PercentBased: $('#discount_type_estimate').val() == 'percent' ? true : false,
                        DiscountPercent: $('#percent_amount_estimate').val(),
                        DiscountAccountRef: {
                            value: "86",
                            name: "Discounts given"
                        }
                    }
                })
            }

            var TxnTaxDetail = {
                TxnTaxCodeRef: {
                    value: $('#tax_rate_estimate').val() == 3 ? "2" : "3"
                },
                TotalTax: $('#tax_amount').val(),
                TaxLine: [
                    {
                        Amount: $('#tax_amount').val(),
                        DetailType: "TaxLineDetail",
                        TaxLineDetail: {
                            TaxRateRef: {
                                value: $('#tax_rate_estimate').val(),
                            },
                            PercentBased: true,
                            TaxPercent: $('#tax_rate_estimate').data('rate'),
                            NetAmountTaxable: $('#span_subtotal_estimate').html()
                        }
                    }
                ]
            };
            var txn_date = new Date($('#estimate_date').val());
            var expiration_date = new Date($('#estimate_expiration_date').val());              
            var vendor_address = $('#billing_address_estimate').val().split('\n');
            var vendor_address_1 = vendor_address.hasOwnProperty('1') ? vendor_address[1].split(', ') : '';
            var vendorAddr = {};
            if(estimate_json.hasOwnProperty('BillAddr')) {
                vendorAddr = {
                    Id: estimate_json.BillAddr.Id,
                    Line1: vendor_address.hasOwnProperty('0') ? vendor_address[0] : estimate_json.BillAddr.Line1,
                    City: vendor_address.hasOwnProperty('1') ? vendor_address[1] : estimate_json.BillAddr.City,
                    CountrySubDivisionCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[0] : estimate_json.BillAddr.CountrySubDivisionCode,
                    PostalCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[1] : estimate_json.BillAddr.PostalCode,
                    Lat: estimate_json.BillAddr.Lat,
                    Long: estimate_json.BillAddr.Long
                }            
            }                      
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                                            
                        // DocNumber: $('reference_no_estimate').val(),
                        ExpirationDate: expiration_date.getFullYear() + '-' + ('0' + (expiration_date.getMonth()+1)).slice(-2) + '-' + ('0' + expiration_date.getDate()).slice(-2),
                        AcceptedBy: $('#update_status_estimate_by').val(),
                        AcceptedDate: $('#update_status_estimate_date').val(),
                        domain: estimate_json.domain,
                        sparse: estimate_json.sparse,
                        Id: estimate_json.Id,
                        SyncToken: estimate_json.SyncToken,
                        MetaData: estimate_json.MetaData,
                        CustomField: estimate_json.CustomField,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        TxnStatus: $('#txn_status_estimate').val(),
                        Line: line,
                        TxnTaxDetail: TxnTaxDetail,
                        Balance: __currency_trans_from_en($('#balance_due_estimate').html(), false),
                        CustomerRef: {
                            value: $('#customer_estimate').find('option:selected').val(),
                            name: $('#customer_estimate').find('option:selected').text(),
                        },
                        CustomerMemo: {
                            value: $('#customer_memo_estimate').val()
                        },
                        BillAddr: bill_address,
                        ShipAddr: bill_address,
                        FreeFormAddress: estimate_json.FreeFormAddress,
                        TotalAmt: __currency_trans_from_en($('#total_amt_estimate').html(), false),                        
                        ApplyTaxAfterDiscount: estimate_json.ApplyTaxAfterDiscount,
                        PrintStatus: estimate_json.PrintStatus,
                        EmailStatus: estimate_json.EmailStatus,
                        CurrencyRef: estimate_json.CurrencyRef,
                        BillEmail: {
                            Address: $('#customer_email_estimate').val()
                        },
                        PrivateNote: $('#private_note_estimate').val(),                        
                        /* LinkedTxn: estimate_json.LinkedTxn,                        
                        PaymentMethodRef: {
                            value: $('#payment_method_estimate').find('option:selected').val(),
                            name: $('#payment_method_estimate').find('option:selected').text(),
                        },
                        DepositToAccountRef: {
                            value: $('#deposit_estimate_account').find('option:selected').val(),
                            name: $('#deposit_estimate_account').find('option:selected').text()
                        } */
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        all_sales_qb_table.ajax.reload();
                        $('#modal_edit_estimate').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else if(transaction_type == 'Refund') {
            var line = [];        
            $('#product_service_refund tr').each(function(index, value) {
                line.push({
                    LineNum: refund_json.Line[index].LineNum,
                    Amount: $('#totalAmountRefund' + (index+1)).html(),
                    Description: $('#DescriptionRefund' + (index+1)).val(),
                    SalesItemLineDetail: {
                        TaxCodeRef: {
                            value: 'TAX'
                        },
                        ItemRef: {
                            name: $('#ItemNameRefund' + (index+1)).find('option:selected').text(),
                            value: $('#ItemNameRefund' + (index+1)).find('option:selected').val()
                        },
                        UnitPrice: $('#UnitPriceRefund' + (index+1)).val(),
                        Qty: $('#QtyRefund' + (index+1)).val(),
                    },
                    Id: refund_json.Line[index].Id,
                    DetailType: "SalesItemLineDetail"
                });         
            });
            line.push({
                DetailType: "SubTotalLineDetail",
                Amount: $('#span_subtotal_refund').html(),
                SubTotalLineDetail: {}
            })
            if(parseFloat($('#total_discount_refund').html())) {
                line.push({
                    Amount: $('#total_discount_refund').html(),
                    DetailType: "DiscountLineDetail",
                    DiscountLineDetail: {
                        PercentBased: $('#discount_type_refund').val() == 'percent' ? true : false,
                        DiscountPercent: $('#percent_amount_refund').val(),
                        DiscountAccountRef: {
                            value: "86",
                            name: "Discounts given"
                        }
                    }
                })
            }

            var TxnTaxDetail = {
                TxnTaxCodeRef: {
                    value: $('#tax_rate_refund').val() == 3 ? "2" : "3"
                },
                TotalTax: $('#tax_amount').val(),
                TaxLine: [
                    {
                        Amount: $('#tax_amount').val(),
                        DetailType: "TaxLineDetail",
                        TaxLineDetail: {
                            TaxRateRef: {
                                value: $('#tax_rate_refund').val(),
                            },
                            PercentBased: true,
                            TaxPercent: $('#tax_rate_refund').data('rate'),
                            NetAmountTaxable: $('#span_subtotal_refund').html()
                        }
                    }
                ]
            };
            var txn_date = new Date($('#refund_date').val());
            var vendor_address = $('#billing_address_refund').val().split('\n');
            var vendor_address_1 = vendor_address.hasOwnProperty('1') ? vendor_address[1].split(', ') : '';
            var vendorAddr = {};
            if(refund_json.hasOwnProperty('BillAddr')) {
                vendorAddr = {
                    Id: refund_json.BillAddr.Id,
                    Line1: vendor_address.hasOwnProperty('0') ? vendor_address[0] : refund_json.BillAddr.Line1,
                    City: vendor_address.hasOwnProperty('1') ? vendor_address[1] : refund_json.BillAddr.City,
                    CountrySubDivisionCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[0] : refund_json.BillAddr.CountrySubDivisionCode,
                    PostalCode: vendor_address_1.hasOwnProperty('1') ? vendor_address_1[1].split(' ')[1] : refund_json.BillAddr.PostalCode,
                    Lat: refund_json.BillAddr.Lat,
                    Long: refund_json.BillAddr.Long
                }            
            }
                
            $.ajax({
                method: 'POST',
                url: 'update_all_sales_qb?type=' + transaction_type,
                data: {   
                    data: {                                            
                        DocNumber: $('reference_no_refund').val(),
                        SyncToken: refund_json.SyncToken,
                        domain: refund_json.domain,
                        Balance: __currency_trans_from_en($('#balance_due_refund').html(), false),
                        BillAddr: bill_address,
                        TxnDate: txn_date.getFullYear() + '-' + ('0' + (txn_date.getMonth()+1)).slice(-2) + '-' + ('0' + txn_date.getDate()).slice(-2),
                        TotalAmt: __currency_trans_from_en($('#total_amt_refund').html(), false),                        
                        CustomerRef: {
                            value: $('#customer_refund').find('option:selected').val(),
                            name: $('#customer_refund').find('option:selected').text(),
                        },
                        CustomerMemo: {
                            value: $('#customer_memo_refund').val()
                        },
                        PrivateNote: $('#private_note_refund').val(),                        
                        ShipAddr: bill_address,
                        LinkedTxn: refund_json.LinkedTxn,                        
                        PrintStatus: refund_json.PrintStatus,
                        EmailStatus: refund_json.EmailStatus,
                        sparse: refund_json.sparse,
                        Line: line,
                        ApplyTaxAfterDiscount: refund_json.ApplyTaxAfterDiscount,
                        CustomField: refund_json.CustomField,
                        Id: refund_json.Id,
                        TxnTaxDetail: TxnTaxDetail,
                        MetaData: refund_json.MetaData,
                        BillEmail: {
                            Address: $('#customer_email_refund').val()
                        },
                        PaymentMethodRef: {
                            value: $('#payment_method_refund').find('option:selected').val(),
                            name: $('#payment_method_refund').find('option:selected').text(),
                        },
                        DepositToAccountRef: {
                            value: $('#deposit_refund_account').find('option:selected').val(),
                            name: $('#deposit_refund_account').find('option:selected').text()
                        }
                    }                             
                },
                beforeSend: function() {
                    $('#pos-loader').css('display', 'inline-flex'); 
                },
                success: function(result) {
                    $('#pos-loader').css('display', 'none')
                    if(result.rc == 1) {                 
                        swal({
                            title: 'Success',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                        all_sales_qb_table.ajax.reload();
                        $('#modal_edit_refund').modal('hide');
                    } else {
                        swal({
                            title: 'Information',
                            text: result.msg,
                            icon: 'info',
                            // buttons: false,
                        })
                    }
                },
                error: function() {
                    $('#pos-loader').css('display', 'none')
                    swal({
                        title: 'Warning',
                        text: "Something went wrong",
                        icon: 'warning',
                        // buttons: false,
                    })
                }
            })
        } else {
            swal({
                title: 'Information',
                text: 'Under Construcsion',
                icon: 'info'
            })
        }
    }

    function calculate_subtotal_expense(element, type) {        
        var subtotal = 0;
        if(type == 'Expense') {
            $('#category_list tr').each(function(index, value) {
                var amount = $('#totalAmountCategory' + (index+1)).val();
                subtotal+= parseFloat(amount);
            })
            $('td[id^=totalAmountExpense]').each(function(index, value) {
                var unitprice = $(this).prev().children().val();
                var qty = $(this).prev().prev().children().val();
                var amount = parseFloat(unitprice) * parseFloat(qty);
                $(this).html(parseFloat(amount).toFixed(2));
                subtotal+= parseFloat(amount);
            })
            // console.log(subtotal);
            $('td#span_subtotal_expense').html(parseFloat(subtotal).toFixed(2));
        } else if(type == 'Purchase Order') {
            $('#category_list_purchase_order tr').each(function(index, value) {
                var amount = $('#totalAmountCategory' + (index+1)).val();
                subtotal+= parseFloat(amount);
            })
            $('td[id^=totalAmountExpense]').each(function(index, value) {
                var unitprice = $(this).prev().children().val();
                var qty = $(this).prev().prev().children().val();
                var amount = parseFloat(unitprice) * parseFloat(qty);
                $(this).html(parseFloat(amount).toFixed(2));
                subtotal+= parseFloat(amount);
            })
            // console.log(subtotal);
            $('td#span_subtotal_purchase_order').html(parseFloat(subtotal).toFixed(2));
        } else if(type == 'Check') {
            $('#category_list_check tr').each(function(index, value) {
                var amount = $('#totalAmountCategory' + (index+1)).val();
                subtotal+= parseFloat(amount);
            })
            $('td[id^=totalAmountExpense]').each(function(index, value) {
                var unitprice = $(this).prev().children().val();
                var qty = $(this).prev().prev().children().val();
                var amount = parseFloat(unitprice) * parseFloat(qty);
                $(this).html(parseFloat(amount).toFixed(2));
                subtotal+= parseFloat(amount);
            })
            // console.log(subtotal);
            $('#amount_check').html(__currency_trans_from_en(subtotal, true));
            $('td#span_subtotal_check').html(parseFloat(subtotal).toFixed(2));            
        } else if(type == 'Bill') {
            $('#category_list_bill tr').each(function(index, value) {
                var amount = $('#totalAmountCategory' + (index+1)).val();
                subtotal+= parseFloat(amount);
            })
            $('td[id^=totalAmountExpense]').each(function(index, value) {
                var unitprice = $(this).prev().children().val();
                var qty = $(this).prev().prev().children().val();
                var amount = parseFloat(unitprice) * parseFloat(qty);
                $(this).html(parseFloat(amount).toFixed(2));
                subtotal+= parseFloat(amount);
            })
            // console.log(subtotal);
            var balance_old = $('#subtotal_balance_old').val();
            
            if(parseFloat(balance_old) > 0) {
                var amount_bill = parseFloat(balance_old) - parseFloat(subtotal);
                if(amount_bill > 0) {
                    $('#amount_bill').html('-'+__currency_trans_from_en(amount_bill, true));
                } else {
                    $('#amount_bill').html(__currency_trans_from_en(amount_bill * -1, true));
                }
            } else {
                $('#amount_bill').html(__currency_trans_from_en(subtotal, true));
            }

            $('td#span_subtotal_bill').html(parseFloat(subtotal).toFixed(2)); 
        } else if(type == "Payment") {
            $('#payment_list tr').each(function(index, value) {
                var amount = $('#amount_payment' + (index+1)).val();
                subtotal+= parseFloat(amount);
            })
            var amount_to_received_input = $('#amount_received_payment_input').val();            
            var amount_to_apply = $('#amount_to_apply_payment').html();
            if(amount_to_received_input != amount_to_apply) {
                $('#amount_to_apply_payment').html(__currency_trans_from_en(amount_to_received_input, true));
            }
            
            var amount_to_apply = $('#amount_to_apply_payment').html();
            var total = parseFloat(__currency_trans_from_en(amount_to_apply, false)) - parseFloat(subtotal);                    
            $('#amount_to_credit_payment').html(__currency_trans_from_en(parseFloat(total).toFixed(2), true));            
        }
    }

    function estimate_status(val) {        
        if(val == 'Pending') {
            $('#estimate_by').addClass('hide');
            $('#update_status_estimate_by').val('');

            $('#estimate_date_div').addClass('hide');
            $('#update_status_estimate_date').val('');
        } else {
            $('#estimate_by').removeClass('hide');
            $('#update_status_estimate_by').val(estimate_json.AcceptedBy);

            $('#estimate_date_div').removeClass('hide');
            $('#update_status_estimate_date').val(format_date(estimate_json.AcceptedDate));
        }        
    }

    function sync_quickbooks() {
        swal({
            title: 'Information',
            text: 'This Process May Take littler longer than regular sync process, Please do not CLOSE or REFRESH your browser during this process.',
            icon: 'info',
            buttons: {
                cancel: "CANCEL",
                confirm: "START SYNC"
            },                      
        }).then((confirmed) => {
            if (confirmed) {   
                $.ajax({
                    method: 'GET',
                    url: '/quickbooks-auth',
                    dataType: 'json',
                    data: {
                        product_locations: $('#product_locations_quickbooks').val(),
                        // checkmarks: $("input[name='checkmarks_walmart[]']:checked").serializeArray()
                    },
                    beforeSend: function() {
                        $('#pos-loader').css('display', 'inline-flex')
                        // swal('Information', 'This process may take litle bit long time, please do not close or refresh the browser', 'info')
                    },
                    success: function (result) {
                        Pace.stop();
                        console.log(result);
                        $('#pos-loader').css('display', 'none')
                        // console.log(result)
                        var message = '<p>'+result.message;
                        var icon = 'info'
                        var title = 'Information'
                        /* if(result.data) {
                            var inserted = 0;
                            var updated = 0;
                            $.each(result.data, function(k, v) {
                                $.each(v, function(k1, v1) {
                                    // console.log(v1)
                                    if(v1.status == 2) {
                                        updated++;
                                    } else {
                                        inserted++;
                                    }                        
                                })
                            })
    
                            message+= '<br>' + inserted + ' Products Imported and Created <br>' + updated + ' Products Updated and Synced</p>';
    
                            icon = 'success'
                            title = 'Success'
                        }  */
                        var msg = document.createElement('div');
                        msg.innerHTML = message;
                        swal({
                            title: title,                            
                            content: msg,
                            icon: icon,
                            // buttons: true,
                            dangerMode: true,
                        })               
                        expense_qb_table.ajax.reload();
                        customer_qb_table.ajax.reload();
                        invoice_qb_table.ajax.reload();
                        products_qb_table.ajax.reload();
                        all_sales_qb_table.ajax.reload();
                    },
                }).fail(function(xhr, status, q) {
                    console.log(xhr);
                    Pace.stop();
                    $('#pos-loader').css('display', 'none')
                    // alert(xhr.responseText)            
                    swal({
                        title: 'Information',
                        text: xhr.responseText,
                        icon: 'info',
                        // buttons: false,
                    })
                });
                //Commented by Paligu
            }
        });
    }

    function get_input(val, tipe) {        
        if(val == '1') {
            if(tipe == 'bigcommerce') {
                // bigcommerce
                $('#quickbooks_api_url').css('display', 'block')
                $('#quickbooks_api_access_token').css('display', 'block')
                $('#quickbooks_api_key').css('display', 'block')
                $('#quickbooks_api_secret').css('display', 'block')
                $('#quickbooks_space').addClass('col-sm-3')
            }
            if(tipe == 'zero') {
                // zero
                $('#zero_api_url').css('display', 'block')
                $('#zero_api_access_token').css('display', 'block')
                $('#zero_api_key').css('display', 'block')
                $('#zero_api_secret').css('display', 'block')
                $('#zero_space').addClass('col-sm-3')
            }
            if(tipe == 'myob') {
                // woo commerce
                $('#myob_api_url').css('display', 'block')
                $('#myob_api_access_token').css('display', 'block')
                $('#myob_api_key').css('display', 'block')
                $('#myob_api_secret').css('display', 'block')
                $('#myob_space').addClass('col-sm-3')
            }
        } else {
            if(tipe == 'bigcommerce') {
                // big commerce
                $('#quickbooks_api_url').css('display', 'none')
                $('#quickbooks_api_access_token').css('display', 'none')
                $('#quickbooks_api_key').css('display', 'none')
                $('#quickbooks_api_secret').css('display', 'none')
                $('#quickbooks_space').removeClass('col-sm-3')
            }
            if(tipe == 'zero') {
                // zero
                $('#zero_api_url').css('display', 'none')
                $('#zero_api_access_token').css('display', 'none')
                $('#zero_api_key').css('display', 'none')
                $('#zero_api_secret').css('display', 'none')
                $('#zero_space').removeClass('col-sm-3')
            }
            if(tipe == 'myob') {
                // woo commerce
                $('#myob_api_url').css('display', 'none')
                $('#myob_api_access_token').css('display', 'none')
                $('#myob_api_key').css('display', 'none')
                $('#myob_api_secret').css('display', 'none')
                $('#myob_space').removeClass('col-sm-3')
            }
        }
    }
</script>
@endsection