define(['jquery'], function ($) {
    // Keep track of variables needed for "show more" and filtering
    var options = {
        offset: 0,
        limit: 12,
        type: 0,                 // Default to AttemptableType::TYPE_ALL
        keywords: ''
    };

    function applyCards(body) {
        if (body.trim() === '')
        {
            $('.js-cards').hide();
            $('.js-no-results').show();
        } else
        {
            // Use the quiz cards HTML as the list
            $('.js-no-results').hide();
            $('.js-cards').show();
        }

        $('.js-cards').html(body);
    }

    // Set up initial view
    applyCards($('.js-cards').html() || '');

    return function (type, paginationLimit) {
        if (paginationLimit !== undefined)
            options.limit = paginationLimit;
        if (type !== undefined)
            options.type = type;

        // Compile the underscore template that lists current user attempts
        var template = _.template($('.js-edit-modal-attempts-template').html());

        // Listen for click events on quiz edit links
        $('.js-cards').on('click', '.js-quiz-link-edit', function (event) {

            var card = $(event.target);
            var data = card.data();
            var modal;
            var endpoint;
            var loc_key;
            var no_attempt_key;

            // We don't need to show this modal for non-live quizzes, or live
            // quizzes that haven't been attempted
            if (!data.statusLive || !data.attempts) {
                return;
            }

            if (data.is_survey) {
                // Show the modal
                modal = $('#edit-modal-survey');
                endpoint = '/api/quiz/v2/surveys/' + data.objectId + '/attempts?completed=0';
                loc_key = 'quiz.admin.edit_live_survey_attempts_count';
                no_attempt_key = 'quiz.admin.edit_live_survey_attempts_none';
            } else {
                modal = $('#edit-modal-poll');
                endpoint = '/api/quiz/v2/polls/' + data.objectId + '/attempts?completed=0';
                loc_key = 'quiz.admin.edit_live_poll_attempts_count';
                no_attempt_key = 'quiz.admin.edit_live_poll_attempts_none';
            }

            // Reset the incomplete attempts blocks
            modal.find('.js-edit-modal-attempt-count').html(lmsg(no_attempt_key));
            modal.find('.js-edit-modal-attempts').html(null);

            modal.find('.js-loading-spinner').show();
            modal.find('.js-edit-modal-attempt-count').hide();

            // Load the incomplete attempts
            $.get(endpoint, function (data) {
                // Only list attempts if we have at least one
                if (data.total > 0) {

                    // Update the count of current attempts
                    modal.find('.js-edit-modal-attempt-count').html(lmsg(loc_key, data.total));

                    // Use the underscore template to print the list of attempts
                    $('.js-edit-modal-attempts').html(template(data));
                }

                modal.find('.js-loading-spinner').hide();
                modal.find('.js-edit-modal-attempt-count').show();
            }).fail(function (xhr) {
                cla.showMessage(lmsg('quiz.error.load_current_attempts'), null, true);
            });

            // Show the modal
            modal.modal({
                show: true
            });

            var path;
            if (data.is_survey)
            {
                path = '/polls-surveys/survey/';
            }else
            {
                path = '/polls-surveys/poll/';
            }
            $('.js-edit-anyway').attr('href', path + data.objectId + '/edit');

            event.preventDefault();
        });

        // Listen for click events on the show more button
        $('.js-show-more').on('click', function (event) {
            var button = $(event.target);

            options.offset = button.data('offset');

            // Disable the button until loading is complete
            button.attr('disabled', true);

            $.get('/polls-surveys/list', options, function (data) {
                // Append the quiz cards HTML to the list
                $('.js-cards').append(data.html);

                // Update the offset for the next load
                button.data('offset', data.nextOffset);

                // Re-enable the button
                button.removeAttr('disabled');

                $('.poll-survey-card-wrapper').removeClass("cla-hide-component");

                if (!data.nextOffset)
                    button.hide();
                else
                    button.show();
            }).fail(function () {
                cla.showMessage(lmsg('quiz.error.show_more'), null, true);
            });
        });

        $('#keywordFilter').on('keyup', _.debounce(function() {
            var button = $('.js-show-more');

            options.keywords = $(this).val();

            // Reset to first page
            options.offset = 0;

            // Disable the "Show more" button until loading is complete
            button.attr('disabled', true);

            $.get('/polls-surveys/list', options, function (data) {
                applyCards(data.html);

                // Update the offset for the next load
                button.data('offset', data.nextOffset);

                // Re-enable the button
                button.removeAttr('disabled');

                if (!data.nextOffset)
                    button.hide();
                else
                    button.show();
            }).fail(function () {
                cla.showMessage(lmsg('quiz.error.show_more'), null, true);
            });
        }, 300));
    };
});
