  var table; 



   function get_Products(){

            $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option class="text-black text-danger-800" selected="selected" value="">'+Translation('جميع المواد')+'</option>';
                      
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =response[i][2];
                          var BC =response[i][3];
                          
                          attach = attach + '<option class="text-black text-danger-800" data-subtext="'+Translation('الرمز الاجنبي')+' : '+response[i][2]+' || '+Translation('الرمز التسلسلي')+' : '+response[i][3]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                           
                          
                        }
                        $("#product_id_search").html(attach);
                        $('#product_id_search').selectpicker('refresh');
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return 'not';
    }


$(document).ready(function() {
  
   

    // remove current other row 
     $("#purchase_item_footer").on('click','.btn_other_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[2];
          $("#item_row_other_"+row_num).remove();
          calc_total_purchase_price();
          calc_payments();
    });

 

});

  

   var product_id = $("#product_id_search").val();

    function search_Product(){
        product_id = $("#product_id_search").val();
        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
    }

    function show_detail_page(){
        product_id = $("#product_id_search").val();
        if(product_id >0){
          window.location="index.php?p=stock_detail&pid="+product_id;
        }else{
          noty({
                  width: 200,
                  text: Translation('قم باختيار مادة'), //'Product Successfully Update',
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'topRight',
                });
        }
    }





$(function() {



    // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 5 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('ﺑﺤﺚ')+':</span> _INPUT_',
            searchPlaceholder: Translation('ﺑﺤﺚ ﻋﻦ')+'...',
            lengthMenu: '<span>'+Translation('ﻋﺮﺽ')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('ﺑﺤﺚ ﻋﻦ')+' '+title+'" />');
    });
    
    

    var query_id = getQueryVariable("id");



    var table = $('.datatable-column-search-inputs').DataTable({
        
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_report.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(product_id > 0 && product_id !=null && product_id !=undefined && product_id !=''){
            d.id =product_id ;
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          


            {
               "render": function(data, type, row){


                        // return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='Show Invoice Details'>`+data+`</a>`;
                        return  `<a onclick="load_account_statment('',`+row[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('ﻋﺮﺽ ﺟﻤﻴﻊ ﻛﺸﻮﻓﺎﺕ اﻟﺤﺴﺎﺏ ﻟﻬﺬا اﻟﻮﺻﻞ')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

           


            {
                "render": function(data, type, row){
                   if(data ==1 ){
                     status=  `<span class="label label-success btn-block ">`+Translation('مباع بالكامل')+`</span>`;
                   }else if(data ==5){
                     status = '<span class="label bg-purple  btn-block ">'+Translation('مباع بالتجزئة')+'  </span>';
                   }else{
                     status = '<span class="label bg-purple  btn-block ">'+data+'  </span>';

                        
                   }
                   return  status;
                },
                "targets": 10
            }
            

           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[5] == 1 ){ // outcome type
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('alpha-info');
                });
            }
        },
        "order": [[0,'desc']],
        "displayLength": 25,
      
        initComplete: function () {
         
          $("div.datatable-header").append(` <div class="row">
                                              <div class="form-group">

                                                  <div class="col-sm-6">
                                                    <div class="input-group">
                                                      <label class="input-group-addon text-black text-danger-800">`+Translation('بحث عن مادة في جميع وصولات البيع والشراء')+`</label>
                                                      <select onchange="search_Product();" class="form-control  multi_lang" data-live-search="true" name="product_id_search" id="product_id_search" data-width="100%" placeholder="اسم المادة">
                                                    
                                                      </select>
                                                    </div>
                                                  </div>
                                                 <!-- <button type="button" class="btn bg-pink-400 col-sm-4 btn-labeled " onclick="show_detail_page();">
                                                    <b><i class="icon-search4"></i></b>
                                                    `+Translation('عرض تفاصيل هذه المادة في جميع وصولات البيع والشراء')+`
                                                  </button>
                                                  -->
                                              </div>
                                            </div>`); 

          // $("div.datatable-header").append(`&nbsp;<div class="btn-group">
          //                 <button id="inv_filter_btn" type="button"
          //                 class="btn bg-teal-400 btn-labeled dropdown-toggle"
          //                 data-toggle="dropdown"><b><i class="icon-filter4">
          //                 </i></b> <span id="inv_filter">`+Translation('ﻓﻠﺘﺮﺓ اﻟﻮﺻﻮﻻﺕ')+`</span> <span class="caret"></span></button>
          //                 <ul class="dropdown-menu dropdown-menu-right">
          //                 <li><a href="index.php?p=invoice"><i class="icon-close2 text-teal"></i>`+Translation('اﺯاﻟﺔ اﻟﻔﻠﺘﺮ')+`  </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=2"><i class="icon-coins text-success"></i>`+Translation('اﻟﻮاﺻﻞ')+` </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=1"><i class="icon-bell-check text-info"></i>`+Translation('ﻭاﺻﻞ ﺟﺰﺋﻴﺎ')+`  </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=0"><i class="icon-alarm-check text-danger"></i>`+Translation('ﻏﻴﺮ ﻭاﺻﻞ')+` </a></li>
          //                 <li class="divider"></li>
          //                 <li><a href="index.php?p=invoice&ip=4"><i class=" icon-task text-violet"></i>`+Translation('ﻋﺮﻭﺽ')+`  </a></li>
          //                 <li><a href="index.php?p=invoice&ip=3"><i class="icon-loop text-purple"></i>`+Translation('ﻣﺴﺘﺮﺟﻊ')+`  </a></li>

          //               </ul>
          //             </div>`);



 
            // invoce_filter_btn_label();

            this.api().columns().every( function() {
                var column = this;
                

            });
            // escape_notes();
                get_Products();   

        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



