$(document).on('click', '.pagination a', function (event) {
    event.preventDefault();
    ajaxLoad($(this).attr('href'));
});

$(document).on('submit', 'form[method="GET"]', function (event) {
    event.preventDefault();
    ajaxLoad($(this).attr('action') + '?' + $(this).serialize());
});

var searchTimer;
$(document).on('keyup', 'input[name="search"]', function () {
    var form = $(this).closest('form');
    clearTimeout(searchTimer);
    if (activeRequest) {
        activeRequest.abort();
        activeRequest = null;
    }
    searchTimer = setTimeout(function () {
        ajaxLoad(form.attr('action') + '?' + form.serialize());
    }, 400);
});

$(document).on('submit', 'form#frm', function (event) {
    event.preventDefault();
    var form = $(this);
    var data = new FormData($(this)[0]);
    var url = form.attr("action");
    $.ajax({
        type: form.attr('method'),
        url: url,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            $('.is-invalid').removeClass('is-invalid');
            if (data.fail) {
                for (control in data.errors) {
                    $('#' + control).addClass('is-invalid');
                    $('#error-' + control).html(data.errors[control]);
                }
            } else {
                ajaxLoad(data.redirect_url);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("Error: " + errorThrown);
        }
    });
    return false;
});

var activeRequest = null;

function ajaxLoad(filename, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    var searchFocused = $('input[name="search"]').is(':focus');

    if (activeRequest) {
        activeRequest.abort();
    }

    $('.loading').show();
    activeRequest = $.ajax({
        type: "GET",
        url: filename,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function (data) {
            activeRequest = null;
            $("#" + content).html(data);
            $('.loading').hide();
            if (searchFocused) {
                var input = $('input[name="search"]');
                input.focus();
                var len = input.val().length;
                input[0].setSelectionRange(len, len);
            }
        },
        error: function (xhr, status, error) {
            if (status !== 'abort') {
                alert(xhr.responseText);
            }
        }
    });
}

function ajaxDelete(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'DELETE', _token: token},
        url: filename,
        success: function (data) {
            window.location.href = filename.slice(0, -9);
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function ajaxDeleteComments(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'DELETE', _token: token},
        url: filename,
        success: function (data) {
            window.location.href = filename.replace("delete/", "");
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function ajaxRedirect(filename, token, content) {
    content = typeof content !== 'undefined' ? content : 'content';
    $('.loading').show();
    $.ajax({
        type: 'POST',
        data: {_method: 'PUT', _token: token},
        url: filename,
        success: function (data) {
            window.location.href = filename.slice(0, -14);
            $("#" + content).html(data);
            $('.loading').hide();
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
