var sort = $('.js-sort')

sort.each(function () {
    var url = $(this).attr('data-url');
    var toastrSuccess = $(this).attr('data-toastr-success');
    var toastrError = $(this).attr('data-toastr-error');
    $(this).find('tbody').sortable({
        handle: ".sortable-handle",
        items: "> tr",
        cancel: "",
        update: function (event, ui) {
            var lang = $('html').attr('lang');
            var selectors = $(this).find('tr');
            data = {};
            selectors.each(function (index) {
                data[$(this).data('id')] = index;
            });
            $.ajax({
                type: 'POST',
                url: url,
                dataType: "json",
                data: data,
                success: function (data, status, jqXHR) {
                    if (jqXHR.responseJSON.data.hasOwnProperty('message')) {
                        toastr['success'](jqXHR.responseJSON.data.message, toastrSuccess);
                    } else {
                        toastr['success']("", toastrSuccess);
                    }
                },
                error: function (jqXHR, status, error) {
                    if (jqXHR.responseJSON.data.hasOwnProperty('message')) {
                        toastr['error'](jqXHR.responseJSON.data.message, toastrError);
                    } else {
                        toastr['error']("", toastrError);
                    }
                }
            });
        }
    });
});

$(document).ready(function() {
    $('.js-reorder-this').click(function () {
        var thisInputValue = $(this).parent().parent().find(">:first-child").val();
        var error = false;
        if(thisInputValue < 0 ){
            $(this).parent().parent().addClass('has-error');
            var error = true;
        }
        if(error == false) {
            var url = $(this).parent().parent().find(">:first-child").attr('attr-url');
            $.ajax({
                url: url,
                type: 'POST',
                data: {value: thisInputValue},
                success: function (result) {
                    if (result == 1) {
                        location.reload();
                    }
                }
            });
        }
    });
});