(function(){
   var PendingCashouts = function() {
      var dt;
      var rows_selected = [];

      function updateDataTableSelectAllCtrl(table){
         var $table             = table.table().node();
         var $chkbox_all        = $('tbody input[type="checkbox"]', $table);
         var $chkbox_checked    = $('tbody input[type="checkbox"]:checked', $table);
         var chkbox_select_all  = $('thead input[name="select_all"]', $table).get(0);

         // If none of the checkboxes are checked
         if($chkbox_checked.length === 0){
            chkbox_select_all.checked = false;
            if('indeterminate' in chkbox_select_all){
               chkbox_select_all.indeterminate = false;
            }

         // If all of the checkboxes are checked
         } else if ($chkbox_checked.length === $chkbox_all.length){
            chkbox_select_all.checked = true;
            if('indeterminate' in chkbox_select_all){
               chkbox_select_all.indeterminate = false;
            }

         // If some of the checkboxes are checked
         } else {
            chkbox_select_all.checked = true;
            if('indeterminate' in chkbox_select_all){
               chkbox_select_all.indeterminate = true;
            }
         }

         $('span#selectedCount').html( rows_selected.length );
      };

    return {

        init: function() {
         dt = $('#pendingCashouts').DataTable( {
                  ajax: {
                     url: ajax_pendingCashouts_dt,
                     type: 'POST'
                  },
                  lengthMenu: [ 25, 50, 75, 100 ],
                  pageLength: 25,
                  serverSide: true,
                  retrieve: true,
                  paging: true,
                  searching: false,
                'order': [[1, 'asc']],
                'rowCallback': function(row, data, dataIndex){
                     // Get row ID
                     var rowId = data[0];

                     // If row ID is in the list of selected row IDs
                     if($.inArray(rowId, rows_selected) !== -1){
                        $(row).find('input[type="checkbox"]').prop('checked', true);
                        $(row).addClass('selected');
                     }
               },
                "columnDefs": [
                     {
                        'targets': 0,
                        'searchable': false,
                        'orderable': false,
                        'width': '1%',
                        'className': 'dt-body-center',
                        "render": function( data, type, full, meta ) {
                           return '<input type="checkbox">';
                        }
                     },
                     {
                        'targets': 1,
                        'orderable': true,
                        'data': 'id'
                     },
                     {
                        'targets': 2,
                        'orderable': true,
                        'data': null,
                        'render': function( data, type, full, meta ) {
                           return '<img src="' + processorImgUrl + full.processor_id + '.gif" />'
                        }
                     },
                     {
                        'targets': 3,
                        'orderable': true,
                        'data': 'balance'
                     },
                     {
                        'targets': 4,
                        'orderable': true,
                        'data': null,
                        'render': function( data, type, full, meta ) {
                           return '<a href="#" class="userPopup" data-id="' + full.user_id + '">' + full.username + ' (#' + full.user_id + ')</a>';
                        }
                     },
                     {
                        'targets': 5,
                        'orderable': true,
                        'data': null,
                        'render': function( data, type, full, meta ) {
                           return full.typeName;
                        }
                     },
                     {
                        'targets': 6,
                        'orderable': true,
                        'data': 'fee'
                     },
                     {
                        'targets': 7,
                        'orderable': true,
                        'data': 'amount'
                     },
                     {
                        'targets': 8,
                        'orderable': false,
                        'data': null,
                        'render': function( full ) {
                            if( full.bitcoin_txid && full.bitcoin_txid !== null ) {
                              return full.bitcoin_txid.trimToLength( 25 );
                            }

                            return full.note;
                        }
                     },
                     {
                        'targets': 9,
                        'orderable': true,
                        'data': 'created_at'
                     },
                     {
                        'targets': 10,
                        'searchable': false,
                        'orderable': false,
                        'data': null,
                        'render': function( full ) {
                           return '<button class="btn yellow approveBtn btn-sm" style="margin-right:10px" data-action="1"><i class="fa fa-check"></i> Approve</button><button class="btn red declineBtn btn-sm" data-action="2"><i class="fa fa-close"></i> Decline</button>';
                        }
                     }
                  ]
               });

         $('#pendingCashouts tbody').on('click', 'tr td a.userPopup', function(e) {
            e.preventDefault();
            var id = $(this).data('id');

            App.userInfo( id, userInfoUrl );
         });

         $('#pendingCashouts tbody').on('click', 'input[type="checkbox"]', function(e){
            var $row = $(this).closest('tr');

            // Get row data
            var data = dt.row($row).data();

            // Get row ID
            var rowId = data.id;

            // Determine whether row ID is in the list of selected row IDs
            var index = $.inArray(rowId, rows_selected);

            // If checkbox is checked and row ID is not in list of selected row IDs
            if(this.checked && index === -1){
               rows_selected.push(rowId);

            // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
            } else if (!this.checked && index !== -1){
               rows_selected.splice(index, 1);
            }

            if(this.checked){
               $row.addClass('selected');
            } else {
               $row.removeClass('selected');
            }

            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(dt);

            // Prevent click event from propagating to parent
            e.stopPropagation();
         });

         // Handle click on table cells with checkboxes
         $('#pendingCashouts').on('click', 'tbody td:not(:last-child), thead th:first-child', function(e){
            $(this).parent().find('input[type="checkbox"]').trigger('click');
         });

         // Handle click on "Select all" control
         $('thead input[name="select_all"]', dt.table().container()).on('click', function(e){
            if(this.checked){
               $('#pendingCashouts tbody input[type="checkbox"]:not(:checked)').trigger('click');
            } else {
               $('#pendingCashouts tbody input[type="checkbox"]:checked').trigger('click');
            }

            // Prevent click event from propagating to parent
            e.stopPropagation();
         });

         // Handle table draw event
         dt.on('draw', function(){
            // Update state of "Select all" control
            updateDataTableSelectAllCtrl(dt);
         });

         $('#pendingCashouts').on('click', 'tbody tr td:last-child .approveBtn, tbody tr td:last-child .declineBtn', function( e ) {
            var self = $(this), $row = $(this).closest('tr'), data = dt.row( $row ).data(), rowId = data.id, index = $.inArray( rowId, rows_selected ), action = self.data('action');

            $('.bulkBtn').prop('disabled', 'disabled');

            var ajaxCall = function( bitcoin_txid ) {
              var bitcoin_txid = bitcoin_txid || null;

              App.ajax({
                  url: ajax_pendingCashouts_action,
                  method: 'POST',
                  data: {
                     action: action,
                     id: rowId,
                     bitcoin_txid: bitcoin_txid
                  }
               }, function( data ) {

                  if( data ) {
                     dt.ajax.reload(function() {

                        if ( index > -1 ){
                           rows_selected.splice( index, 1 );
                           updateDataTableSelectAllCtrl(dt);
                        }

                     });
                  }

                  $('.bulkBtn').prop('disabled', false);
               });
            };

            if( action == 1 ) {
              bootbox.prompt("What is the bitcoin TX Id?", function( result ) {
                  if ( result === null ) {
                    $('.bulkBtn').prop('disabled', false);
                  } else {
                    ajaxCall( result );
                  }
              });
            } else {
              ajaxCall();
            }

         });

         $('.bulkBtn').on('click', function(e){
            var self = $( this );

            if( rows_selected.length > 0 ) {

               $('.bulkBtn').prop('disabled', 'disabled');

               var action = self.data('action');

               App.ajax({
                  url: ajax_pendingCashouts_action,
                  method: 'POST',
                  data: {
                     action: action,
                     id: rows_selected
                  }
               }, function( data ) {
                  if( data ) {
                     rows_selected = [];
                     dt.ajax.reload();
                     $('.bulkBtn').prop('disabled', false);
                  }
               });
            }

         });

        }
    };

   }();

   $(document).ready(function() {
      PendingCashouts.init();
   });

})();
