define(['jquery'], function () {
    return function (quiz_id) {

        /**
         * Sortable question list
         */
        $('#questionList').sortable({
            handle: '.js-question-handle',
            update: function () {
                // Grab the new sort order values, keyed by question IDs
                var questionSortOrders = {};

                $('.question-panel').each(function (index, elem) {
                    var $listItem = $(elem);

                    questionSortOrders[$listItem.data('question-id')] = $listItem.index();
                });

                // TODO: Localize the messages
                $.ajax('/api/quiz/v1/' + quiz_id + '/questions/sort', {
                    'method': 'POST',
                    'data': questionSortOrders,
                    'success': function () {
                        cla.showMessage('Updated question sort order');
                    },
                    'error': function () {
                        cla.showMessage('Failed to update question sort order', null, true);
                    }
                });
            }
        });

        // delete question modal window
        $(".js-delete-modal").click(function () {
            var question_id = parseInt($(this).data('question'));
            $("#delete-question-form").attr({action: '/quiz/' + quiz_id + '/' + question_id + '/delete'});
            $("#delete-question-modal").modal('show');
        });

        // tab change, make sure page reloads render the correct tab
        var url = document.location.toString();
        if (url.match('#')) {
            $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
        }
        $('.nav-tabs a').on('shown.bs.tab', function (e) {
            window.location.hash = e.target.hash;
        });

        $("#js-quiz_preview").click(function () {
            $.post('/api/quiz/v1/' + quiz_id + '/preview', {}, function () {
                window.location.href = '/quiz/' + quiz_id + '#/';
            });
        });

    };
});
