/* Minification failed. Returning unminified contents.
(1,17): run-time error CSS1031: Expected selector, found '='
(1,17): run-time error CSS1025: Expected comma or open brace, found '='
(2,20): run-time error CSS1031: Expected selector, found ';'
(2,20): run-time error CSS1025: Expected comma or open brace, found ';'
(3,19): run-time error CSS1031: Expected selector, found '='
(3,19): run-time error CSS1025: Expected comma or open brace, found '='
(4,10): run-time error CSS1031: Expected selector, found ';'
(4,10): run-time error CSS1025: Expected comma or open brace, found ';'
(5,16): run-time error CSS1031: Expected selector, found ';'
(5,16): run-time error CSS1025: Expected comma or open brace, found ';'
(6,10): run-time error CSS1031: Expected selector, found 'f_beforeunload('
(6,10): run-time error CSS1025: Expected comma or open brace, found 'f_beforeunload('
(11,8): run-time error CSS1030: Expected identifier, found 'addEventListener('
(11,8): run-time error CSS1031: Expected selector, found 'addEventListener('
(11,8): run-time error CSS1025: Expected comma or open brace, found 'addEventListener('
(12,14): run-time error CSS1031: Expected selector, found ';'
(12,14): run-time error CSS1025: Expected comma or open brace, found ';'
(13,10): run-time error CSS1031: Expected selector, found '='
(13,10): run-time error CSS1025: Expected comma or open brace, found '='
(14,10): run-time error CSS1031: Expected selector, found 'initExam('
(14,10): run-time error CSS1025: Expected comma or open brace, found 'initExam('
(54,10): run-time error CSS1031: Expected selector, found 'initLc('
(54,10): run-time error CSS1025: Expected comma or open brace, found 'initLc('
(95,10): run-time error CSS1031: Expected selector, found 'initQuestions('
(95,10): run-time error CSS1025: Expected comma or open brace, found 'initQuestions('
(187,10): run-time error CSS1031: Expected selector, found 'scrollTo('
(187,10): run-time error CSS1025: Expected comma or open brace, found 'scrollTo('
(196,10): run-time error CSS1031: Expected selector, found 'goToSections('
(196,10): run-time error CSS1025: Expected comma or open brace, found 'goToSections('
(200,10): run-time error CSS1031: Expected selector, found 'sectionChanged('
(200,10): run-time error CSS1025: Expected comma or open brace, found 'sectionChanged('
(206,10): run-time error CSS1031: Expected selector, found 'selectSecion('
(206,10): run-time error CSS1025: Expected comma or open brace, found 'selectSecion('
(215,10): run-time error CSS1031: Expected selector, found 'starTimer('
(215,10): run-time error CSS1025: Expected comma or open brace, found 'starTimer('
(239,10): run-time error CSS1031: Expected selector, found 'nextOrPrev('
(239,10): run-time error CSS1025: Expected comma or open brace, found 'nextOrPrev('
(251,10): run-time error CSS1031: Expected selector, found 'getScale('
(251,10): run-time error CSS1025: Expected comma or open brace, found 'getScale('
(267,10): run-time error CSS1031: Expected selector, found 'renderQuestion('
(267,10): run-time error CSS1025: Expected comma or open brace, found 'renderQuestion('
(345,10): run-time error CSS1031: Expected selector, found 'changeQuestion('
(345,10): run-time error CSS1025: Expected comma or open brace, found 'changeQuestion('
(393,10): run-time error CSS1031: Expected selector, found 'toSelected('
(393,10): run-time error CSS1025: Expected comma or open brace, found 'toSelected('
(407,10): run-time error CSS1031: Expected selector, found 'selectAnswer('
(407,10): run-time error CSS1025: Expected comma or open brace, found 'selectAnswer('
(436,10): run-time error CSS1031: Expected selector, found 'finishExam('
(436,10): run-time error CSS1025: Expected comma or open brace, found 'finishExam('
(514,10): run-time error CSS1031: Expected selector, found 'setToLocalStorage('
(514,10): run-time error CSS1025: Expected comma or open brace, found 'setToLocalStorage('
(522,10): run-time error CSS1031: Expected selector, found 'getFromLocalStorage('
(522,10): run-time error CSS1025: Expected comma or open brace, found 'getFromLocalStorage('
(525,10): run-time error CSS1031: Expected selector, found 'clearLocalStorage('
(525,10): run-time error CSS1025: Expected comma or open brace, found 'clearLocalStorage('
 */
var userAnswers = [];
var currentQuestion;
var remainSeconds = 0;
var oeKey;
var filigranUrl;
function f_beforeunload(e) { // Cancel the event
    e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
    // Chrome requires returnValue to be set
    e.returnValue = '';
}
window.addEventListener('beforeunload', f_beforeunload);
var global_lc;
var conf = { GetOnlineExamUri: "", ExamGuid: "", FinishExamUri: "", ExamId: "", ExamDuration: "", Area: "", V: "", UseOpticalForm: null };
function initExam(configuration) {
    conf = configuration;
    oeKey = "oe_" + devapp.configuration.currentUserId + "_" + conf.V;
    if (conf.UseOpticalForm == "True") {
        conf.UseOpticalForm = true;
        $("#questionContainer").remove();
        initQuestions();
    } else if (conf.UseOpticalForm == "False") {
        conf.UseOpticalForm = false;
        initLc();
        initQuestions();
    }
    else {
        swal.fire({
            text: 'Sınavı nasıl çözmek istersiniz?',
            type: "info",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Sorular Üzerinden",
            cancelButtonText: "Sadece Optik Form İle",
            closeOnConfirm: false,
            closeOnCancel: false,
            allowOutsideClick: false,
        }).then(function (result) {
            if (result.value) {
                conf.UseOpticalForm = false;
                initLc();
                initQuestions();
            } else {
                conf.UseOpticalForm = true;
                $("#questionContainer").remove();
                $("#onlyOpticFormButton").removeClass("hide");
                $("#onlyOpticFormButton").addClass("show");
                initQuestions();
            }

        });
    }
}

function initLc() {
    global_lc = LC.init(document.getElementById("questionArea"),
        {
            imageURLPrefix: '/Plugins/DevApp.Plugins.SolutionApp/Content/images',
            toolbarPosition: 'bottom',
            primaryColor: 'rgb(255, 0, 0)',
            defaultStrokeWidth: 3,
            strokeWidths: [1, 2, 3, 5, 10, 15, 20],
            backgroundColor: 'white',
            secondaryColor: 'transparent',
            watermarkScale: 1,
            tools: [
                LC.tools.Pan, LC.tools.Pencil, LC.tools.Eraser, LC.tools.Line,
                LC.tools.Rectangle, LC.tools.Polygon, LC.tools.Ellipse
            ]
        });
    $(".lc-clear").html("<i class='fas fa-trash-alt'></i>");
    $("[title='Pan']").attr("Title", "Sürükle").html("<i class='far fa-hand-pointer'></i>")
        .css("background-image", "");
    $("[title='Pencil']").attr("Title", "Kalem").html("<i class='fas fa-pencil-alt'></i>")
        .css("background-image", "");
    $("[title='Eraser']").attr("Title", "Silgi").html("<i class='fas fa-eraser'></i>")
        .css("background-image", "");
    $("[title='Line']").attr("Title", "Çizgi").html("<i class='fas fa-slash'></i>")
        .css("background-image", "");
    $("[title='Rectangle']").attr("Title", "Dikdörtgen").html("<i class='far fa-square'></i>")
        .css("background-image", "");
    $("[title='Polygon']").attr("Title", "Çokgen").html("<i class='fas fa-draw-polygon'></i>")
        .css("background-image", "");
    $("[title='Ellipse']").attr("Title", "Daire").html("<i class='far fa-circle'></i>")
        .css("background-image", "");
    $("[title='Undo']").attr("Title", "Geri Al").html("<i class='fas fa-undo-alt'></i>")
        .css("background-image", "");
    $("[title='Redo']").attr("Title", "Tekrarla").html("<i class='fas fa-redo-alt'></i>")
        .css("background-image", "");
    $("[title='Zoom out']").attr("Title", "Uzaklaş").html("<i class='fas fa-search-minus'></i>")
        .css("background-image", "");
    $("[title='Zoom in']").attr("Title", "Yakınlaş").html("<i class='fas fa-search-plus'></i>")
        .css("background-image", "");
}

function initQuestions() {
    swal.fire({
        title: "Sorular Yükleniyor...",
        text: "Lütfen Bekleyiniz",
        allowOutsideClick: false
    });
    swal.showLoading();
    $.post(conf.GetOnlineExamUri, { guid: conf.ExamGuid, bookLetType: null }).
        done(function (res) {
            var exam = JSON.parse(res);
            if (exam.FiligranUrl && global_lc != undefined) {
                var watermarkImage = new Image();
                watermarkImage.src = exam.FiligranUrl;
                global_lc.setWatermarkImage(watermarkImage);
            }
            $.each(exam.Sections,
                function (i, item) {
                    item.UserAnswers = [];
                    $.each(item.Questions,
                        function (j, q) {
                            var options = [];
                            for (var k = 0; k < q.OptionCount; k++) {
                                options.push({
                                    "Option": q.Options[k],
                                    "QuestionId": q.Id,
                                    IsSelected: false
                                });
                            }
                            var question = {
                                QuestionId: q.Id,
                                UserAnswer: null,
                                SectionId: q.SectionId,
                                LessonId: q.SectionLessonId,
                                QuestionNumber: q.QuestionNumber,
                                SectionQuestionNumber: j + 1,
                                Image: q.QuestionImageUrl,
                                RootImage: q.RootQuestionImageUrl,
                                SectionLessonName: q.SectionLessonName,
                                SectionName: q.SectionName,
                                HasRoot: q.HasRoot,
                                Options: options
                            };
                            userAnswers.push(question);

                            item.UserAnswers.push(question);
                        });
                });

            $('#opticContainer').html($("#tmplOptic").render(exam));
            swal.close();
            var storedUserAnswers = getFromLocalStorage();
            if (storedUserAnswers) {
                swal.fire({
                    text: 'Bu sınava ait kayıtlı verileriniz bulundu, kayıtlı verilerinize devam etmek ister misiniz?',
                    type: "info",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger",
                    confirmButtonText: "Kaldığın Yerden Devam Et",
                    cancelButtonText: "Tekrar Başla",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }).then(function (result) {
                    if (result.value) {
                        $.each(storedUserAnswers.UserAnswers,
                            function (index, item) {
                                if (item.UserAnswer) {
                                    selectAnswer(item.QuestionId, item.UserAnswer);
                                }
                            });
                        changeQuestion(storedUserAnswers.CurrentQuestion.QuestionId);
                    } else {
                        clearLocalStorage();
                        changeQuestion(userAnswers[0].QuestionId);
                    }
                });

            } else {
                changeQuestion(userAnswers[0].QuestionId);
            }

            if (exam.IsTimeLimited) {
                starTimer();
            }
        }).fail(function () {
            swal.close();
            swal.fire({
                icon: 'error',
                title: 'Hata Oluştu...',
                text: 'Sorularınız getirilirken bir sorun oluştu, lütfen sayfayı yenileyerek tekrar deneyiniz.'
            });
        });
}
function scrollTo(id) {
    if ($("#" + id).position()) {
        $('html,body').animate({
            scrollTop: $("#" + id).position().top
        }, 'fast');
    }

}

function goToSections() {
    scrollTo("opticContainer");
}

function sectionChanged(sectionId) {
    if (conf.Area === "Public") {
        $('.show').not("#section_" + sectionId).collapse('toggle');

    }
}
function selectSecion(sectionId) {
    if (conf.Area === "Public") {
        if ($("#section_" + sectionId).attr('aria-expanded') === "false") {
            $("#section_" + sectionId).collapse('toggle');
            sectionChanged(sectionId);
        }
    }
}

function starTimer() {
    var examDuration = conf.ExamDuration * 60; //seconds
    var storedData = getFromLocalStorage();
    if (storedData) {
        examDuration = storedData.RemainSeconds; //seconds from
    }
    examDuration = examDuration * 10 * 10 * 10;
    examDuration = new Date().getTime() + examDuration;
    $("#countDown").countdown(examDuration)
        .on('update.countdown',
            function (event) {
                var $this = $(this);
                $this.html("<span> Sınav Süresi: </span>" + event.strftime("%H : %M : %S"));
                remainSeconds = event.offset.totalSeconds;
                setToLocalStorage();
            }).on('finish.countdown',
                function (event) {
                    var $this = $(this);
                    remainSeconds = -1;
                    setToLocalStorage();
                    $this.text(event.strftime("Süre Tamamlandı"));
                    finishExam(true);
                });
}
function nextOrPrev(isNext) {
    var q = isNext ? userAnswers[($.inArray(currentQuestion, userAnswers) + 1) % userAnswers.length] : userAnswers[($.inArray(currentQuestion, userAnswers) - 1 + userAnswers.length) % userAnswers.length];
    if (q) {
        selectSecion(q.SectionId);
        changeQuestion(q.QuestionId);
        if (!IsMobileDevice()) {
            document.getElementById("question-" + q.QuestionId).scrollIntoView(false);

        }
    }
}

function getScale(width, height) {
    var questionImageWidth = $('#canvasId').width() - 10;
    var canvasheight = $('#canvasId').height() - 10;
    var scale = 1;
    if (canvasheight < height) {
        var b = canvasheight / height;
        scale *= b;
    }
    if (questionImageWidth < width) {
        var scale2 = questionImageWidth / width;
        if (scale > scale2) {
            scale *= scale2;
        }
    }
    return scale;
}
function renderQuestion(question) {
    global_lc.clear();
    var snap = global_lc.getSnapshot(['backgroundShapes']);
    snap.backgroundShapes = [];
    var image = question.Image;
    if (question.HasRoot) {
        var img1 = new Image();
        img1.src = question.RootImage;
        var img2 = new Image();

        img1.onload = function () {
            img2.src = question.Image;
            img2.onload = function () {
                var tWidth, tHeight;
                if (IsMobileDevice()) {
                    tWidth = img1.width > img2.width ? img1.width : img2.width;
                    tHeight = img1.height + img2.height;
                } else {
                    tWidth = img1.width + img2.width;
                    tHeight = img1.height > img2.height ? img1.height : img2.height;
                }
                var scale = getScale(tWidth, tHeight);
                var backgroundShape = LC.createShape('Image',
                    {
                        x: IsMobileDevice() ? 10 : ($("#canvasId").width() / 2 - tWidth * scale / 2) ,
                        y: 10,
                        image: img1,
                        scale: scale
                    });
                snap.backgroundShapes.push(LC.shapeToJSON(backgroundShape));
                backgroundShape = LC.createShape('Image',
                    {
                        x: IsMobileDevice() ? 10 : ($("#canvasId").width() / 2 - tWidth * scale / 2) + img1.width * scale,
                        y: IsMobileDevice() ? img1.height * scale + 10 : 10,
                        image: img2,
                        scale: scale
                    });
                snap.backgroundShapes.push(LC.shapeToJSON(backgroundShape));
                global_lc.loadSnapshot(snap);
            }
        };

    } else {
        if (question.Image) {
            var qImage = new Image();// $('#mergedImage').src;
            qImage.src = image;
            qImage.onload = function () {
                var scale = getScale(qImage.width, qImage.height);
                var backgroundShape = LC.createShape('Image',
                    {
                        x: IsMobileDevice() ? 10 : ($("#canvasId").width() / 2 - qImage.width * scale / 2),
                        y: 10,
                        image: qImage,
                        scale: scale
                    });
                snap.backgroundShapes.push(LC.shapeToJSON(backgroundShape));
                global_lc.loadSnapshot(snap);
            }
        } else {
            var noImageShape = LC.createShape(
                'Text',
                {
                    x: IsMobileDevice() ? 10 : $("#canvasId").width() / 2 - 100,
                    y: 200,
                    width: 200,
                    text: "Soru resmi bulunamadı!",
                    font: "bold 24px Helvetica"
                });

            snap.backgroundShapes.push(LC.shapeToJSON(noImageShape));
            global_lc.loadSnapshot(snap);
        }

    }
    //soru değişiminde sorunun default değerlerle gösterilmesi sağlanır
    global_lc.setZoom(1);
    global_lc.setPan(0, 0);
}
function changeQuestion(questionId) {

    const selected = $.grep(userAnswers,
        function (n, i) {
            return (n.QuestionId === questionId);
        });
    var question = selected[0];
    currentQuestion = question;
    if (!conf.UseOpticalForm) {
        global_lc.clear();
        var snap = global_lc.getSnapshot(['backgroundShapes']);
        snap.backgroundShapes = [];
        var loadingShape = LC.createShape(
            'Text',
            {
                x: IsMobileDevice() ? 10 : $("#canvasId").width() / 2 - 100,
                y: 200,
                width: 200,
                text: "Soru Yükleniyor...",
                font: "24px Helvetica"
            });

        snap.backgroundShapes.push(LC.shapeToJSON(loadingShape));
        global_lc.loadSnapshot(snap);
        renderQuestion(question);
        $('#questionHeader').text(question.SectionName + " - " + question.SectionLessonName + " - " + question.SectionQuestionNumber + ". Soru");
    }
    $('#questionOptic').html($("#tmplQuestionOptic").render({
        Options: question.Options,
        QuestionId: questionId
    }));

    $.each($(".card-body"),
        function (index, parent) {
            $.each(parent.children,
                function (i, item) {
                    if ($(item).hasClass("optic-tr-" + questionId)) {
                        $(item).addClass("current-bar");
                    } else {
                        $(item).removeClass("current-bar");
                    }
                });
        });

    //if (IsMobileDevice()) {
    //    scrollTo("questionContainer");
    //}
}
function toSelected(questionId, option) {
    $.each($(".optic-button-" + questionId),
        function (index, item) {
            if ($(item).hasClass("btn-light") && item.innerText === option) {
                $(item).removeClass("btn-light").addClass("btn-dark");
            } else {
                if ($(item).hasClass("btn-dark")) {
                    $(item).removeClass("btn-dark").addClass("btn-light");
                }
            }
        });
    selectAnswer(questionId, option);
    setToLocalStorage();
}
function selectAnswer(questionId, answer) {
    $.each(userAnswers, function (i, ua) {
        if (ua.QuestionId === questionId) {

            if (ua.UserAnswer !== answer) {
                ua.UserAnswer = answer;
                var $radios = $('input[name=questionOption-' + questionId + ']');
                $radios.filter('[value=' + answer + ']').prop('checked', true);
                $.each(ua.Options,
                    function (i, item) {
                        item.IsSelected = answer === item.Option;
                    });
                $("#question-" + questionId).addClass("marked-bar");
                return false;
            } else {
                ua.UserAnswer = null;
                $('input[name=questionOption-' + questionId + ']').prop('checked', false);
                $.each(ua.Options,
                    function (i, item) {
                        item.IsSelected = false;
                    });
                $("#question-" + questionId).removeClass("marked-bar");
                return false;
            }

        }
    })
}

function finishExam(timeIsUp) {
    $("#finishButton").prop('disabled', true);
    if (timeIsUp) {
        $("#finishButton").remove();
    }

    if (userAnswers && userAnswers.length > 0) {
        swal.fire({
            title: timeIsUp
                ? 'Sınav için belirlenen süre tamamlandı, sınavını kaydedebilirsin'
                : 'Sınavı tamamlamak istediğine emin misin?',
            showCancelButton: !timeIsUp,
            cancelButtonText: 'Sınava Devam Et',
            confirmButtonText: 'Sınavı Tamamla',
            showLoaderOnConfirm: true,
            preConfirm: function () {
                return $.post(conf.FinishExamUri,
                    { examId: conf.ExamId, remainSeconds: remainSeconds, userAnswers: userAnswers })
                    .done(function (data) {
                        window.removeEventListener("beforeunload", f_beforeunload);
                        window.onbeforeunload = function () { }
                        if (data.Status === 1) {
                            clearLocalStorage();
                            swal.fire({
                                icon: 'success',
                                text: data.Description,
                                timer: 2000,
                                timerProgressBar: true,
                                showLoaderOnConfirm: true,
                                allowOutsideClick: false,
                                onBeforeOpen: function () {
                                    location.assign(data.RedirectUrl);
                                    swal.showLoading();
                                }
                            });
                        } else {
                            swal.fire({
                                icon: 'error',
                                title: 'Hata oluştu!',
                                text: data.Description
                            });
                            $("#finishButton").prop('disabled', false);
                        }
                    }).fail(function (e) {
                        swal.fire({
                            icon: 'error',
                            title: 'Hata oluştu!'
                        });
                        $("#finishButton").prop('disabled', false);
                    });
            },
            allowOutsideClick: false
        }).then(function (result) {
            if (!result.value) {
                $("#finishButton").prop('disabled', false);
            }
        });

    } else {
        if (timeIsUp) {
            swal.fire({
                icon: 'error',
                title: 'Sınav için belirlenen süre tamamlandı, anasayfaya yönlendiriliyorsun!',
                allowOutsideClick: false
            });
            window.location = '/';
        } else {
            swal.fire({
                icon: 'error',
                title: 'Cevap işaretlenmedi!',
                allowOutsideClick: false
            });
            $("#finishButton").prop('disabled', false);
        }


    }
}
function setToLocalStorage() {
    const data = {
        UserAnswers: userAnswers,
        CurrentQuestion: currentQuestion,
        RemainSeconds: remainSeconds
    };
    localStorage.setItem(oeKey, JSON.stringify(data));
}
function getFromLocalStorage() {
    return JSON.parse(localStorage.getItem(oeKey));
}
function clearLocalStorage() {
    return localStorage.removeItem(oeKey);
}

