(function(){
	var Commissions = function() {
    return {

    	init: function() {
				var dt = $('#datatable-commissions').on('xhr.dt', function ( e, settings, json ) {
		        $('#searchBtn').prop('disabled', false);
		    	} ).DataTable( {
						ajax: {
							url: ajax_commissions_dt,
							type: 'POST',
							data: function(d) {
                d.level = $('#level').val();
                d.search = $('#search').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": "Username", "sortable": false, "data": "username" },
              { "title": "Email", "data": "email", "sortable": false },
              { "title": "Level", "data": null, "sortable": true },
              { "title": "Signed Up", "data": "created_at" }
				    ],
				    "columnDefs": [
              {
                  "targets": [2],
                  "render": function ( data, type, full, meta ) {
                      return full.levelCalc;
                  }
              }
            ]
					});

			$('#betweenFilter').daterangepicker({
	            format: 'MM/DD/YYYY',
	            separator: ' to ',
	            startDate: moment().subtract(1, 'month'),
	            endDate: moment(),
	            minDate: '01/01/2012',
	            maxDate: '12/31/2018'
            },
            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();
	        });
        }
    };
  }();

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

})();