/**
 * /script/quizedit.js
 * @version 1.9
 * @desc Script file for creating and editing tests
 * @author Fándly Gergő Zoltán (gergo@systemtest.tk, systemtest.tk)
 * @copy 2017 Fándly Gergő Zoltán
 * License:
    sQuiz for creating small jQuery based quizs in an implementable way
    Copyright (C) 2017  Fándly Gergő Zoltán

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

function appendNewField(type){
    $("<div>"+$("#newPrototypes div[data-type="+type+"]").html()+"</div>").hide().appendTo($("#questions")).slideDown();
}

function removeField(el){
    $(el).parent().slideUp(function(){
        $(el).parent().remove();
    });
}

function addNewAnswer(el){
    $("<div>"+$(el).data("append")+"</div>").hide().appendTo($(el).parent().children("[name=answers]")).slideDown();
}

function toggleGoodAnswer(el){
    if($(el).hasClass("fa-square")){
        $(el).removeClass("fa-square").addClass("fa-check-square");
        $(el).next().data("correct", "true");
    }
    else{
        $(el).removeClass("fa-check-square").addClass("fa-square");
        $(el).next().data("correct", "false");
    }
}

function addNewFillInField(el){
    $(el).parent().children("textarea").selection("insert", {text:"[]", mode:"before"});
    $(el).parent().children("textarea").selection("insert", {text:"[/]", mode:"after"});
}

//map funcs
function loadMap(el){
    var file=$(el).parent().children("input[type=file]")[0].files[0];
    var fr=new FileReader();
    fr.onload=function(){
        loadMapCallback(el, fr.result);
    };
    fr.readAsDataURL(file);
}
function loadMapCallback(el, res){
    $(el).parent().children("div").children("img").attr("src", res);
    $(el).parent().children("input[name=map]").val(res);
}

function addNewMarker(el){
    $(el).parent().children("div[name=mapArea]").css("cursor", "crosshair");
    $(el).parent().children("div[name=mapArea]").on("click", function(e){
        var x=Math.round(e.pageX-$(this).position().left)-7;
        var y=Math.round(e.pageY-$(this).position().top)-7;
        $("<i class=\"fa fa-circle\" style=\"position: absolute; top: "+y.toString()+"px; left: "+x.toString()+"px\" data-posx=\""+x.toString()+"\" data-posy=\""+y.toString()+"\" data-correct=\"false\" onclick=\"toggleGoodMarker(this)\"></i>").hide().appendTo($(el).parent().children("div[name=mapArea]").children("div[name=markers]")).fadeIn();
        $(el).parent().children("div[name=mapArea]").css("cursor", "default");
        $(el).parent().children("div[name=mapArea]").off();
    });
}

function removeMarker(el){
    $(el).parent().children("div[name=mapArea]").children("div[name=markers]").children("i").css("cursor", "crosshair");
    $(el).parent().children("div[name=mapArea]").children("div[name=markers]").children("i").on("click", function(e){
        $(this).fadeOut(function(){
            $(this).remove();
        });
        $(el).parent().children("div[name=mapArea]").children("div[name=markers]").children("i").css("cursor", "default");
        $(el).parent().children("div[name=mapArea]").children("div[name=markers]").children("i").off();
    });
}

function toggleGoodMarker(el){
    if($(el).hasClass("fa-circle")){
        $(el).removeClass("fa-circle").addClass("fa-check-circle");
        $(el).data("correct", "true");
    }
    else{
        $(el).removeClass("fa-check-circle").addClass("fa-circle");
        $(el).data("correct", "false");
    }
}


//export, cancel
function resetNewQuizForm(){
    if(confirm(lang.sure)){
        $("#newquizcontainer").slideUp(function(){
            $("#newquiz")[0].reset();
            $("#questions").html("");
            $("input[name=timeLimitPerTestVal]").css("display", "none");
            $("input[name=timeLimitVal]").css("display", "none");
            $("input[name=onlineTag]").css("display", "none");
            $("#newquizcontainer").slideDown();
        });
    }
}

function exportQuiz(){
    var exp={};
    //general settings
    exp.name=$("#newquiz #general input[name=name]").val();
    exp.description=$("#newquiz #general textarea[name=description]").val();
    exp.timeLimitPerTest=$("#newquiz #general input[name=timeLimitPerTest]").is(":checked")?$("#newquiz #general input[name=timeLimitPerTestVal]").val():-1;
    exp.timeLimit=$("#newquiz #general input[name=timeLimit]").is(":checked")?$("#newquiz #general input[name=timeLimitVal]").val():-1;
    var publish=$("#newquiz #general input[name=submitOnline]").is(":checked");
    
    exp.questions=[];
    //questions
    $("#newquiz #questions").children("div").each(function(){
        var q={};
        q.type=$(this).children("input[name=type]").val();
        
        if(q.type=="simpleQuestion"){
            q.question=$(this).children("input[name=question]").val();
            q.answer=$(this).children("input[name=answer]").val().toLowerCase();
        }
        else if(q.type=="simpleSelect"){
            q.question=$(this).children("input[name=question]").val();
            q.answers=[];
            $(this).children("fieldset[name=answers]").children("div").each(function(){
                var a={};
                a.answer=$(this).children("input[name=answer]").val();
                a.correct=($(this).children("input[name=answer]").data("correct")=="true")?true:false;
                q.answers.push(a);
            });
        }
        else if(q.type=="connectGraph"){
            q.question=$(this).children("input[name=question]").val();
            q.answers=[];
            $(this).children("fieldset[name=answers]").children("div").each(function(){
                var a={};
                a.pair1=$(this).children("input[name=pair1]").val();
                a.pair2=$(this).children("input[name=pair2]").val();
                q.answers.push(a);
            });
        }
        else if(q.type=="fillIn"){
            q.question=$(this).children("input[name=question]").val();
            q.text=$(this).children("textarea[name=text]").val();
        }
        else if(q.type=="markOnMap"){
            q.question=$(this).children("input[name=question]").val();
            q.map=$(this).children("input[name=map]").val();
            q.markers=[];
            $(this).children("div[name=mapArea]").children("div[name=markers]").children("i").each(function(){
                var m={};
                m.posx=$(this).data("posx");
                m.posy=$(this).data("posy");
                m.correct=($(this).data("correct")=="true")?true:false;
                q.markers.push(m);
            });
        }
        
        exp.questions.push(q);
    });
    
    var json=JSON.stringify(exp);
    
    if(publish){
        $.ajax({
            url: "./engine/engine.php",
            type: "POST",
            data: {
                "submitQuiz": json,
                "submitQuiz_tag": $("#newquiz #general input[name=onlineTag]").val(),
                "submitQuiz_name": $("#newquiz #general input[name=name]").val(),
                "submitQuiz_description": $("#newquiz #general textarea[name=description]").val()
            },
            success: function(res){
                alert(lang.availableAtURL+": "+res);
            }
        });
    }
    
    var send="text/json;charset=utf-8,"+encodeURIComponent(json);
    $("<a href=\"data:"+send+"\" download=\""+exp.name+"_sQuiz.json\"></a>")[0].click();
}
