/**
 * Sortable table
 *
 * @author Elze Kool
 * @copyright Elze Kool, Kool Software en Webdevelopment
 *
 * @package KoolWebshop
 **/


(function($, undefined) {

    $(function() {

        $('.sortable-table-form').each(function() {
            
            var form = $(this);

            var table = form.find('.sortable-table');

            // Maak tabel rijen sorteerbaar
            table.find('tbody').sortable({
                helper: function(e, ui) {
                    ui.children().each(function() {
                        $(this).width($(this).width());
                    });
                    return ui;
                }
            }).disableSelection();

            table.on("sortupdate", function(event, ui) {

                var toon_opslaan = false;

                var volgorde_items = table.find('.sortable-table-field');
                var cnt = 0;
                volgorde_items.each(function() {
                    var el = $(this);

                    if (form.attr('data-sort-direction') === 'ASC') {
                        el.val(cnt + 1);
                    } else {
                        el.val(volgorde_items.length - cnt);
                    }

                    cnt++;

                    var tr = el.parents('tr:first');
                    if (el.val() !== el.attr('data-org-value')) {
                        tr.addClass('success');
                        tr.find('.sortable-table-field-org').removeClass('hide');
                        toon_opslaan = true;
                    } else {
                        tr.removeClass('success');
                        tr.find('.sortable-table-field-org').addClass('hide');
                    }

                });

                if (toon_opslaan) {
                    form.find('.sortable-table-save').removeClass('hide');
                    form.find('.sortable-table-description').addClass('hide');
                } else {
                    form.find('.sortable-table-save').addClass('hide');
                    form.find('.sortable-table-description').removeClass('hide');
                }


            });

        });

    });


})(jQuery);