(function(){
	var AuctionPurchase = function() {
    	return {

	    	init: function() {
                var dt = $('#datatable-auctionpurchase').on('xhr.dt', function ( e, settings, json ) {

                    $('#searchBtn').prop('disabled', false);
    
                    } ).DataTable( {
                      
                            ajax: {
                                url: ajax_auctionpurchase_dt,
                                type: 'POST',
                                data: function(d) {
                                    d.item = $('#item').val();
                                    d.user= $('#userID').val();
                                    d.startDate = $('#startDate').val();
                                    d.endDate = $('#endDate').val();
                                }
                            },
                            lengthMenu: [ 25, 50, 75, 100 ],
                            pageLength: 25,
                            serverSide: true,
                            retrieve: true,
                            paging: true,
                            searching: false,
                            "columns": [
                                {"title": 'ID', "sortable": true, "data": "id"},
                                {"title": 'User', "sortable": true, "data": "user"},
                                {"title": 'Item', "sortable": true, "data": "item_id"},
                                {"title": 'Price', "sortable": true, "data": "price"},
                                {"title": 'Status', "data": "status", "sortable": true},
                                {"title": 'Type', "data": "type", "sortable": true},
                                {"title": 'Purchase date', "data": "created_at", "sortable": true},
                                {"title": 'Actions', "data": null}
                          
                        ],
                        "columnDefs": [
                            {
                                'targets': 7,
                                'orderable': false,
                                'className': 'text-center',
                                'data': null,
                                'render': function (data, type, full, meta) {
                                    var btn = '<button class="btn btn-sm yellow viewShipping" data-id="' + full.id + '"><i class="fa fa-eye"></i> Details </button>';

                                    if(full.status !== 'Delivered' && full.status !== 'Shipping'){
                                        //if(full.status === 'Under Process') {
                                            btn += '<button class="btn btn-success changeStatusBtn btn-sm" style="margin-right:10px" data-action="2" data-id="' + full.id + '"><i class="fa fa-check"></i> Shipping </button>';
                                        //}
                                    }
                                    return btn;
                                }
                            },
                        ],
                        });
            
                $('#datatable-auctionpurchase').on('click', 'tbody tr td:last-child .changeStatusBtn', function() {
                    var id = $(this).data('id');
                    var code = $(this).data('action');
                    //window.active_group = $(this).parent().parent().prevAll('.group:first').children().text();

                    App.ajax({
                        url: ajax_auctionpurchase_status,
                        type: 'POST',
                        data: {
                            id: id,
                            code: code
                        }
                    }, function(data){
                        if( data ) {
                            dt.ajax.reload();
                        }
                    });

                });

                $('#datatable-auctionpurchase tbody').on('click', 'tr td .viewShipping', function(e) {
                    e.preventDefault();
                    var id = $(this).data('id');

                    sitename = 'Auction Purchase Details';
                    window.open(shippingInfoUrl + '/' + id, 'Shipping Information' + ' (#' + id + ') ' + sitename, 'height=800,width=1200');
                });

                $('#betweenFilter').daterangepicker({
                    format: 'MM/DD/YYYY',
                    separator: ' to ',
                    startDate: moment().subtract(1, 'month'),
                    endDate: moment(),
                    minDate: '01/01/2012',
                    maxDate: 'moment()'
                },
                function (start, end) {
                  $('#startDate').val( start.format('YYYY-MM-D') );
                  $('#endDate').val( end.format('YYYY-MM-D') );
                  $('#betweenFilter input').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                  });

                $('#filterForm').submit(function(e){
                    e.preventDefault();
                    $('#filterBtn').prop('disabled', 'disabled');
                    var range = $('#betweenFilter input').val().toString(), srange = range.split(' - ');
    
                    if( range == '' || range.length < 1 || srange.length !== 2 || !moment(srange[0]).isValid() || !moment(srange[0]).isValid(srange[1]) ) {
                        $('#startDate').val('');
                          $('#endDate').val('');
                          $('#betweenFilter input').val('');
                    }
    
                    dt.ajax.reload();
                });
                $( "#reset" ).click(function() {
                    $(".userSearch").select2('val', '');
                    $('.userSearch')
                    .find('option')
                    .remove()
                    .end()
                    .append('<option value=""></option>')
                    .val("");  
                  });
                $(".userSearch").select2({
                    tags: false,
                    multiple: false,
                                maximumSelectionSize: 10,
                                minimumInputLength: 1,
                    width: '400px',
                    ajax: {
                        url: ajax_admin_usersearch_select2,
                        dataType: "json",
                        type: "POST",
                        data: function(params) {
                            return {
                                q: params.term, // search term
                                page: params.page
                            };
                        },
                        processResults: function (data) {
                            var results = [];
                            $.each(data.data, function (index, user) {
                                results.push({
                                    id: user.id,
                                    text: user.username
                                });
                            });
        
                            return {
                                results: results
                            };
                        },
                        cache: true
                    }
                  });
	      	}
    	};
  	}();

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

})();