$(function () {
    dynAction();
    // Per page
    $('select[name=perpage]').change(function () {
        var form = $('#data_{unique} form');
        form.find('input[name=page]').val('0');
        formSubmit(form);
    });

    // Order by
    $('.orderBy').click(function () {
        var el = $(this);
        var form = $('#data_{unique} form');
        var order = form.find('input[name=order]');
        var orderType = form.find('input[name=ordertype]');
        if (order.val() === el.attr('href')) {
            if (orderType.val() === '1') {
                orderType.val('0');
            } else {
                orderType.val('1');
            }
        } else {
            order.val($(this).attr('href'));
            orderType.val('0');
        }
        formSubmit(form);

        // Set arrow
        var arrow = $(this);
        if (arrow.hasClass('arrow-up')) {
            arrow.removeClass('arrow-up').addClass('arrow-down');
        } else {
            form.find('.orderBy').each(function () {
                $(this).attr('class', 'orderBy');
            });
            arrow.removeClass('arrow-down').addClass('arrow-up');
        }

        return false;
    });

    // Check/Uncheck all
    $('.check_all').change(function () {
        $('#data_{unique} input[type=checkbox]').prop('checked', $(this).prop('checked'));
    });

    // Search
    $('#data_{unique} form').submit(function () {
        formSubmit($(this));

        return false;
    });
    $('.searchbtn').click(function () {
        var form = $('#data_{unique} form');
        formSubmit(form);

        return false;
    });
    $('.clearbtn').click(function () {
        $('#data_{unique} form input[name=searchtext]').val('');
        var form = $('#data_{unique} form');
        formSubmit(form);

        return false;
    });
});

function formSubmit(form) {
    form.addClass('formWait');
    $.post('', form.serialize(), function (data) {
        var obj = jQuery.parseJSON(data);
        form.find('tbody').html(obj.data);
        form.find('.pagination ul').html(obj.pagination);
        dynAction();
        form.removeClass('formWait');
        if (obj.pagination == '') {
            location.reload();
        }
    });
}

function doAction(actionVal, message, el, isMulti) {
    var form = el.parents('form');
    if (!isMulti) {
        form.find('input[type=checkbox]').prop('checked', false);
        el.parents('tr').find('input[type=checkbox]').prop('checked', true);
    }

    if (form.find('input[type=checkbox]:checked').length > 0) {
        if (confirm(message)) {
            var action = form.find('input[name=action]');
            action.val(actionVal);
            formSubmit(form);
            action.val('');
        }
        form.find('input[type=checkbox]').prop('checked', false);
    }
}