<style>
    .panel-default {
        min-height: 550px;
    }

    #TopContainer {
        background: #ddd;
        padding: 12px 6px;
    }

    .DropDownForForms>.dropdown-menu {
        width: 100%;
        height: 200px;
        max-height: 200px;
        overflow-y: scroll;
    }

    .DropDownForForms>.dropdown-menu {
        height: auto;
        cursor: pointer;
        overflow-y: auto;
    }

    .DropDownForForms>button>input {
        position: absolute;
        left: 5;
        top: 0;
        width: 90%;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
        padding: 0;
        border: 0;
        background: transparent;
    }

    .dropdown-menu>li>a {

        color: #000 !Important;
        opacity: 1;
    }


    .control-label {
        font-size: 14px !important;
        color: rgb(70, 70, 70) !important;
        opacity: 1 !important;
    }

    .form-horizontal .form-group .control-label {
        white-space: nowrap;
    }

    .ValueSpan {
        height: 35px;
        display: block;
        padding: 6px 6px;
        font-size: 18px;
        font-family: "Segoe UI", Arial, sans-serif;
    }

    /*#ledgerTable_filter,#ledgerTable_length{
        display: none
    }*/
    #ledgerTable th {
        color: #444;
        background: #ddd;
        text-align: center;
        border-top: 1px solid #4c0870;
    }

    #ledgerTable td {
        text-align: center;
    }

    .panel.panel-default {
        border: 1px solid #4c0870;
    }

    .bg-master-lighter {
        border: none;
        background-color: #fff;
        border-top: 1px solid #ddd;
    }

    .form-horizontal .form-group {
        border-bottom: 1px solid #4c0870;
    }

    @media print {
        .print-only {
            display: block;
        }

        h3 {
            font-size: 18px !important;
        }

        h4 {
            font-size: 16px !important;
            /*line-height: 23px !important;*/
        }

        .table thead tr th,
        .table tbody tr td {
            font-size: 1.1em !important;
        }

        /*        .table thead tr th,.table tbody tr td{
                    border:2px solid #000 !important;
                }
                .table-bordered{
                    border:2px solid #000 !important;
                }
                .table thead tr >th,.table tbody tr td{
                    font-size: 0.8em !important;
                }*/

    }

    .advance_search {
        margin-left: 5px !important;
        margin-right: 5px !important;
        margin-bottom: 0px !important;
    }
</style>
<script>
    //    function AddCommas(val) {
    //        val = parseFloat(val.toString()).toString();
    //        while (/(\d+)(\d{3})/.test(val.toString())) {
    //            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    //        }
    //        return val.replace(/\.0$|\.00$/, "") || "0";
    //    }
    //    function FixNumber(val) {
    //        return AddCommas(parseFloat(val + "").toXFixed(2));
    //    }
</script>
<script src="<?php echo THEME_PATH; ?>/plugins/moment/moment.min.js"></script>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">

        <div class="panel-body">
            <div class="row">
                <div class="row form-group advance_search">
                    <div class="card-group horizontal " id="accordion" role="tablist" aria-multiselectable="true">
                        <div class="card card-default m-b-0">
                            <div class="card-header " role="tab" id="headingOne">
                                <h4 class="card-title">
                                    <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne" class="collapsed btn btn-search">
                                        <span class="filter-title"> <i class="fa fa-search"></i><?php echo CommonLanguage::getMessage('advanced_search'); ?></span>
                                    </a>
                                </h4>
                            </div>
                            <div id="collapseOne" class="collapse" role="tabcard" aria-labelledby="headingOne" aria-expanded="false" style="">
                                <div class="card-block">
                                    <div class="row p-15">
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('Date') ?></label>
                                            <input id="range_date" type="text" class="form-control" readonly name="range_date">
                                        </div>
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('due_date') ?></label>
                                            <input id="range_duedate" type="text" class="form-control" readonly name="range_duedate">
                                        </div>

                                        <div class="col-md-3">
                                            <div class="row">
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_jv') ?></label></div>
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_jv') ?></label></div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6"><input type="number" min="1" id="from_jv" class="form-control full-width"></div>
                                                <div class="col-md-6"><input type="number" min="1" id="to_jv" class="form-control full-width"></div>
                                            </div>

                                        </div>
                                        <div class="col-md-3">
                                            <div class="row">
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_account') ?></label></div>
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_account') ?></label></div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6"><input type="number" min="1" id="from_account" class="form-control full-width"></div>
                                                <div class="col-md-6"><input type="number" min="1" id="to_account" class="form-control full-width"></div>
                                            </div>

                                        </div>
                                    </div>
                                    <div class="row p-15">
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                            <input type="hidden" class="full-width" id="job_id" />
                                        </div>

                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('multi_accounts') ?></label>
                                            <input type="hidden" class="full-width" id="multi_accounts" />
                                        </div>
                                        <div class="col-md-3 trans_curr_div">
                                            <label><?php echo CommonLanguage::getMessage('trans_in_currency'); ?></label>
                                            <input type="hidden" class="full-width" id="trans_in_currrency" />
                                            <?php // echo Forms::CurrencyDropDown(1, 'complete') 
                                            ?>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="row">
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('from_amount') ?></label></div>
                                                <div class="col-md-6"><label><?php echo CommonLanguage::getMessage('to_amount') ?></label></div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6"><input type="number" min="0" step="any" id="from_amount" class="form-control full-width"></div>
                                                <div class="col-md-6"><input type="number" min="0" step="any" id="to_amount" class="form-control full-width"></div>
                                            </div>

                                        </div>
                                    </div>
                                    <div class="row p-15">
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('entry_type') ?></label>
                                            <input type="hidden" class="full-width" id="ref_type" />
                                        </div>
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('family_accounts') ?></label>
                                            <input type="hidden" class="full-width" id="family_acc" />
                                        </div>
                                        <div class="col-md-2">
                                            <label><?php echo CommonLanguage::getMessage('users'); ?></label>
                                            <select id="users" class="full-width Account_Code " multiple data-init-plugin="select2">
                                                <?php foreach ($users as $user) : ?>
                                                    <option value="<?php echo $user['User_ID']; ?>"><?php echo $user['User_Name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2 ">
                                            <label><?php echo CommonLanguage::getMessage('Transaction_Type'); ?></label>
                                            <select id="TypeTrans" class="full-width Transaction" data-init-plugin="select2">
                                                <option value="All"><?php print CommonLanguage::getMessage('All'); ?></option>
                                                <option value="Credit"><?php print CommonLanguage::getMessage('credit'); ?></option>
                                                <option value="Debit"><?php print CommonLanguage::getMessage('debit'); ?></option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label><?php echo CommonLanguage::getMessage('currency'); ?></label>
                                            <?php echo Forms::CurrencyDropDown(1, 'complete') ?>
                                        </div>
                                    </div>
                                    <div class="row p-15">
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('type'); ?></label>
                                            <select id="transaction_type" class="full-width" multiple data-init-plugin="select2">
                                                <option value=""><?php echo CommonLanguage::getMessage('All') ?></option>
                                                <option value="inv"><?php echo CommonLanguage::getMessage('invoice') ?></option>
                                                <option value="pur"><?php echo CommonLanguage::getMessage('purchase') ?></option>
                                                <option value="pay"><?php echo CommonLanguage::getMessage('payment') ?></option>
                                                <option value="rec"><?php echo CommonLanguage::getMessage('receipt') ?></option>
                                                <option value="mjv"><?php echo CommonLanguage::getMessage('manual_jv') ?></option>
                                                <option value="exp"><?php echo CommonLanguage::getMessage('expense') ?></option>

                                            </select>
                                        </div>
                                        <div class="col-md-3 <?php echo $permissions->hasPermission('Branches') ? '':'hidden'; ?>">
                                            <label><?php print CommonLanguage::getMessage('branch'); ?></label>

                                            <input class=" full-width" id="branch_id" name="branch_id" type="hidden"   />


                                        </div>
                                        <div class="col-md-3">
                                            <label><?php echo CommonLanguage::getMessage('projects') ?></label>
                                            <input type="hidden" class="full-width" id="project_ids" />
                                        </div>
                                        <?php if ($is_actual) { ?>
                                            <div class="col-md-1">
                                                <label><?php print CommonLanguage::getMessage('actual_only'); ?></label>
                                                <input type="checkbox" id="actual_only" name="actual_only" />
                                            </div>
                                        <?php }
                                        if (smc_session()['default_setting']['show_related_acc']) { ?>
                                            <div class="col-md-2" style="display:grid;">
                                                <label><?php print CommonLanguage::getMessage('related_acc'); ?></label>
                                                <input type="checkbox" checked='checked' id="related_acc" name="related_acc" />
                                            </div>
                                        <?php } ?>

                                        <!--                                        <div class="col-md-1">
                                                                                    <label><?php print CommonLanguage::getMessage('multi_year'); ?></label>
                                                                                    <input type="checkbox"  id="multi_year" name="multi_year"/>
                                                                                </div>-->
                                    </div>
                                    <div class="row p-15">
                                        <div class=" col-md-2 ">
                                            <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                                            <input type="hidden" name="salesman_id" id="salesman_id" class="full-width" />
                                        </div>
                                        <div class=" col-md-2 ">
                                            <label><?php print CommonLanguage::getMessage('road_customer'); ?></label>
                                            <input type="hidden" name="pos_customer_id" id="pos_customer_id" class="full-width" />
                                        </div>
                                        <div class="col-md-2 pull-right">
                                            <button id="Generate_Report" type="button" class="btn btn-complete pull-right" data-toggle="dropdown" aria-expanded="false">
                                                <?php print CommonLanguage::getMessage('generate_report'); ?></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div>
                </div>



                <div class="col-md-12">
                    <div class="panel panel-default">

                        <div id="TopContainer">

                            <div class="row Row1 callout callout-info col-md-5 col-xs-5 form-horizontal">
                                <div class="form-group">
                                    <label for="fname" class="col-sm-4 control-label"><?php print CommonLanguage::getMessage('account_name'); ?></label>
                                    <div class="col-sm-8 col-xs-8">
                                        <input type="text" id="Account_Name" class="form-control" name="Account_Name" required="" aria-required="true">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="fname" class="col-sm-4 control-label"><?php print CommonLanguage::getMessage('account_number'); ?></label>
                                    <div class="col-sm-8">
                                        <input type="text" id="Account_Number" class="form-control" name="Account_Number" required="" aria-required="true">
                                    </div>
                                </div>
                            </div>
                            <div class="row Row1 callout callout-info col-md-5 col-xs-5 form-horizontal pull-right" style="margin: 20px;">

                                <div class="form-group" style="padding:0;">
                                    <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('opening_balance'); ?></label>
                                    <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                        <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                                    </div>
                                    <div class="col-sm-7">
                                        <span id="PreviousBalance" class="ValueSpan"> 0</span>
                                    </div>
                                </div>
                                <div class="form-group" style="padding:0;">
                                    <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('current_balance'); ?></label>
                                    <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                        <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                                    </div>
                                    <div class="col-sm-7">
                                        <span id="Current_Balance" class="ValueSpan"> 0</span>
                                    </div>
                                </div>
                                <div class="form-group" style="padding:0;">
                                    <label for="fname" class="col-sm-4 col-xs-4 control-label"><?php print CommonLanguage::getMessage('overall_balance'); ?></label>
                                    <div class="col-sm-1 col-xs-3" style="margin-top: 6px; font-size: 20px;">
                                        <span class="totalCurr"><?php echo $defCurrencySymbol; ?></span>
                                    </div>
                                    <div class="col-sm-7">
                                        <span id="OverAll" class="ValueSpan">0</span>
                                    </div>
                                </div>
                            </div>
                            <div style="clear:both"></div>
                        </div>
                        <div class="box-body no-padding table-responsive">
                            <table class="table table-hover" id="ledgerTable">
                                <thead>
                                    <tr>
                                        <th><?php print CommonLanguage::getMessage('Date'); ?></th>
                                        <th><?php print CommonLanguage::getMessage('due_date'); ?></th>
                                        <th><?php print CommonLanguage::getMessage('jv'); ?>#</th>
                                        <th><?php echo CommonLanguage::getMessage('check'); ?>&nbsp;#</th>
                                        <th><?php print CommonLanguage::getMessage('ref'); ?>#</th>
                                        <th><?php print CommonLanguage::getMessage('user_ref'); ?>#</th>
                                        <th style="min-width: 70px"><?php print CommonLanguage::getMessage('description'); ?></th>
                                        <th style="min-width: 70px"><?php print CommonLanguage::getMessage('job'); ?></th>
                                        <th class='ledger-debit-col'><?php print CommonLanguage::getMessage('debit'); ?></th>
                                        <th class='ledger-credit-col'><?php print CommonLanguage::getMessage('credit'); ?></th>
                                        <th><?php print CommonLanguage::getMessage('balance'); ?></th>
                                        <?php if (smc_session()['default_setting']['activate_second_currency'] == 1) { ?>
                                            <th class='ledger-loc-debit-col'><?php print CommonLanguage::getMessage('debit') . ' ' . smc_session()['local_currency_symbol']; ?></th>
                                            <th class='ledger-loc-credit-col'><?php print CommonLanguage::getMessage('credit') . ' ' . smc_session()['local_currency_symbol']; ?></th>
                                            <th><?php print CommonLanguage::getMessage('balance') . ' ' . smc_session()['local_currency_symbol']; ?></th>
                                            <th class='ledger-sec-debit-col'><?php print CommonLanguage::getMessage('debit') . ' ' . smc_session()['second_currency']['symbol']; ?></th>
                                            <th class='ledger-sec-credit-col'><?php print CommonLanguage::getMessage('credit') . ' ' . smc_session()['second_currency']['symbol']; ?></th>
                                            <th><?php print CommonLanguage::getMessage('balance') . ' ' . smc_session()['second_currency']['symbol']; ?></th>
                                        <?php } ?>
                                        <th><?php print CommonLanguage::getMessage('overall_balance'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="transactions">

                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </div>

        </div>
    </div>
</div>


<script type="text/javascript">
    var TotalLang = <?php echo json_encode(CommonLanguage::getMessage('total')); ?>,
        CurrentTotalLang = <?php echo json_encode(CommonLanguage::getMessage('current_balance')); ?>;
    var general_ledger = <?php echo json_encode(CommonLanguage::getMessage('general_ledger')); ?>;
    var general_ledger_ar = <?php echo json_encode(CommonLanguage::getMessage('general_ledger', 'ar')); ?>;
    var today = <?php echo json_encode($today) ?>,
        fromdate = <?php echo json_encode($from_day) ?>,
        is_actual = <?php echo json_encode($is_actual) ?>,
        Ismatch = <?php echo json_encode($Ismatches) ?>,
        code = <?php echo json_encode($Account_ID) ?>,
        activate_second_currency = <?php echo json_encode(smc_session()['default_setting']['activate_second_currency']); ?>,
        account_name = <?php echo json_encode($account_name) ?>;
    is_customer_supplier = <?php echo json_encode($is_customer_supplier) ?>,
        ledger_msg = <?php echo json_encode(isset(smc_session()['datatable_header_temp']['ledger']) ? smc_session()['datatable_header_temp']['ledger'] : null) ?>,
        startDate = '', endDate = '';
    var startDueDate = '',
        endDueDate = '';
    var org_name = org_head[0]['Organization_Legal_Name'],
        org_phone = org_head[0]['Organization_Phone'],
        org_email = org_head[0]['Organization_Email'],
        org_address = org_head[0]['Name'] + '-' + org_head[0]['Organization_Province'];
    if (!is_actual) {
        $("#transactions").on("click", ".desc", function() {
            var link_id = $(this).parents("tr").attr("data-id"),
                link_type = $(this).parents("tr").attr("data-type"),
                link_prefix = $(this).parents("tr").attr("data-prefix"),
                url = '';
            if (link_type == 'inv') {
                url = site_link + "Inventory/ViewInvoice/" + link_id + "/0?is_pop=1";
            } else if (link_type == 'pur') {
                url = site_link + "Inventory/ViewInvoice/vendor/" + link_id + "/0?is_pop=1";
            } else if (link_type == 'pay') {
                url = site_link + "ACC/ViewReceipt/" + link_id + "?is_pop=1";
            } else if (link_type == 'rec') {
                url = site_link + "ACC/ViewReceipt/Receipt/" + link_id + "?is_pop=1";
            } else if (link_type == 'exp') {
                url = site_link + "ACC/view_expense/" + link_id + "?is_pop=1";
            } else if (link_type == 'dwt') {
                url = site_link + "ACC/view_deposit_withdrawal/" + link_id + "?is_pop=1";
            } else if (link_type == 'cco') {
                url = site_link + "Inventory/view_customer_coupon/" + link_id + "?is_pop=1";
            } else if (link_type == 'sin') {
                url = site_link + "Inventory/view_station_invoice/" + link_id + "?is_pop=1";
            } else if (link_type == 'rin' || link_type == 'rpr') {
                url = site_link + "Inventory/ViewReturnDebit/" + link_id + "?is_pop=1";
            } else if (link_type == 'cre' || link_type == 'deb') {
                url = site_link + "ACC/ViewNote/" + link_id + "?is_pop=1";
            }
            if (url != '')
                open_frame_modal(url);
        })
    }
    $(document).ready(function() {
        new Switchery($("#actual_only").get(0), {
            color: $.Pages.getColor("complete")
        });
        new Switchery($("#related_acc").get(0), {
            color: $.Pages.getColor("complete")
        });

        build_select2($("#job_id"), "ACCAjax/JobSearch", 1);
        //        build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs", 1)
        //        build_select2($("#trans_in_currrency"), "xhr/CommonSearch?col_id=Currency_ID&col_name=Currency_Name&table=tbl_common_currency", 1)
        build_select2($("#trans_in_currrency"), "xhr/CurrencySearch", 1);
        build_select2($("#multi_accounts"), ("xhr/accIDSearch?type=Payment"), 1);
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches");
        build_select2($("#project_ids"), "ACCAjax/projectSearch", 1);
        build_select2($("#ref_type"), "xhr/CommonSearch?col_id=subtype_abbrv&col_name=subtype_abbrv&table=tbl_accounting_transaction_subtype", 1);
        build_select2($("#family_acc"), "xhr/CommonSearch?col_id=family_id&col_name=family_name&table=tbl_family_accounts", 1);
        //        new Switchery($("#multi_year").get(0), {color: $.Pages.getColor("complete")})
        build_select2($("#salesman_id"), "xhr/employeeSearch")
        build_select2($("#pos_customer_id"), ("xhr/poscustomerSearch"));
        $("input[name=range_date]").daterangepicker({
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                locale: {
                    cancelLabel: 'Clear'
                },
                allowEmpty: true,
                //            autoApply: true,
                autoUpdateInput: false,
            }
            /*, function (start, end, label) {
                     //window.startDate = start.format("YYYY-MM-DD"),
                     //window.endDate = end.format("YYYY-MM-DD")
                     AjaxCall();
                     }*/
        );
        $('input[name="range_date"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            AjaxCall();
        });
        $('input[name="range_date"]').on('cancel.daterangepicker', function(ev, picker) {
            window.startDate = ''
            window.endDate = ''
            $(this).val('');
            AjaxCall();
        });
        $("input[name=range_duedate]").daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            locale: {
                cancelLabel: 'Clear'
            },
            allowEmpty: true,
            //            autoApply: true,
            autoUpdateInput: false,
        }, function(start, end, label) {
            //            window.startDueDate = start.format("YYYY-MM-DD"),
            //                    window.endDueDate = end.format("YYYY-MM-DD");
        });
        $('input[name="range_duedate"]').on('apply.daterangepicker', function(ev, picker) {
            window.startDueDate = picker.startDate.format('YYYY-MM-DD'),
                window.endDueDate = picker.endDate.format('YYYY-MM-DD');
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        });
        $('input[name="range_duedate"]').on('cancel.daterangepicker', function(ev, picker) {
            window.startDueDate = ''
            window.endDueDate = ''
            $(this).val('');
        });
        if (Ismatch) {
            var x = account_name + ' - ' + code;
            $("#Account_Number").attr("value", code)
            $("#Account_Name").attr("value", x)
            $("#Account_Name").attr("data-name", x)
            $(window).on("load", function() {
                AjaxCall();
            })
        }
        //RebuildTable();

        $("#Generate_Report").on("click", function() {
            AjaxCall();
        })


        $("#Account_Name").autocomplete({
            source: "xhr/ajaxTransaction?is_customer_supplier=" + is_customer_supplier + '&is_actual=' + is_actual,
            minLength: 1,
            select: function(event, ui) {
                var id = ui.item.id;
                var code = ui.item.code;
                $('#Account_Name').attr('data-name', ui.item.account_name);
                $('#Account_Name').val(ui.item.value + ' - ' + ui.item.Currency_Code);
                $("#Account_Number").attr("value", code);
                $("#Account_Number").attr("data-nb", code);
                AjaxCall();
            }
        }).autocomplete("instance")._renderItem = function(ul, item) {
            var $LI = $("<li>").html("<table style='height:24px;' cellspacing='0' cellpadding='0' ><tr><td ><strong>" + item.label + "</strong></td></tr></table>").appendTo(ul);
            return $LI
        }
        $("#Account_Name").autocomplete("instance")._resizeMenu = function(ul, items) {
            this.menu.element.outerWidth($("#Account_Name").width() + parseFloat($("#Account_Name").css("padding-left")) + parseFloat($("#Account_Name").css("padding-right")));
            //                            this.menu.element.outerWidth($("#Account_Name").width()-295 + parseFloat($("#Account_Name").css("padding-left")) + parseFloat($("#Account_Name").css("padding-right")) + 300);
        }
    });

    function FixFloatVal(what) {
        return what.replace(/\.0$|\.00$|\.000$/, "");
    }

    function AjaxCall() {
        var From_Date = startDate,
            To_Date = endDate,
            code = $("#Account_Number").attr("value"),
            Type = $("#TypeTrans").val(),
            Currency_ID = (parseInt($("#CurrencyDropDown button input").val()));
        $("#ledgerTable  tbody").empty()
        var AccountNumber = code || 0
        if ($("#multi_accounts").val() == '' && AccountNumber == 0 && $("#from_account").val() == '' && $("#to_account").val() == '' && $("#family_acc").val() == '')
            return false;

        var DataArr = {
            Account_Number: AccountNumber,
            From_Date: From_Date,
            To_Date: To_Date,
            Currency_ID: Currency_ID,
            Type: Type,
            actual: is_actual,
            users: $("#users").val(),
            trans_type: $("#transaction_type").val(),
            from_jv: $("#from_jv").val(),
            to_jv: $("#to_jv").val(),
            from_account: $("#from_account").val(),
            to_account: $("#to_account").val(),
            job_ids: $("#job_id").val(),
            project_ids: $("#project_ids").val(),
            multi_accounts: $("#multi_accounts").val(),
            trans_currency: $("#trans_in_currrency").val(),
            from_amount: $("#from_amount").val(),
            to_amount: $("#to_amount").val(),
            ref_type: $("#ref_type").val(),
            family_acc: $("#family_acc").val(),
            branch_id: $("#branch_id").val(),
            salesman_id: $("#salesman_id").val(),
            pos_customer_id: $("#pos_customer_id").val(),
            due_date_from: startDueDate,
            due_date_to: endDueDate,
            Actual_Only: $("#actual_only").is(":checked") ? 1 : 0,
            related_acc: $("#related_acc").is(":checked") ? 1 : 0,
            //            multi_year:$("#multi_year").is(":checked") ? 1 : 0
        }
        $.ajax({
            url: 'ACCAjax/ledgerAjax',
            method: 'GET',
            data: {
                data: DataArr
            },
            dataType: 'json',
            complete: function(data, vv) {
                console.log('data')
                console.log(data)
                $('#ledgerTable tbody').empty()
                var results = data.responseJSON;

                var results = $.map(
                    data.responseJSON,
                    function(el) {
                        return el;
                    }
                );
                var final_results = results[results.length - 2];
                var overall_results = results[results.length - 1];



                var total_debit = final_results['Debit'];
                var total_credit = final_results['Credit'];
                var Current_Balance = final_results['Current_Balance'];
                var All_Balance = final_results['All_Balance'];
                var Prev_Balance = final_results['Prev_Balance'];
                var Currency = results[results.length - 3];
                //console.log(Currency)
                var Default_Currency = Currency['Currency_Symbol'];
                $("#PreviousBalance").html(AddCommas(public_round_number(parseFloat(Prev_Balance + ""))));
                $("#Current_Balance").html(AddCommas(public_round_number(parseFloat(Current_Balance + ""))));
                $("#OverAll").html(AddCommas(public_round_number(parseFloat(All_Balance + ""))));

                $('.totalCurr').html(Default_Currency)
                //console.log(results)


                //                if(results.length <= 2)
                //                    $("#ledgerTable > tbody").append($('<tr class="odd"><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td style="display:none"></td><td valign="top" colspan="9" class="dataTables_empty PrintThisTable">No data available in table</td></tr>'));
                //    
                //    
                //    "local_debit" => $local_debit_amount,
                //                "local_credit" => $local_credit_amount,
                //                "local_balance" => $local_balance,
                //                "second_debit" => $second_debit_amount,
                //                "second_credit" => $second_credit_amount,
                //                "second_balance" => $second_balance,
                if (results.length > 3) {
                    for (var i = 0; i < (results.length) - 3; i++) {
                        var transactions = "<tr data-id='" + results[i]['main_id'] + "' data-type='" + results[i]['main_type'] + "' data-prefix = '" + results[i]['serial_prefix'] + "'>" +
                            "<td>" + results[i]["Transaction_Date"] + "</td>" +
                            "<td>" + results[i]["due_date"] + "</td>" +
                            "<td><a class='openFrame cursor' data-src='ACC/dailyJVs" + (results[i]['is_actual'] == 0 ? '/' : '/act/') + results[i]["jv"] + "?is_pop=1'><span style='color:black !important;'>" + results[i]["JV_ID"] + "</span></a></td><td>" + (results[i]["check_nb"] && results[i]["check_nb"] != 0 ? results[i]["check_nb"] : '') + "</td>" +
                            "<td>" + (results[i]['has_permission'] == 1 ? "<a class='openFrame cursor' data-src='" + results[i]['link'] + "?is_pop=1'><span style='color:black !important;'>" + results[i]["main_nb"] + "</span></a>" : results[i]["main_nb"]) + "</td>" +
                            //                                "<td>" + results[i]["main_nb"] + "</td>" +
                            "<td>" + results[i]["user_ref"] + "</td>" +
                            "<td class='desc' " + (is_actual ? '' : "style='cursor:pointer'") + " > " + results[i]["Transaction_Description"] + "</td>" +
                            "<td>" + results[i]["job_name"] + "</td>" +
                            "<td>" /*+ Default_Currency + " " */ + AddCommas(public_round_number(parseFloat(results[i]["Debit"] + ""))) + "</td>" +
                            "<td>" /*+ Default_Currency + " " */ + AddCommas(public_round_number(parseFloat(results[i]["Credit"] + ""))) + "</td>" +
                            "<td>" /*+ Default_Currency + " " */ + AddCommas(public_round_number(parseFloat(results[i]['Current_Balance'] + ""))) + "</td>";
                        if (activate_second_currency == 1) {
                            transactions += "<td>" + AddCommas(public_round_number(parseFloat(results[i]["local_debit"]))) + "</td>" +
                                "<td>" + AddCommas(public_round_number(parseFloat(results[i]["local_credit"]))) + "</td>" +
                                "<td>" + AddCommas(public_round_number(parseFloat(results[i]["local_balance"]))) + "</td>" +
                                "<td>" + AddCommas(public_round_number(parseFloat(results[i]["second_debit"]))) + "</td>" +
                                "<td>" + AddCommas(public_round_number(parseFloat(results[i]["second_credit"]))) + "</td>" +
                                "<td>" + AddCommas(public_round_number(parseFloat(results[i]["second_balance"]))) + "</td>";
                        }
                        transactions += "<td>" /*+ Default_Currency + " "*/ + AddCommas(public_round_number(parseFloat(results[i]["All_Balance"] + ""))) + "</td>" +
                            "</tr>";
                        $("#ledgerTable tbody").append(transactions);
                    }
                    var finaltr = "<tr style='color:#4c0870;'><td>&nbsp;</td><td></td><td></td><td></td><td></td><td></td><td style='font-size: 1.3em' class='bold'>" + CurrentTotalLang + "</td><td></td>" +
                        "<td style='font-size: 1.3em' class='bold'><strong>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(total_debit + ""))) + "</strong></td><td style='font-size: 1.3em' class='bold'>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(total_credit + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(Current_Balance + ""))) + "</td>";
                    if (activate_second_currency == 1) {
                        finaltr += "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(final_results['local_debit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(final_results['local_credit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(final_results['local_balance']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(final_results['second_debit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(final_results['second_credit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'><strong>" + AddCommas(public_round_number(parseFloat(final_results['second_balance']))) + "</strong></td>";
                    }
                    finaltr += "</td><td style='font-size: 1.3em' class='bold'><strong>" /* + Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(All_Balance + ""))) + "</strong></td></tr>";

                    $("#ledgerTable > tbody:last").append($(finaltr))
                    var finaltr = "<tr style='color:#4c0870;'><td>&nbsp;</td><td></td><td></td><td></td><td></td><td></td><td style='font-size: 1.3em' class='bold'>" + TotalLang + "</td><td></td>" +
                        "<td style='font-size: 1.3em' class='bold'>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(overall_results['Debit'] + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(overall_results['Credit'] + ""))) + "</td><td style='font-size: 1.3em' class='bold'>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(overall_results['Current_Balance'] + ""))) + "</td>";
                    if (activate_second_currency == 1) {
                        finaltr += "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(overall_results['local_debit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(overall_results['local_credit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(overall_results['local_balance']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'>" + AddCommas(public_round_number(parseFloat(overall_results['second_debit']))) + "</td>" +
                            "<td style='font-size: 1.3em' class='bold'><strong>" + AddCommas(public_round_number(parseFloat(overall_results['second_credit']))) + "</strong></td>" +
                            "<td style='font-size: 1.3em' class='bold'><strong>" + AddCommas(public_round_number(parseFloat(overall_results['second_balance']))) + "</strong></td>";
                    }
                    finaltr += "</td><td style='font-size: 1.3em' class='bold'><strong>" /*+ Default_Currency + ' '*/ + AddCommas(public_round_number(parseFloat(overall_results['All_Balance'] + ""))) + "</strong></td></tr>";

                    $("#ledgerTable > tbody:last").append($(finaltr))

                    //                    $(".PrintThisTableButton").attr({"data-Account": $('#Account_Name').val(), "data-title": "General Ledger", "data-balance": Default_Currency + ' ' + AddCommas(parseFloat(All_Balance + "").toXFixed(2)), "data-debit": Default_Currency + ' ' + AddCommas(parseFloat(total_debit + "").toXFixed(2)), "data-credit": Default_Currency + ' ' + AddCommas(parseFloat(total_credit + "").toXFixed(2)), "data-currency": $("#CurrencyDropDown > button>span").html(), "data-table": "#ledgerTable", "data-date": 'From :' + (From_Date) + ' To :' + (To_Date), "data-Old": Default_Currency + ' ' + AddCommas(parseFloat(Prev_Balance + "").toXFixed(2)), "data-current": Default_Currency + ' ' + AddCommas(parseFloat(Current_Balance + "").toXFixed(2))})
                    //                    $("[data-download-pdf]").attr({"data-Account": $('#Account_Name').val(), "data-title": "General Ledger", "data-balance": Default_Currency + ' ' + AddCommas(parseFloat(All_Balance + "").toXFixed(2)), "data-debit": Default_Currency + ' ' + AddCommas(parseFloat(total_debit + "").toXFixed(2)), "data-credit": Default_Currency + ' ' + AddCommas(parseFloat(total_credit + "").toXFixed(2)), "data-currency": $("#CurrencyDropDown > button>span").html(), "data-table": "#ledgerTable", "data-date": 'From :' + (From_Date) + ' To :' + (To_Date), "data-Old": Default_Currency + ' ' + AddCommas(parseFloat(Prev_Balance + "").toXFixed(2)), "data-current": Default_Currency + ' ' + AddCommas(parseFloat(Current_Balance + "").toXFixed(2))})
                }
                RebuildTable();
            }
        });
    }

    function RebuildTable() {
        console.log('$("#multi_accounts").val()')
        console.log($("#multi_accounts").val())

        $.ajax({
            url: 'ACCAjax/getAccountName',
            method: 'GET',
            data: {
                data: $("#multi_accounts").val()
            },
            dataType: 'json',
            complete: function(data, vv) {
                // console.log('data')
                // console.log(data.responseJSON[0])
                var multi_accounts_name = data.responseJSON[0];
                if(  $("#Account_Number").attr("value") != null &&  $('#Account_Name').attr('data-name')  != null)
                    multi_accounts_name+= ' ' +  $("#Account_Number").attr("value") + ' - ' +$('#Account_Name').attr('data-name') ;

                var date_from = startDate != '' ? startDate : fromdate,
                    date_to = endDate != '' ? endDate : today;
                //
                var msg = '<br/> <div style="width: 100%;"> <table style="width: 100%;" border="0"> <tr style="width: 100%;"> <td rowspan="2" style="width: 50%;"><strong>Acc. Name:&nbsp'+ multi_accounts_name+ '</strong> </td> <td style="width: 50%;text-align: center;"><strong>Currency:&nbsp'+ $('#CurrencyDropDown button span').text()+'</strong></td> </tr> <tr style="width: 100%;"> <td style="text-align: center;"><strong>Date:&nbsp'+ date_from +'-'+ date_to+'</strong></td> </tr> </table> </div> <style type="text/css"> @media print { .table tbody tr:last-child, .table tbody tr:nth-last-child(2) { font-weight: bold !important; } } </style>';

                if (ledger_msg != null) {
                    msg = ledger_msg.replace("[[account_code]]", $("#Account_Number").attr("value"))
                    msg = msg.replace("[[account_name]]", $('#Account_Name').attr('data-name'))
                    msg = msg.replace("[[currency]]", $('#CurrencyDropDown button span').text())
                    msg = msg.replace("[[start_date]]", date_from)
                    msg = msg.replace("[[end_date]]", date_to)
                }
                //
                //var print_footer = "<div class='col-xs-6'><p style='text-align:center;padding-top:15px;font-size:18px;'>Acc.Dept.Signature<br/>توقيع قسم المحاسبة</p></div><div class='col-xs-6'><p style='text-align:center;padding-top:15px;font-size:18px;'>Customer Signature<br/>توقيع الزبون</p></div>";
                var print_footer = "";
                RebuildDataTable(general_ledger + '<br/>' + general_ledger_ar, [0, 2, 3, 4, 5, 6, 7], '', [], '#ledgerTable', [], {
                    bSort: false,
                    msg: msg,
                    footer: print_footer
                });
                console.log(msg)
            }
        });


    }
</script>