$(document).ready(function() {

    var ajaxUrl = 'index.php?fuse=clients&action=getdomainlist&controller=index';
    var table = $('#table-list').DataTable({
        columnDefs: [{
            targets: 0,
            orderable: false,
            className: 'select-checkbox',
            checkboxes: {
                selectRow: true
            },
            width: '5%'
        }],
        select: {
            style: 'multi',
            selector: 'td:first-child'
        },
        "searching": false,
        "ajax": {
            url: ajaxUrl,
            dataSrc: 'domains',
            data: function(d) {
                d.registrar = $('#domains-grid-filterbyregistrar').val();
                d.limit = $('#domains-grid-filter').val();
            }
        },
        "columns": [
            { data: null, defaultContent: '', orderable: false, },
            { "data": "domain" },
            { "data": "expiry" },
        ],
        "order": [[1, 'desc']]
    });

    table.on('select.dt deselect.dt', function() {
        disableButtons();

        var selectedRows = table.rows({ selected: true }).count();

        if (selectedRows > 0) {
           enableButtons();
        }
    });

    function enableButtons() {
        $('#importDomainButton').prop('disabled', false);
    };

    function disableButtons() {
        $('#importDomainButton').prop('disabled', true);
    };

    disableButtons();

    $('#checkAll').on('click', function () {
        if (this.checked) {
            table.rows({page: 'current'}).select();
        } else {
            table.rows().deselect();
        }
    });

    $('#domains-grid-filterbyregistrar, #domains-grid-filter').on('change', function() {
        disableButtons();
        table.ajax.reload();
    });

    $('#importDomainButton').click(function (e) {
        RichHTML.mask();
        e.preventDefault();
        if ($(this).attr('disabled')) return false;

        var strItems = '';
        $.each(table.getSelectedRows(), function(i, val) {
            strItems += val + ' ';
        });

        $.post('index.php?fuse=clients&action=importdomain&controller=index', {
            domains: strItems,
            registrar: $('#domains-grid-filterbyregistrar').val()
        },function(data){
            table.ajax.reload();
            $('#domains_results').html(data);
            RichHTML.unMask();
        });
    });
});