/**
 * Created by David Camacho on 21/04/2015.
 */



// Add question button event
function saveAnswer(id_question) {

    insertAnswer(id_question, $('#answer_input').val(),$('#is_correct_input').val() );
}

function refreshAnswerList(){

    // ajax call starts
    $.ajax({

        type: "POST",
        url: './modules/teacher/coursesoptions/json_store_answer.php',
        data: { "get_list" : 1,
                "id_question": $('#question_id').html()
        },
        success: printAnswerList,
        dataType: 'json'
    })


}


function insertAnswer(id_question, answer, is_correct) {

    // ajax call starts
    $.ajax({

        type: "POST",
        url: './modules/teacher/coursesoptions/json_store_answer.php',
        data: { "insert" : 1,
                "id_question" : id_question,
                "answer" : answer,
                "is_correct" : is_correct},
        success: insertAnswerSuccess,
        dataType: 'json'
    })

}

function insertAnswerSuccess(ajaxResponse){

    if (ajaxResponse == false) {
        $('#answer_form_alerts').empty();
        $('#answer_form_alerts').css("display", "block");
        $('#answer_form_alerts').append("<div class='small-12 large-12 alert-box alert' >Answer not inserted. Check fields</div>");

    }
    
    refreshAnswerList();
}


function printAnswerList(ajaxResponse){

    $('#answers_list').empty();
    var html_output;
    // If no results
    if (ajaxResponse["id_answer"].length < 1) {
        $('#answers_list').append('<div class="row" >No answers</div>');
    }else {
        for (i=0; i<ajaxResponse["id_answer"].length; i++) {
            html_output = '<div class="row panel" >' +
            '<div class="small-12 large-12 columns">' +
            '<div class="columns" style=" width: 15px;" onclick="removeAnswer('+  ajaxResponse["id_answer"][i]+')">' +
            '<i class="fi-x size-18"></i></div><div class="columns" style="width:600px;float:left;">' +
            '<p style="padding-top: 1px;  float: left; width: 406px; font-weight:bolder;">';

            if (ajaxResponse["is_correct"][i] == 1)
               html_output = html_output + '<i class="fi-check size-18" style="float:left; color: green;"></i>';
            else
                html_output = html_output + '<i class="fi-x size-18" style="float:left; color: red;"></i>';


            html_output = html_output  + ajaxResponse["text"][i] + '</p>' +
            '</div>' +
            '</div>' +
            '</div>';

            $('#answers_list').append(html_output);
            html_output="";
        }

    }
}

function removeAnswer(id_question){
    // ajax call starts
    $.ajax({

        type: "POST",
        url: './modules/teacher/coursesoptions/json_store_answer.php',
        data: { "remove" : 1,
            "id_answer" : id_question
        },
        success: removeAnswerSuccess,
        dataType: 'json'
    });




}

function removeAnswerSuccess(ajaxResponse){

    refreshAnswerList();

}
