topic.js 5.47 KB
$.fn.extend({
    animateCSS: function (animation, run_on_end) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        this.addClass('animated ' + animation).one(animationEnd, function() {
            $(this).removeClass('animated ' + animation);
            if (run_on_end !== undefined) {
                run_on_end();
            }
        });
    }
});

function showTriesLeft(tries) {
    var msg;
    if (tries > 1)
        msg = "(" + tries + " tentativas)";
    else if (tries == 1)
        msg = "(1 tentativa)";
    else
        msg = "";
    $("#tries").html(msg);
}

// Get current question
function getQuestion() {
    $("#comments").html("").hide();
    $("#submit").addClass("disabled");
    $.ajax({
        type: "GET",
        url: "/question",
        dataType: "json", // expected from server
        success: updateQuestion,
        error: function() {alert("O servidor não responde.");}
    });
}

// updates question in the page according to the response given by the server
function updateQuestion(response) {
    var params = response["params"];

    $("#right, #wrong").hide();

    switch (response["method"]) {
    case "new_question":
        new_question(params["type"], params["question"], params["tries"], params["progress"]);
        break;
    case "finished_topic":
        $('#submit, #comments, #solution').remove();
        $("#content").html(params["question"]).animateCSS('tada');
        $('#topic_progress').css('width', '100%').attr('aria-valuenow', 100);
        setTimeout(function(){window.location.replace('/course/');}, 2000);
        break;
    }
}

function new_question(type, question, tries, progress) {
    window.scrollTo(0, 0);

    $("#submit").hide();
    $("#question_div").animateCSS('bounceOutUp', function() {
        $("#question_div").html(question);
        MathJax.typeset();
        $("#question_div").animateCSS('bounceInDown', function() {
            showTriesLeft(tries);
            $("#submit").removeClass("disabled").show();

            // disable enter in some question types (prevent submission on enter)
            $("input:text, input:radio, input:checkbox").keydown(function (e) {
                if (e.keyCode == 13 || e.keyCode == 169) {
                    e.preventDefault();
                    return false;
                }
            });
        });
    });
    var btntext = (type == "information") ? "Continuar" : "Responder";
    $("#submit").html(btntext).off().click(postAnswer);
    $('#topic_progress').css('width', (100*progress)+'%').attr('aria-valuenow', 100*progress);

    if (type == "radio") {
        $(".list-group-item").click(function (e) {
            var index = $(this).index();
            $("div.list-group input:radio").eq(index).prop("checked", true);
        });
    }
}


// ===========================================================================
// Send answer and receive a response with the result of the correction.
// The response can be right, try_again or wrong.
// A new question is not loaded. To load questions a GET is required.
function postAnswer() {
    if (typeof editor === 'object')
        editor.save();

    $.ajax({
        type: "POST",
        url: "/question",
        data: $("#question_form").serialize(), // {'a':10,'b':20},
        dataType: "json", // expected from server
        success: getFeedback,
        error: function() {alert("O servidor não responde.");}
    });
    $("#submit").addClass("disabled").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
    $("fieldset").prop("disabled", true);
}

function getFeedback(response) {
    var params = response["params"];

    if (params["type"] == "information") {
        getQuestion();
        return;
    }

    switch (response["method"]) {
    case "right":
        $('#wrong').hide();
        $('#comments').html(params['comments']).show();
        $('#solution_right').html(params['solution']);
        MathJax.typeset();
        $('#right').show().animateCSS('zoomIn', function(){
            $("#submit").html("Continuar").removeClass("disabled").off().click(getQuestion);
        });
        break;

    case "try_again":
        $('#comments').html(params['comments']).show();
        MathJax.typeset();
        $('#topic_progress').css('width', (100*params["progress"])+'%').attr('aria-valuenow', 100*params["progress"]);
        $('#question_div').animateCSS('shake', function() {
            showTriesLeft(params["tries"]);
            $("fieldset").prop("disabled", false);
            $("#submit").html("Responder").removeClass("disabled");
        });
        break;

    case "wrong":
        $("fieldset").prop("disabled", true);
        $('#right').hide();
        $('#comments').html(params['comments']).show();
        $('#solution_wrong').html(params['solution']);
        MathJax.typeset();
        $('#question_div').animateCSS('shake', function() {
            showTriesLeft(params["tries"]);
            $('#wrong').show().animateCSS('zoomIn', function() {
                $("#submit").html("Continuar").removeClass("disabled").off().click(getQuestion);
            });
        });
        $('#topic_progress').css('width', (100*params["progress"])+'%').attr('aria-valuenow', 100*params["progress"]);
        break;

    case "invalid":
        alert(params["msg"]);
        break;
    }
}

// ===========================================================================
$(document).ready(function() {
    getQuestion();
    $("#submit").click(postAnswer);
});