$(document).ready(function(){
   $(document).on("click",".ex-check",function(e){
       e.preventDefault();
       renshu.check($(this));
   })
    
    $(document).on("submit",".renshu-form",function(e) {
        e.preventDefault();
        renshu.check($(this).find(".ex-check"));
    });
   
   $(document).on("click",".renshu-timer .start",function(e){
      e.preventDefault();
      renshu.timer($(this));
   });
});

renshu = {
    jsonResultClone:{},
    check:function( $root ) {
        var scope = this;
        var $form = $root.closest("form");
        $params = $form.serialize();
        this.checkAction($form,$params,false);
        this.showDetails($form);
        this.endWhenTimerNoZero($form);
    },
    checkAction:function($form,$params,avoidempty) {
        var scope = this;
        var addParameters = "";
        if ($form.find(".chrono").length) {
            avoidempty = true;
            addParameters = "&timer="+$form.find(".chrono").text();
        }
        $.post($form.attr("action"),$params+"&avoidempty="+avoidempty+addParameters,function(jsonResult){
            scope.jsonResultClone = jsonResult;
            var isEmpty = false;
            $form.find("select.renshu-select, .renshu-text").removeClass("renshu-is-empty");
            if (jsonResult.result == true) {
                $.each(jsonResult.data,function(i,v){
                    if (v.result=="empty") {
                        isEmpty = v.msg;
                        $($("select.renshu-select").get(i)).addClass("renshu-is-empty");
                        $($(".renshu-text").get(i)).addClass("renshu-is-empty");
                    }
                });
                if(isEmpty) {
                    bootbox.confirm(isEmpty,function(ok) {
                        if (ok == true) {
                            scope.checkAction($form,$params,true);
                        }
                    });
                    $(".bootbox.modal").css({"z-index":"3489248200093842"})
                    scope.actions();
                } else {
                    scope.showResults($form,jsonResult.data);
                    $(".ex-details").removeClass("d-none");
                }
            } else {
                bootbox.alert(jsonResult.msg);
                $(".bootbox.modal").css({"z-index":"3489248200093842"})
            }
        },"json");
        
    },
    actions: function() {
        $(".renshu-select").change(function () {
            if ($(this).val() != "") {
                $(this).removeClass("renshu-is-empty");
            } else {
                $(this).addClass("renshu-is-empty");
            }
        });
    },
    showResults: function($form,data) {
        var scope = this;
        var target = "select.renshu-select, .renshu-text";
        $form.find(".renshu-msg-area-top").html(data.html);
        $form.find(".renshu-comment").remove();
        $form.find(target).each(function(i){
            $(this).removeClass("renshu-is-right");
            $(this).removeClass("renshu-is-wrong");

            if (data[i].result=="right") {
                $(this).addClass("renshu-is-right");
                $(this).attr("data-comment","");
            }
            if (data[i].result=="wrong") {
                $(this).addClass("renshu-is-wrong");
                if (typeof data[i].comment != "undefined") {
                    $(this).attr("data-comment",data[i].comment);
                }
            }
            if (data.score == 100) {
                $(this).prop("disabled","true");
            }
        });
        if (data.score == 100) {
            $form.find(".ex-check").addClass("d-none");
            $form.find(".ex-retry").removeClass("d-none");
        }
        if ($form.attr("data-avoidscroll")=="1") {

        }else {
            $(window).scrollTop( $form.position().top  - 32);

        }

        $form.find(".ex-retry").click(function(e){
            e.preventDefault();
            scope.timerEnd($form.find(".ex-check"));
            scope.rollback($form,target);
        });
    },
    rollback: function($form,target) {
        
        $form.find(".ex-check").removeClass("d-none");
        $form.find(".ex-retry").addClass("d-none");
        $form.find(".ex-retry").closest("form").find(".renshu-comment").remove();
        $form.find(".renshu-msg-area-top").html("");
        $form.find(".renshu-msg-area-bottom").html("");
        this.hideDetails($form);
 
        $form.find(target).each(function(i) {
            $(this).removeClass("renshu-is-right");
            $(this).removeClass("renshu-is-wrong");
            $(this).prop("disabled",false);
            $(this).attr("data-comment","");
            $(this).val("");
            if ($form.attr("data-avoidscroll")=="1") {

            }else {
                $(window).scrollTop($form.position().top - 32);
            }
        });
    },
    showDetails:function($form) {
        var scope = this;
        $(".ex-details").click(function(e){
            scope.showDetailsAction($form);
        });
    },
    showDetailsAction:function($form) {
        var scope = this;
        var rightAnswers = scope.jsonResultClone.rightAnswers;
        var comments = scope.jsonResultClone.comments;
        var target = "select.renshu-select, .renshu-text";
        $form.find(".renshu-details").remove();
        $form.find(target).each(function(i) {
            var $parsedElement = $(this);
            var givenAnswer = $parsedElement.val();
            if ($(this).hasClass("renshu-is-wrong")) {
                if (rightAnswers[i]!="") {
                    var strRightAnswers = rightAnswers[i].join(", ");
                    $(this).after("<div class='renshu-details renshu-right-answer'><span class='fa fa-check'>&nbsp;"+strRightAnswers+"</span></div>");
                }
            } else {
                if (typeof comments[i] != "undefined") {
                    $.each(rightAnswers[i],function(answerIndex,answerValue){
                        if (givenAnswer == answerValue && typeof comments[i][answerIndex] != "undefined") {
                            $parsedElement.after("<div class='renshu-details renshu-comment'><i class='fa fa-exclamation-triangle'></i>&nbsp;"+comments[i][answerIndex]+"</div>");
                        }
                    });
                }
            }
        });
    },
    hideDetails:function($form) {
        $form.find(".renshu-details").remove();
        $(".ex-details").addClass("d-none");
    },
    timer:function($root) {
        var scope = this;
        var $target = $root.closest(".renshu-timer").find("select[name=timer]");
        if ($target.val() == "") {
            bootbox.alert("Selezionare un valore");
            $(".bootbox.modal").css({"z-index":"3489248200093842"})

        } else {
            scope.timerStart($root);
        }
    },
    timerStart:function($root) {
        var scope = this;
        $root.closest(".renshu-timer-selection").hide();
        $(".renshu-block").hide();
        $root.closest(".renshu-block").show();
        $root.closest(".renshu-block").find(".renshu-timer-display").show();
        var $target = $root.closest(".renshu-timer").find("select[name=timer]");
        var startSeconds = parseInt($target.val())+1;
        //var eventEndUrl = JBASE_URL+LANG.label+"renshu/timerEnd";
        var $targetDisplay = $root.closest(".renshu-timer").find(".renshu-timer-display");
        $(".fixed-breadcrumb-inner").after("<div class='container fixed-timer'>&nbsp;</div>");
        var target = "select.renshu-select, .renshu-text";
        scope.rollback($root.closest("form"),target);
        scope.eventClock(startSeconds,"chrono",$targetDisplay,$root);
    },
    timerEnd:function($root) {
        var scope = this;
        $root.closest(".renshu-block").find(".renshu-timer-selection").show();
        $(".renshu-block").show();
        $(".fixed-timer").remove();
        $root.closest(".renshu-block").find(".renshu-timer-display").hide();
        if (typeof setEventClockVar != "undefined") {
            clearInterval(setEventClockVar);
        }
    },
    endWhenTimerNoZero:function($form) {
        if ($(".chrono").length) {
            $(".renshu-block").show();
            if (typeof setEventClockVar != "undefined") {
                clearInterval(setEventClockVar);
            }
            $form.find(".ex-check").addClass("d-none");
            $form.find(".ex-retry").removeClass("d-none");
        }
    },
    eventClock:function(startSeconds,lang,targetDom,$root) {
        var scope = this;
        if (typeof setEventClockVar != "undefined") {
            clearInterval(setEventClockVar);
        }
        if ($(targetDom).length) {
            $destDom = $(targetDom);
            var oNow = new Date();
            var countDownDate = new Date();
            countDownDate.setSeconds(countDownDate.getSeconds()+parseInt(startSeconds));
            var interval = 1000;
            var counter = 0;
            setEventClockVar = setInterval(function() {
                
                oNow.setSeconds(oNow.getSeconds()+1);
                //counter++;
                var now = oNow.getTime();
                // Find the distance between now an the count down date
                var distance = countDownDate - now;
                
                // Time calculations for days, hours, minutes and seconds
                var days = Math.floor(distance / (interval * 60 * 60 * 24));
                var hours = Math.floor((distance % (interval * 60 * 60 * 24)) / (interval * 60 * 60));
                var minutes = Math.floor((distance % (interval * 60 * 60)) / (interval * 60));
                var seconds = Math.floor((distance % (interval * 60)) / interval);
                var addhZero = addmZero = addsZero = "";
                switch(lang) {
                    default:
                    case "en":
                        var daysLabel = "d ";
                        var hoursLabel = "h ";
                        var minutesLabel = "m ";
                        var secondsLabel = "s ";
                        var daysStr = (days>0)? days + daysLabel : "";
                        var hoursStr = (hours>0)? addhZero+hours + hoursLabel : "";
                        var minutesStr = (minutes>0)? addmZero+minutes + minutesLabel : "";
                        var secondsStr = (seconds>0)? addsZero+seconds + secondsLabel : "";
                        break;
                    case "ja":
                        var daysLabel =  "日 ";
                        var hoursLabel = "時 ";
                        var minutesLabel = "分 ";
                        var secondsLabel = "秒 ";
                        var daysStr = (days>0)? days + daysLabel : "";
                        var hoursStr = (hours>0)? addhZero+hours + hoursLabel : "";
                        var minutesStr = (minutes>0)? addmZero+minutes + minutesLabel : "";
                        var secondsStr = (seconds>0)? addsZero+seconds + secondsLabel : "";
                        
                        break;
                    case "chrono":
                        var daysLabel = "d ";
                        var hoursLabel = ":";
                        var minutesLabel = ":";
                        var secondsLabel = "";
                        if (hours<10) {
                            addhZero = "0";
                        }
                        if (minutes<10) {
                            addmZero = "0";
                        }
                        if (seconds<10) {
                            addsZero = "0";
                        }
                        var daysStr = (days>0)? days + daysLabel : "";
                        var hoursStr = (hours>0)? addhZero+hours + hoursLabel : "";
                        var minutesStr =  addmZero+minutes + minutesLabel;
                        var secondsStr =  addsZero+seconds + secondsLabel;
                        break;
                }
                
                var h = "<span class='chrono'>"+daysStr + hoursStr + minutesStr + secondsStr+"</span>";
                $destDom.html(h);
                $(".fixed-timer").html(h);
                if (distance <= 0) {
                    clearInterval(setEventClockVar);
                    if (typeof $root != "undefined") {
                        bootbox.alert("Il tempo è scaduto. Chiudi questo popup per vedere i risultati");
                        $(".bootbox.modal").css({"z-index":"3489248200093842"})

                        scope.check($root);
                        setTimeout(function(){
                            scope.timerEnd($root);
                        },300);
                    }
                }
            }, interval);
        }
    }
    
}