<!--<style>
    .tab-pane{
        min-height: 500px;
        max-height: 500px;
        overflow-y: scroll;
    }
</style>-->
<div class="row">
    <div class="container">
        <ol class="breadcrumb">
            <li><a href="#">التقارير</a></li>
            <li class="active">النقدى الآجل{if $do == "laterNakdiPaymentSell"} بيع{elseif $do == "laterNakdiPaymentRet"} مردود{/if}</li>
        </ol>
        <div class="panel panel-default panel-m">
            <!-- Default panel contents -->
            <div class="panel-heading">
                فواتير النقدى الآجل {if $do == "laterNakdiPaymentSell"} بيع{elseif $do == "laterNakdiPaymentRet"} مردود{/if}
                <a href="{$youtubes[32]->url}" target="_blank" class="hidden-print"><img src="../views/default/assets/img/youtube.png" class="pull-left" alt="Youtube" style="width: 2%;"></a>

            </div>
            <div class="panel-body">
                <input type="hidden" id="searchvalue" value="{$Programsettingdata->searchvalue}">
                <input type="hidden" name="withNakdi" id="withNakdi" value="{$Usergroupdata->showClientAndSupplierOne}"/>
                <input type="hidden" id="defUserSaveId" value="{$user->saveid}"/>
                <input type="hidden" id="defUserSaveName" value="{$defUserSaveName}"/>
                <form class="form-inline hidden-print" action="sellbillController.php?do=show" method="post">
                    <!--<input type="hidden" name="clientid" id="clientid" value="{$Programsettingdata->laterNakdiClientId}"/>-->

                    <div class="form-group">
                        <label class="sr-only">رقم الفاتورة</label>
                        <input type="text" class="form-control search_bill" placeholder="رقم الفاتورة" name="sellbillserial" id="sellbillserial">
                    </div>
                    <div class="form-group">
                        <label class="sr-only">الرقم تسلسل الفاتورة</label>
                        <input type="text" class="form-control search_bill" placeholder="رقم تسلسل الفاتورة" name="sellbillid" id="sellbillid">
                    </div>

                    <div id="dateTimeDiv" class="form-group">
                        <div class="form-group">
                            <label class="sr-only">من التاريخ</label>
                            <div  class="input-group date form_datetime col-md-5" data-date="" data-date-format="yyyy-mm-dd  h:i:s" data-link-field="dtp_input1">
                                <input class="form-control search_bill" size="16" type="text" value="{$startDateTime}" name="from" id="from" readonly="">
                                <span class="input-group-addon " style="width: 0%;"><span class=" glyphicon glyphicon-remove col-lg-4"></span></span>
                                <span class="input-group-addon"  style="width: 0%;"><span class="glyphicon glyphicon-th col-lg-4"></span></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="sr-only">إلى التاريخ</label>
                            <div  class="input-group date form_datetime col-md-5" data-date="" data-date-format="yyyy-mm-dd  h:i:s" data-link-field="dtp_input1">
                                <input class="form-control search_bill" size="16" type="text" value="{$endDateTime}" name="to" id="to" readonly="" >
                                <span class="input-group-addon " style="width: 0%;"><span class=" glyphicon glyphicon-remove col-lg-4"></span></span>
                                <span class="input-group-addon" style="width: 0%;"><span class="glyphicon glyphicon-th col-lg-4"></span></span>
                            </div>
                        </div>
                    </div>

                    <div id="dateOnlyDiv" class="form-group">
                        <div class="form-group">
                            <label class="sr-only">من التاريخ</label>
                            <input type="text" class="form-control awdatepicker search_bill" autocomplete="off"   data-date-format="yyyy-mm-dd" name="from" id="from" value="{$startDate}">
                        </div>
                        <div class="form-group">
                            <label class="sr-only">إلى التاريخ</label>
                            <input type="text" class="form-control awdatepicker search_bill" autocomplete="off"   data-date-format="yyyy-mm-dd" name="to" id="to" value="{$endDate}">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="sr-only">بحث بـ</label>
                        <label>  <input value="dateOnly" name="search" id="searchdateOnly" type="radio" checked onclick='localStorage.setItem("search", "dateOnly");
                                window.location.reload();'>
                            تاريخ</label>
                        <label>
                            <input value="dateTime" name="search" id="searchdateTime" type="radio" onclick='localStorage.setItem("search", "dateTime");
                                    window.location.reload();'>
                            تاريخ ووقت</label>
                    </div>
                    <div class="clearfix"></div>
                    <!--<button type="submit" class="btn btn-primary">بحث</button>-->
                </form>
                <input type="hidden" id="laterNakdiPayment" value="1"/>

                <div class="row">
                    <div style="margin: 0px 37%">
                        <button type="button" class="btn btn-primary" id="refreshResultsBtn">تحديث النتائج</button>
                    </div>

                </div>

                <br/>

                <div class="row">
                    <div class="{if $do == "laterNakdiPayment"}col-lg-6{else}col-lg-12{/if}"><!-- this if is to make the two tables side by side or only one table has width of page-->
                         {if $do == "laterNakdiPayment" || $do == "laterNakdiPaymentSell"}
                         <div class="panel panel-default panel-m">
                             <!-- Default panel contents -->
                             <div class="panel-heading">مبيعات</div>
                             <div class="panel-body" style="overflow-x: scroll">

                                     <table class="table table-black" id="billTablesellNotReviewed">
                                         <thead>
                                             <tr>
                                                 <!--<th>م</th>-->
                                                 <th>رقم الفاتورة</th>
                                                 <th>العميل</th>
                                                 <th>اجمالى الفاتورة</th>
                                                 <th>المدفوع</th>
                                                 <!-- <th>الباقى</th> -->

                                                 <th>تاريخ الفاتورة</th>
                                                 <th>اسم المستخدم</th>
                                                 <th>خدمه</th>
                                                 <th>قيمة السداد	</th>
                                                 <th>نوع الدفع	</th>
                                                 <th>سداد	</th>
                                             </tr>
                                         </thead>
                                         <tbody>
                                         </tbody>
                                     </table>
                                     <br/>
                                     <div class="row">
                                         <div class="col-lg-offset-6 col-lg-6 ">
                                             <div class="well well-sm">
                                                 <h4 class="text-center">إجمالي الفواتير  <span id="totalsellNotReviewed">0</span></h4>
                                             </div>
                                         </div>
                                     </div>



                                 </div>
                                 <!-- =================================================   -->


                             </div>
                             {/if}



                             {if $do == "laterNakdiPayment"} <!-- this if is to make the two tables side by side or only one table has width of page-->
                         </div>
                         <div class="col-lg-6">
                             {/if}


                             {if $do == "laterNakdiPayment" || $do == "laterNakdiPaymentRet"}
                             <div class="panel panel-default panel-m">
                                 <!-- Default panel contents -->
                                 <div class="panel-heading">مرتجعات</div>
                                 <div class="panel-body" style="overflow-x: scroll">



                                     <table class="table table-black" id="billTableretSellNotReviewed">
                                         <thead>
                                             <tr>
                                                 <!--<th>م</th>-->
                                                 <th>رقم الفاتورة</th>
                                                 <th>العميل</th>
                                                 <th>اجمالى الفاتورة</th>
                                                 <!--                                            <th>المدفوع</th>
                                                                                             <th>الباقى</th>-->

                                                 <th>تاريخ الفاتورة</th>
                                                 <th>اسم المستخدم</th>
                                                 <!--<th>قيمة السداد	</th>-->
                                                 <th>نوع الدفع	</th>
                                                 <th>سداد	</th>
                                             </tr>
                                         </thead>
                                         <tbody>
                                         </tbody>
                                     </table>
                                     <br/>
                                     <div class="row">

                                         <div class="col-lg-offset-6 col-lg-6 ">
                                             <div class="well well-sm">
                                                 <h4 class="text-center">إجمالي الفواتير  <span id="totalretSellNotReviewed">0</span></h4>
                                             </div>
                                         </div>
                                     </div>

                                 </div>
                                 <!-- =================================================   -->


                             </div>
                             {/if}
                         </div>
                     </div>



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


        </div>

        <!-- ======================= accountstree Modal Box =========== -->
        <!-- Modal -->
        <div class="modal fade" id="choosePaymentToPrintModal" tabindex="-1" role="dialog" aria-labelledby="drinkDetailsModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content bg-modal">
                    <div class="modal-header" style="border-bottom:none">
                        <!--<button type="button" class="close pull-left" data-dismiss="modal" aria-hidden="true">&times;</button>-->
                        <h4 class="modal-title">
                            <label>يوجد دفعات سابقه على الفاتورة </label>
                        </h4>
                    </div>
                    <div class="modal-footer" style="border-top:none;padding-right: 10px;margin-top: -12px">
                        <button type="button" class="btn btn-default choosePaymentToPrint" data-choose="all">طباعه اجمالى الدفعات </button>
                        <button type="button" class="btn btn-primary choosePaymentToPrint" data-choose="current">طباعة الدفعه الحاليه</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->

        {literal}
        <script>
        if (window.matchMedia("(max-width: 767px)").matches)  {
        var buttons = [];
    }
    else{
        var buttons = [//'csv', 'pdf'
                                    {
                                        extend: "print",
                                        className: "btn dark btn-outline",
                                        text: "طباعه<i class='fa fa-print'></i>",
                                        exportOptions: {
                                            //columns: '.show-print'
                                            columns: ':visible'
                                        },
                                        customize: function (win) {
                                            $(win.document.body).find('table')
                                                    //.addClass('compact')
                                                    .css('direction', 'rtl');
                                        }
                                    }, {
                                        extend: "copy",
                                        className: "btn red btn-outline",
                                        text: "نسخ",
                                        exportOptions: {
                                            //columns: '.show-print'
                                            columns: ':visible'
                                        }
                                    }, {
                                        extend: "excel",
                                        className: "btn yellow btn-outline ",
                                        text: "اكسل",
                                        exportOptions: {
                                            //columns: '.show-print'
                                            columns: ':visible'
                                        }
                                    }, {
                                        extend: "colvis",
                                        className: "btn dark btn-outline",
                                        text: "المكونات"
                                    }
                                ];
    }

            $(function () {

                //#####
                var otablesellnotreviewed;
                function draw_billTablesellNotReviewed() {
                    if ($('#billTablesellNotReviewed').length > 0) {
                        var tablesellnotreviewed = $('#billTablesellNotReviewed');
                        if ($.fn.dataTable.isDataTable('#billTablesellNotReviewed')) {
                            otablesellnotreviewed.ajax.reload();
                        } else {
                            otablesellnotreviewed = tablesellnotreviewed.DataTable({
                                "processing": true,
                                "stateSave": true,
                                "serverSide": true,
                                "ajax": {url: 'salesreportbills.php?do=showallajaxsell', type: 'POST', "data": {
                                        "from": function () {
                                            return $('#from').val()
                                        },
                                        "to": function () {
                                            return $('#to').val()
                                        },
                                        "tabDateGuide": function () {
                                            return "today";
                                        },
                                        "sellbillserial": function () {
                                            return $('#sellbillserial').val()
                                        },
                                        "sellbillid": function () {
                                            return $('#sellbillid').val()
                                        },
                                        "clientid": function () {
                                            return $('#clientid').val()
                                        },
                                        //                    "pricetype": function () {
                                        //                        return $('#pricetype').val()
                                        //                    },
                                        "searchDate": function () {
                                            return localStorage.getItem("search")
                                        },
                                        "laterNakdiPayment": function () {
                                            return 1;
                                        },
                                        // etc..
                                    }}, //  server side processing
                                "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                    if (aData[0].includes("danger")) {//not deleted
                                        $('td', nRow).css('background-color', '#F2DEDE');
                                    } else if (aData[0].includes("dark")) {
                                        $('td', nRow).css('background-color', '#9E9E9E');
                                    } else {
                                        //$('td', nRow).css('background-color', 'white');
                                    }
                                },
                                dom: 'Bfrtip',
                                buttons: buttons,
                                "bStateSave": true,
                                "language": {
                                    "aria": {
                                        "sortAscending": ": Used to order Ascending",
                                        "sortDescending": ": Used to order Descending"
                                    },
                                    "emptyTable": "لا يوجد بيانات",
                                    "info": "عرض من  _START_ إلى  _END_  - عدد فواتير البحث _TOTAL_",
                                    "infoEmpty": "لا يوجد بيانات",
                                    "infoFiltered": "",//"(تنقيه  من عدد فواتير كلى _MAX_)",
                                    "lengthMenu": " _MENU_ عنصر",
                                    "search": "البحث:",
                                    "zeroRecords": "لا يوجد بيانات تشابه البحث"
                                },
                                responsive: !0,
                                "columnDefs": [//            {// set default column settings //                "orderable": false,
                                    //                "searchable": false,
                                    //                "targets": [lstone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //            {// set default column settings
                                    //                "orderable": false,
                                    //                "searchable": false,
                                    //                "targets": [belastone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //            {// set default column settings
                                    //                "orderable": false,
                                    //                "searchable": false, //                "targets": [thrdone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //                {targets: '_all', "className": 'show-print'}
                                ],
                                order: [
                                    [0, "asc"]
                                ],
                                paging: true,
                                lengthMenu: [
                                    [5, 10, 15, 20, 50, -1],
                                    [5, 10, 15, 20, 50, "All"]
                                ],
                                pageLength: 10,
                                dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
                            });
                            //when draw is comlete cal total of column using datatable api sum func //we may need settimeout
                            otablesellnotreviewed.on('draw', function (e, ajaxdata) {
                                //var sum = otablesell.column(3).data().sum();
                                $('#totalsellNotReviewed').html(ajaxdata.json.totals.totalBills);
                                $(".positivefloat").forcepositivefloat();
                                $(".save").select2({
                                    placeholder: "اختر الخزنة ",
                                    minimumInputLength: 0,
                                    //  minimumInputLength: 3,
                                    multiple: false,
                                    quietMillis: 100,
                                    ajax: {
                                        url: "savedailyAjaxController.php?do=getSavesAjax",
                                        dataType: 'json',
                                        data: function (term, page) {
                                            //  alert(term);
                                            return {
                                                term: term, //search term
                                                page_limit: 10, // page size
                                            };
                                        },
                                        results: function (data) {

                                            // alert(term);
                                            return {results: data};
                                        }
                                    },
                                    formatResult: function (data) {
                                        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
                                    },
                                    initSelection: function (element, callback) {
                                        var item = element.val().split(':');
                                        //# to prevent add client .

                                        var data = {id: item[0], text: item[1]};
                                        callback(data);
                                    }
                                }).on('change', function () {
                                });
                                $(".bankAccount").select2({
                                    placeholder: "اختر الحساب البنكى",
                                    minimumInputLength: 0,
                                    //  minimumInputLength: 3,
                                    multiple: false,
                                    quietMillis: 100,
                                    ajax: {
                                        url: "sellbillAjaxController.php?do=getBankAccount",
                                        dataType: 'json',
                                        data: function (term, page) {
                                            //  alert(term);
                                            return {
                                                term: term, //search term
                                                page_limit: 10, // page size
                                            };
                                        },
                                        results: function (data) {

                                            // alert(term);
                                            return {results: data};
                                        }
                                    },
                                    formatResult: function (data) {
                                        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
                                    },
                                    initSelection: function (element, callback) {
                                        var item = element.val().split(':');
                                        //# to prevent add client .

                                        var data = {id: item[0], text: item[1]};
                                        callback(data);
                                    }
                                }).on('change', function () {
                                });
                                //

                                setTimeout(function () {
                                    $('#billTablesellNotReviewed input[id^=save_]').each(function () {
                                        var sid = $(this).attr('id');
                                        $("#billTablesellNotReviewed #" + sid).select2('data', {id: $('#defUserSaveId').val(), text: $('#defUserSaveName').val()});
                                    });
                                    $('#billTablesellNotReviewed input[type="radio"]').each(function () {
                                        if ($(this).val() === "save") {
                                            $(this).attr('checked', 'checked');
                                        }
                                    });
                                }, 500);
                            });
                        }

                    }
                }
                //#####
                var otableretSellnotreviewed;
                function draw_billTableretSellNotReviewed() {
                    if ($('#billTableretSellNotReviewed').length > 0) {
                        var tableretSellnotreviewed = $('#billTableretSellNotReviewed');
                        if ($.fn.dataTable.isDataTable('#billTableretSellNotReviewed')) {
                            otableretSellnotreviewed.ajax.reload();
                        } else {
                            otableretSellnotreviewed = tableretSellnotreviewed.DataTable({
                                "processing": true,
                                "stateSave": true,
                                "serverSide": true,
                                "ajax": {url: 'salesreportbills.php?do=showallajaxret', type: 'POST', "data": {
                                        "from": function () {
                                            return $('#from').val()
                                        },
                                        "to": function () {
                                            return $('#to').val()
                                        },
                                        "tabDateGuide": function () {
                                            return "today";
                                        },
                                        "sellbillserial": function () {
                                            return $('#sellbillserial').val()
                                        },
                                        "sellbillid": function () {
                                            return $('#sellbillid').val()
                                        },
                                        "clientid": function () {
                                            return $('#clientid').val()
                                        },
                                        "searchDate": function () {
                                            return localStorage.getItem("search")
                                        },
                                        "laterNakdiPayment": function () {
                                            return 1;
                                        },
                                        // etc..
                                    }}, //  server side processing
                                "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                    //console.log(aData[0]);
                                    if (aData[0].includes("danger")) {//not deleted
                                        $('td', nRow).css('background-color', '#F2DEDE');
                                    } else if (aData[0].includes("dark")) {
                                        $('td', nRow).css('background-color', '#9E9E9E');
                                    } else {
                                        //$('td', nRow).css('background-color', 'white');
                                    }
                                },
                                dom: 'Bfrtip',
                                buttons: buttons,
                                "bStateSave": true,
                                "language": {
                                    "aria": {
                                        "sortAscending": ": Used to order Ascending",
                                        "sortDescending": ": Used to order Descending"
                                    },
                                    "emptyTable": "لا يوجد بيانات",
                                    "info": "عرض من  _START_ إلى  _END_  - عدد فواتير البحث _TOTAL_",
                                    "infoEmpty": "لا يوجد بيانات",
                                    "infoFiltered": "",// "(تنقيه  من عدد فواتير كلى _MAX_)",
                                    "lengthMenu": " _MENU_ عنصر",
                                    "search": "البحث:",
                                    "zeroRecords": "لا يوجد بيانات تشابه البحث"
                                },
                                responsive: !0,
                                "columnDefs": [//            {// set default column settings //                "orderable": false,
                                    //                "searchable": false,
                                    //                "targets": [lstone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //            {// set default column settings
                                    //                "orderable": false,
                                    //                "searchable": false,
                                    //                "targets": [belastone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //            {// set default column settings
                                    //                "orderable": false,
                                    //                "searchable": false, //                "targets": [thrdone],
                                    //                "className": 'hide-print'
                                    //            },
                                    //                {targets: '_all', "className": 'show-print'}
                                ],
                                order: [
                                    [0, "asc"]
                                ],
                                paging: true,
                                lengthMenu: [
                                    [5, 10, 15, 20, 50, -1],
                                    [5, 10, 15, 20, 50, "All"]
                                ],
                                pageLength: 10,
                                dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
                            });
                            //when draw is comlete cal total of column using datatable api sum func //we may need settimeout
                            otableretSellnotreviewed.on('draw', function (e, ajaxdata) {
                                //var sum = otableretSellnotreviewed.column(2).data().sum();
                                $('#totalretSellNotReviewed').html(ajaxdata.json.totals.totalBills);
                                $(".positivefloat").forcepositivefloat();
                                $(".save").select2({
                                    placeholder: "اختر الخزنة ",
                                    minimumInputLength: 0,
                                    //  minimumInputLength: 3,
                                    multiple: false,
                                    quietMillis: 100,
                                    ajax: {
                                        url: "savedailyAjaxController.php?do=getSavesAjax",
                                        dataType: 'json',
                                        data: function (term, page) {
                                            //  alert(term);
                                            return {
                                                term: term, //search term
                                                page_limit: 10, // page size
                                            };
                                        },
                                        results: function (data) {

                                            // alert(term);
                                            return {results: data};
                                        }
                                    },
                                    formatResult: function (data) {
                                        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
                                    },
                                    initSelection: function (element, callback) {
                                        var item = element.val().split(':');
                                        //# to prevent add client .

                                        var data = {id: item[0], text: item[1]};
                                        callback(data);
                                    }
                                }).on('change', function () {
                                });
                                $(".bankAccount").select2({
                                    placeholder: "اختر الحساب البنكى",
                                    minimumInputLength: 0,
                                    //  minimumInputLength: 3,
                                    multiple: false,
                                    quietMillis: 100,
                                    ajax: {
                                        url: "sellbillAjaxController.php?do=getBankAccount",
                                        dataType: 'json',
                                        data: function (term, page) {
                                            //  alert(term);
                                            return {
                                                term: term, //search term
                                                page_limit: 10, // page size
                                            };
                                        },
                                        results: function (data) {

                                            // alert(term);
                                            return {results: data};
                                        }
                                    },
                                    formatResult: function (data) {
                                        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
                                    },
                                    initSelection: function (element, callback) {
                                        var item = element.val().split(':');
                                        //# to prevent add client .

                                        var data = {id: item[0], text: item[1]};
                                        callback(data);
                                    }
                                }).on('change', function () {
                                });
                                //
                                setTimeout(function () {
                                    $('#billTableretSellNotReviewed input[id^=save_]').each(function () {
                                        var sid = $(this).attr('id');
                                        $("#billTableretSellNotReviewed #" + sid).select2('data', {id: $('#defUserSaveId').val(), text: $('#defUserSaveName').val()});
                                    });
                                    $('#billTableretSellNotReviewed input[type="radio"]').each(function () {
                                        if ($(this).val() === "save") {
                                            $(this).attr('checked', 'checked');
                                        }
                                    });
                                }, 500);
                            });
                        }
                    }
                }

                draw_billTablesellNotReviewed();
                draw_billTableretSellNotReviewed();
                $('body').on('change', '.search_bill', function (e, checkToUnlockButtons) {
                    var flagArr = new Array();
                    for (var i = 1; i <= 10; i++) {
                        flagArr[i] = 0;
                    }
                    if ($('#billTablesellNotReviewed').length > 0 && $('#billTablesellNotReviewed').is(':visible')) {
                        otablesellnotreviewed.ajax.reload(function () {
                            flagArr[1] = 1;
                        });
                    } else {
                        flagArr[1] = 1;
                    }

                    //
                    if ($('#billTableretSellNotReviewed').length > 0 && $('#billTableretSellNotReviewed').is(':visible')) {
                        otableretSellnotreviewed.ajax.reload(function () {
                            flagArr[2] = 1;
                        });
                    } else {
                        flagArr[2] = 1;
                    }

                    //otablesell.draw();//both work fine
                    if (checkToUnlockButtons == 1) {
                        checkToUnlockButtonsFunc(flagArr);
                    }
                });
                function checkToUnlockButtonsFunc(flagArr) {
                    var flag = 1;
                    for (var i = 1; i <= 2; i++) {
                        if (flagArr[i] == 0) {
                            flag = 0;
                        }
                    }
                    if (flag == 1) {//all is ok ubblock buttons
                        thisis.removeClass('processing...');
                        $('.confirmReview').removeClass('processing...');
                    } else {
                        setTimeout(function () {
                            checkToUnlockButtonsFunc(flagArr);
                        }, 500);
                    }
                }
                $('body').on('click', '#refreshResultsBtn', function () {
                    $('.search_bill:first').trigger('change');
                });
            });
            $('body').on('keyup', '.bill_pay, .bill_pay_ret', function () {
                var wait = Number($(this).data('wait'));
                var pay = Number($(this).val());
                if (pay > wait) {
                    $(this).val(wait);
                }
            });
            $('body').on('change', '.paytype', function () {
                var ths_val = $(this).val();
                var id = $(this).attr('data-id');
                if (ths_val == 'save') {
                    $('#save_Div_' + id + '').show();
                    $('#bank_Div_' + id + '').hide();
                } else if (ths_val == 'bank') {
                    $('#save_Div_' + id + '').hide();
                    $('#bank_Div_' + id + '').show();
                }

            });
            //this is to pay many bills @same time ##now commented
            /*$('body').on('click', '.save_payment', function () {



             var client_id = $('#clientid').val();
             //        var payment_print = $(this).attr('data-print');

             //        var total_value_h = $('#total_value_h').val();
             //        if (total_value_h > 0) {
             //
             //        } else {
             //            alert(' يجب ادخال القيم المراد سدادها فى الفواتير');
             //        }

             //## sell part
             var id_pay = [];
             $('.bill_pay').each(function () {
             var bill_id = $(this).attr('data-id');
             $('#billTablesellNotReviewed #moneyReq' + bill_id).hide();
             var check_Select2_select = '';//save or bank

             var bill_tr = $(this).parent();//$('#bill_tr_' + bill_id + '');
             var ths_val = Number($(this).val());
             var saveId = 0;
             var bankAccountId = 0;
             if (ths_val > 0) {
             $(this).css('background-color', 'white');
             //# remove hidden print class if exist to show tr in print .
             if (bill_tr.hasClass('hidden-print')) {
             bill_tr.removeClass('hidden-print');
             }

             var paytype = $('#billTablesellNotReviewed #paytype_' + bill_id + ':checked').val();
             var paytype_txt = '';
             if (paytype == 'save') {
             var saveData = $('#billTablesellNotReviewed #save_' + bill_id + '').select2('data');
             saveId = saveData.id;
             paytype_txt = 'خزنة - ' + saveData.text;
             if (typeof (saveId) == 'undefined') {
             check_Select2_select = 'يجب اختيار خزنة';
             $('#billTablesellNotReviewed #saveReq' + bill_id).show();
             } else {
             $('#billTablesellNotReviewed #saveReq' + bill_id).hide();
             }
             } else if (paytype == 'bank') {
             var bankData = $('#billTablesellNotReviewed #bankAccount_' + bill_id + '').select2('data');
             bankAccountId = bankData.id;
             paytype_txt = 'بنك - ' + bankData.text;
             if (typeof (bankAccountId) == 'undefined') {
             check_Select2_select = 'يجب اختيار بنك';
             $('#billTablesellNotReviewed #bankReq' + bill_id).show();
             } else {
             $('#billTablesellNotReviewed #bankReq' + bill_id).hide();
             }
             }
             //# allow this span to show pay type text .
             $('#billTablesellNotReviewed #paytype_text_' + bill_id + ' span').html(paytype_txt);
             $('#billTablesellNotReviewed .paytype_radio').addClass('hidden-print');

             //# change total dept value .????????????????????????
             var values = {"bill_id": bill_id, "payed": ths_val, "paytype_txt": paytype_txt, "paytype": paytype, "saveId": saveId, "bankAccountId": bankAccountId};
             //                var lbl_dept = Number($('#billTablesellNotReviewed #lbl_dept').html());
             //                lbl_dept = lbl_dept - ths_val;
             //                $('#billTablesellNotReviewed #lbl_dept').html(lbl_dept);
             //                var total_dept = Number($('#billTablesellNotReviewed #waitValue').val()) + Number($('#billTablesellNotReviewed #lbl_dept').html());
             //                $('#total_dept').html(Number(total_dept));

             if (check_Select2_select == "")
             id_pay.push(values);
             } else {
             $('#billTablesellNotReviewed #moneyReq' + bill_id).show();
             //# add hidden print class to prevent empty payment from showing on print .
             if (!bill_tr.hasClass('hidden-print')) {
             bill_tr.addClass('hidden-print');
             }
             }

             });

             //## ret sell part
             var id_pay_ret = [];
             $('.bill_pay_ret').each(function () {
             var bill_id = $(this).attr('data-id');
             $('#billTableretSellNotReviewed #moneyReq' + bill_id).hide();
             var check_Select2_select = '';//save or bank

             var bill_tr = $(this).parent();//$('#bill_tr_' + bill_id + '');
             var ths_val = Number($(this).val());
             var saveId = 0;
             var bankAccountId = 0;
             if (ths_val > 0) {
             $(this).css('background-color', 'white');
             //# remove hidden print class if exist to show tr in print .
             if (bill_tr.hasClass('hidden-print')) {
             bill_tr.removeClass('hidden-print');
             }

             var paytype = $('#billTableretSellNotReviewed #paytype_' + bill_id + ':checked').val();
             var paytype_txt = '';
             if (paytype == 'save') {
             var saveData = $('#billTableretSellNotReviewed #save_' + bill_id + '').select2('data');
             saveId = saveData.id;
             paytype_txt = 'خزنة - ' + saveData.text;
             if (typeof (saveId) == 'undefined') {
             check_Select2_select = 'يجب اختيار خزنة';
             $('#billTableretSellNotReviewed #saveReq' + bill_id).show();
             } else {
             $('#billTableretSellNotReviewed #saveReq' + bill_id).hide();
             }
             } else if (paytype == 'bank') {
             var bankData = $('#billTableretSellNotReviewed #bankAccount_' + bill_id + '').select2('data');
             bankAccountId = bankData.id;
             paytype_txt = 'بنك - ' + bankData.text;
             if (typeof (bankAccountId) == 'undefined') {
             check_Select2_select = 'يجب اختيار بنك';
             $('#billTableretSellNotReviewed #bankReq' + bill_id).show();
             } else {
             $('#billTableretSellNotReviewed #bankReq' + bill_id).hide();
             }
             }
             var values = {"bill_id": bill_id, "payed": ths_val, "paytype_txt": paytype_txt, "paytype": paytype, "saveId": saveId, "bankAccountId": bankAccountId};


             if (check_Select2_select == "")
             id_pay_ret.push(values);
             } else {
             $('#billTableretSellNotReviewed #moneyReq' + bill_id).show();
             //# add hidden print class to prevent empty payment from showing on print .
             if (!bill_tr.hasClass('hidden-print')) {
             bill_tr.addClass('hidden-print');
             }
             }

             });

             var sucessSell = 0;
             var sucessRet = 0;
             if (id_pay.length > 0) {
             $.ajax({
             type: "POST",
             url: 'sellbillAjaxController.php?do=makeSellBillPayment',
             data: {id_pay: id_pay, client_id: client_id},
             async: false,
             success: function (data) {
             sucessSell = 1;
             }
             });
             }
             if (id_pay_ret.length > 0) {
             $.ajax({
             type: "POST",
             url: 'sellbillAjaxController.php?do=makeReturnSellBillPayment',
             data: {id_pay: id_pay_ret, client_id: client_id},
             async: false,
             success: function (data) {
             sucessRet = 1;
             }
             });
             }

             if ((id_pay.length > 0 && sucessSell == 1) || (id_pay_ret.length > 0 && sucessRet == 1)) {
             alert('تمت العمليه بنجاح');
             $('#refreshResultsBtn').click();
             }

             }); */

            //this is to pay many one bill at a time and print recit
            var id_pay, client_id, oldpayments, row_id, moneyPaid, serviceMoneyPaid;
            $('body').on('click', '.save_payment', function () {


                row_id = Number($(this).data('id'));
                var ret = Number($(this).data('ret'));
                /*-----------------------------------------------------*/
                client_id = $('#clientid').val();
                var whatPayedToPrint = 0;
                oldpayments = 0;

                moneyPaid = 0;
                serviceMoneyPaid = 0;
                //## sell part
                id_pay = [];
                if (ret != 1) {
                    $('.bill_pay[data-id="' + row_id + '"]').each(function () {
                        var bill_id = $(this).attr('data-id');
                        $('#billTablesellNotReviewed #moneyReq' + bill_id).hide();
                        var check_Select2_select = ''; //save or bank

                        var bill_tr = $(this).parent(); //$('#bill_tr_' + bill_id + '');
                        var ths_val = Number($(this).val());
                        oldpayments = Number($(this).data('payed'));
                        var saveId = 0;
                        var bankAccountId = 0;
                        if (ths_val > 0) {
                            $(this).css('background-color', 'white');
                            //# remove hidden print class if exist to show tr in print .
                            if (bill_tr.hasClass('hidden-print')) {
                                bill_tr.removeClass('hidden-print');
                            }

                            var paytype = $('#billTablesellNotReviewed #paytype_' + bill_id + ':checked').val();
                            var paytype_txt = '';
                            if (paytype == 'save') {
                                var saveData = $('#billTablesellNotReviewed #save_' + bill_id + '').select2('data');
                                saveId = saveData.id;
                                paytype_txt = 'خزنة - ' + saveData.text;
                                if (typeof (saveId) == 'undefined') {
                                    check_Select2_select = 'يجب اختيار خزنة';
                                    $('#billTablesellNotReviewed #saveReq' + bill_id).show();
                                } else {
                                    $('#billTablesellNotReviewed #saveReq' + bill_id).hide();
                                }
                            } else if (paytype == 'bank') {
                                var bankData = $('#billTablesellNotReviewed #bankAccount_' + bill_id + '').select2('data');
                                bankAccountId = bankData.id;
                                paytype_txt = 'بنك - ' + bankData.text;
                                if (typeof (bankAccountId) == 'undefined') {
                                    check_Select2_select = 'يجب اختيار بنك';
                                    $('#billTablesellNotReviewed #bankReq' + bill_id).show();
                                } else {
                                    $('#billTablesellNotReviewed #bankReq' + bill_id).hide();
                                }
                            }
                            //# allow this span to show pay type text .
                            $('#billTablesellNotReviewed #paytype_text_' + bill_id + ' span').html(paytype_txt);
                            $('#billTablesellNotReviewed .paytype_radio').addClass('hidden-print');
                            //# change total dept value .????????????????????????
                            var values = {"bill_id": bill_id, "payed": ths_val, "paytype_txt": paytype_txt, "paytype": paytype, "saveId": saveId, "bankAccountId": bankAccountId, serviceMoney: $('#serviceMoney' + bill_id).val(), discountMoney: $('#discountMoney' + bill_id).val()};
                            //                var lbl_dept = Number($('#billTablesellNotReviewed #lbl_dept').html());
                            //                lbl_dept = lbl_dept - ths_val;
                            //                $('#billTablesellNotReviewed #lbl_dept').html(lbl_dept);
                            //                var total_dept = Number($('#billTablesellNotReviewed #waitValue').val()) + Number($('#billTablesellNotReviewed #lbl_dept').html());
                            //                $('#total_dept').html(Number(total_dept));

                            if (check_Select2_select == "") {
                                id_pay.push(values);
                                moneyPaid += ths_val;
                                serviceMoneyPaid += Number($('#serviceMoney' + bill_id).val());
                            }
                        } else {
                            $('#billTablesellNotReviewed #moneyReq' + bill_id).show();
                            //# add hidden print class to prevent empty payment from showing on print .
                            if (!bill_tr.hasClass('hidden-print')) {
                                bill_tr.addClass('hidden-print');
                            }
                            return false;
                        }

                    });
                }
                //## ret sell part
                var id_pay_ret = [];
                if (ret == 1) {
                    $('.bill_pay_ret[data-id="' + row_id + '"]').each(function () {
                        var bill_id = $(this).attr('data-id');
                        $('#billTableretSellNotReviewed #moneyReq' + bill_id).hide();
                        var check_Select2_select = ''; //save or bank

                        var bill_tr = $(this).parent(); //$('#bill_tr_' + bill_id + '');
                        var ths_val = Number($(this).val());
                        var saveId = 0;
                        var bankAccountId = 0;
                        if (ths_val > 0) {
                            $(this).css('background-color', 'white');
                            //# remove hidden print class if exist to show tr in print .
                            if (bill_tr.hasClass('hidden-print')) {
                                bill_tr.removeClass('hidden-print');
                            }

                            var paytype = $('#billTableretSellNotReviewed #paytype_' + bill_id + ':checked').val();
                            var paytype_txt = '';
                            if (paytype == 'save') {
                                var saveData = $('#billTableretSellNotReviewed #save_' + bill_id + '').select2('data');
                                saveId = saveData.id;
                                paytype_txt = 'خزنة - ' + saveData.text;
                                if (typeof (saveId) == 'undefined') {
                                    check_Select2_select = 'يجب اختيار خزنة';
                                    $('#billTableretSellNotReviewed #saveReq' + bill_id).show();
                                } else {
                                    $('#billTableretSellNotReviewed #saveReq' + bill_id).hide();
                                }
                            } else if (paytype == 'bank') {
                                var bankData = $('#billTableretSellNotReviewed #bankAccount_' + bill_id + '').select2('data');
                                bankAccountId = bankData.id;
                                paytype_txt = 'بنك - ' + bankData.text;
                                if (typeof (bankAccountId) == 'undefined') {
                                    check_Select2_select = 'يجب اختيار بنك';
                                    $('#billTableretSellNotReviewed #bankReq' + bill_id).show();
                                } else {
                                    $('#billTableretSellNotReviewed #bankReq' + bill_id).hide();
                                }
                            }
                            var values = {"bill_id": bill_id, "payed": ths_val, "paytype_txt": paytype_txt, "paytype": paytype, "saveId": saveId, "bankAccountId": bankAccountId};
                            if (check_Select2_select == "") {
                                id_pay_ret.push(values);
                                moneyPaid += ths_val;
                            }
                        } else {
                            $('#billTableretSellNotReviewed #moneyReq' + bill_id).show();
                            //# add hidden print class to prevent empty payment from showing on print .
                            if (!bill_tr.hasClass('hidden-print')) {
                                bill_tr.addClass('hidden-print');
                            }
                            return false;
                        }

                    });
                }

                var sucessSell = 0;
                var sucessRet = 0;
                if (id_pay.length > 0) {
                    if (oldpayments > 0) {
                        $('#choosePaymentToPrintModal').modal({backdrop: 'static', keyboard: false});
                        $('#choosePaymentToPrintModal').modal('show');
                        return true;
                    }
                    $.ajax({
                        type: "POST",
                        url: 'sellbillAjaxController.php?do=makeSellBillPayment',
                        data: {id_pay: id_pay, client_id: client_id},
                        async: false,
                        success: function (data) {
                            if (Number(data) == -1000) {
                                alert("تم سداد الفاتوره من قبل");
                                sucessSell = 0;
                            } else if (Number(data) == -2000) {
                                alert("هذه الفاتوره محذوفه");
                                sucessSell = 0;
                            } else {
                                sucessSell = 1;
                            }
                        }
                    });
                }
                if (id_pay_ret.length > 0) {
                    $.ajax({
                        type: "POST",
                        url: 'sellbillAjaxController.php?do=makeReturnSellBillPayment',
                        data: {id_pay: id_pay_ret, client_id: client_id},
                        async: false,
                        success: function (data) {
                            if (Number(data) == -1000) {
                                alert("تم سداد الفاتوره من قبل");
                                sucessRet = 0;
                            } else if (Number(data) == -2000) {
                                alert("هذه الفاتوره محذوفه");
                                sucessRet = 0;
                            } else {
                                sucessRet = 1;
                            }
                        }
                    });
                }

                if ((id_pay.length > 0 && sucessSell == 1) || (id_pay_ret.length > 0 && sucessRet == 1)) {
                    //            alert('تمت العمليه بنجاح');
                    window.open('salesreportbills.php?do=printReceipt&bill=' + row_id + '&type=' + ret + '&m=' + moneyPaid + '&s=' + serviceMoneyPaid, '_blank');
                }

                if ($("[id^='moneyReq']:visible").length === 0)
                    $('#refreshResultsBtn').click();

            });

            $('.choosePaymentToPrint').on('click', function () {
                $('#choosePaymentToPrintModal').modal('hide');
                var choice = $(this).data('choose');//all or current
                if (id_pay.length > 0) {
                    var sucessSell = 0;
                    $.ajax({
                        type: "POST",
                        url: 'sellbillAjaxController.php?do=makeSellBillPayment',
                        data: {id_pay: id_pay, client_id: client_id},
                        async: false,
                        success: function (data) {
                            if (Number(data) == -1000) {
                                alert("تم سداد الفاتوره من قبل");
                                sucessSell = 0;
                            } else if (Number(data) == -2000) {
                                alert("هذه الفاتوره محذوفه");
                                sucessSell = 0;
                            } else {
                                sucessSell = 1;
                            }
                        }
                    });
                }
                if ((id_pay.length > 0 && sucessSell == 1)) {
                    //            alert('تمت العمليه بنجاح');
                    window.open('salesreportbills.php?do=printReceipt&bill=' + row_id + '&type=0&m=' + moneyPaid + '&s=' + serviceMoneyPaid + '&ch=' + choice + '&op=' + oldpayments, '_blank');
                }
                if ($("[id^='moneyReq']:visible").length === 0)
                    $('#refreshResultsBtn').click();

            });
            //
            var search = localStorage.getItem("search");
            if (search == "dateTime") {
                $('#searchdateTime').attr('checked', 'checked');
                $('#searchdateOnly').removeAttr('checked');
                //
                $('#dateTimeDiv').show();
                $('#dateOnlyDiv').remove();
            } else {
                $('#searchdateOnly').attr('checked', 'checked');
                $('#searchdateTime').removeAttr('checked');
                //
                $('#dateOnlyDiv').show();
                $('#dateTimeDiv').remove();
            }

            //#############
            //scroll into view
            setTimeout(function () {
                $("#billTablesellNotReviewed")[0].scrollIntoView({
                    behavior: "smooth", // or "auto" or "instant"
                    block: "start", // or "end"
                    inline: "nearest"
                });
            }, 100);



        </script>
        {/literal}
