;(function($, window, document, undefined) {

    'use strict';

    // Create the defaults once
    var pluginName = "customButtons",
        defaults = {
            group: 1,
            table: null,
            buttons: [],
            container: '#dt-header',
            dom: {
                container: {
                    className: 'dt-buttons btn-group dt-margin-right'
                }
            }
        };

    // The actual plugin constructor
    function Plugin (element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this.table = this.settings.table || $(element).DataTable();
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    // Avoid Plugin.prototype conflicts
    $.extend(Plugin.prototype, {
        init: function() {
            new $.fn.dataTable.Buttons(this.table, {
                dom: this.settings.dom,
                buttons: this.settings.buttons
            });

            this.table.on('select.dt', $.proxy(this.toggle, this, 'select'));
            this.table.on('deselect.dt', $.proxy(this.toggle, this, 'deselect'));

            this.apply();
        },
        toggle: function(type, e, dt) {
            var selected = dt.column(0).checkboxes.selected();
            var button = dt.buttons(this.settings.group, null)[0];

            this.getDisabledButtons(button).map($.proxy(function(index) {
                dt.buttons(this.settings.group, index)[(selected.length) ? 'enable' : 'disable']();
            }, this));
        },
        getDisabledButtons: function(button) {
            var indices = [];
            for (var b in button.inst.c.buttons) {
                if (button.inst.c.buttons.hasOwnProperty(b)) {
                    var btn = button.inst.c.buttons[b];
                    if (btn.hasOwnProperty('enabled') && !btn.enabled) {
                        indices.push(b);
                    }
                }
            }
            return indices;
        },
        apply: function() {
            this.table.buttons(this.settings.group, null)
                .container()
                .prependTo($(this.settings.container));
        }
    } );

    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);
