$("#selectAll").on('change', function () {
    if ($(this).prop('checked') == true) {
        $('.allCamps').prop('checked', true);
        $("#deleteBtn").show();
    } else {
        $('.allCamps').prop('checked', false);
        $("#deleteBtn").hide();
    }
});

$(".allCamps").on('change', function () {
    if ($(this).prop('checked') == true) {
        $("#deleteBtn").fadeIn();

    } else {
        var camps = [];

        $('input:checkbox.allCamps').each(function () {
            if ($(this).prop('checked') == true) {
                camps.push($(this).val());
            }
        });

        if (camps.length == 0) {
            $("#selectAll").prop('checked', false);
            $("#deleteBtn").hide();
        } else {
            $("#deleteBtn").show();
        }
    }
    var camps = [];
});

function deleteAll() {
    var dCamps = [];

    $('input:checkbox.allCamps').each(function () {
        if ($(this).prop('checked') == true) { dCamps.push($(this).val()); }
    });

    if(dCamps != '') {
        swal({
            title: 'Are you sure?',
            text: 'Do you want to delete ?',
            buttons: ['No', 'Yes'],
        })
            .then((value) => {
                if (value) {

                    $.ajax({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url: '/campaign/campaign_delete',
                        data: {
                            camps: dCamps
                        },
                        success: function () {
                            window.location.reload();
                        }
                    });
                }
            });
    } else {
        swal({text: 'Nothing Selected', buttons: false, timer: 500});
    }
    
}

$(document).ready(function () {
    $("#page_id").val(1);
    getdata();
});

function getdata() {
    var page_id = $("#page_id").val();
    var search = $("#search").val();

    $.ajax({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        dataType: 'html',
        url: "/campaigns?page=" + page_id,
        data: "",
        async: false,
        success: function (result) {
            $("#data_div").append(result);
            var pg = $("#page_id").val();
            $("#page_id").val(+pg + 1);
        }
    });
}

$("#search").on('keyup', function (e) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        dataChange();
    }

    if (e.keyCode == 13) {
        dataChange();
    }
});

function dataChange() {
    $("#page_id").val(1);
    $("#data_div").html('');
    getdata();
}

$(window).scroll(function () {
    if ($(document).height() == $(window).scrollTop() + $(window).height()) {
        if (+$("#last_page").val() >= +$("#page_id").val()) {
            getdata();
        }
    }
});