(function ($) {
    $(document).ready(function () {
        var url_ajax = tx_dashboard.admin_ajax;

        check_empty_column();

        $('.txw-dashboard-wrapper')
            .sortable({
                placeholder: "txw-ui-state-highlight",
                opacity: 0.8,
                handle: '.txw-box-header',
                items: '.txw-box',
                cursor: 'move',
                appendTo: '.txw-sortable',
                update: function (event, ui) {
                    var data = {};

                    $('.txw-sortable').each(function () {
                        var self = $(this);
                        var boxes = self.find('> *');
                        var col = self.attr('data-column');
                        var boxesArr = [];
                        boxes.each(function () {
                            var b = $(this);
                            boxesArr.push(b.attr('data-id'));
                        });
                        data[col] = boxesArr;
                    });

                    check_empty_column();

                    _request(data);
                }
            });

        function check_empty_column() {
            $('.txw-sortable').each(function () {
                var self = $(this);
                self.removeClass('txw-sortable-empty');
                self.find('.txw-box-temporary').remove();
                var boxes = self.find('> *');
                if (boxes.length === 0) {
                    self.addClass('txw-sortable-empty');
                    self.html('<div class="txw-box ui-sortable-handle txw-box-temporary"></div>');
                }
            });
        }

        function _request(data) {
            window.onbeforeunload = function() {
                return '';
            };

            $.ajax({
                method: 'POST',
                url: url_ajax,
                data: data,
                complete: function () {
                    window.onbeforeunload = null;
                }
            })
        }
    });
})(jQuery);
