
String.prototype.px2int = function () {
    if (!this || !this.length) {
        return 0;
    }

    return Math.ceil(parseFloat(this.replace('px', '') || 0));
};
$.fn.hasAnyClass = function () {
    var classes = arguments[0].split(" ");
    for (var i = 0; i < classes.length; i++) {
        if (this.hasClass(classes[i])) {
            return true;
        }
    }
    return false;
};

var exercice = exercice || {};
exercice.Core = (function (data) {

    /* VAR */
    var _collection = {};
    var onplaying = true;
    var audio_feed = null;
    var audio, audioTTS;
    var _show_bilan = false;
    var currentActivity = 0;
    var _state = {};
    var dom = {};
    var dom_bilan = {};
    var enabledValid = 1;
    var yourDatas;
    var totalActivities = 1;
    var _active_activity = 0;
    var _layer, _stage;
    var _linkingEvents;
    var _data_activity, _data_serie, _data_total_activities, question;
    var _try = 1;
    var _mode = "single";
    var mediaManager;
    var _stageId;
    var _btn;
    var _balloonTxt = ["Mauvaise réponse", "Bonne réponse", "Il manque des réponses"];
    var _solutions_qc = [];
    var listOfWords = [];
    var _anchors = [];
    var _listOfWordsCorrects = [];
    var _copyOfListOfWordsCorrects = [];
    var _listOfWordsInputs = [];
    var _goodAnswers = [];
    var _score = {};
    var _points = 0;
    var _end = 0;
    var _totalPoints = 0;
    var mousex = 0,
        mousey = 0,
        dragged = null,
        coordinates = [];
    var coordinates_drag = [];
    var target;
    var idDrop = [];
    var _lastMovePositon = {};
    var _moving = false;
    var _line = null;
    var _lines = [];
    var _student_lines = [];
    var _correction_lines = []
    var _linkingMode = "oneToMany";
    var targetActive;
    var _tempRepForLines = [];
    var bankOffsetTop = 0;
    var bankOffsetLeft = 0;
    var _casse = "yes";
    var _qcm_qcu_max = 6;
    var _image_position_bilan = "middle";
    var version = "Version : 9";

    var _audio_good = "";
    var _audio_bad = "";
    var _audio_mi = "";
    var _can_click = 0
    var _modePlayer = "noCorrection";
    var _dim_img = {
        _normal_desktop_normal: { w: 120, h: 120 },
        _normal_desktop_primaire: { w: 180, h: 220 },
    }
    var _words = {}




    /* UI */
    function createWindow() {
        var title = "Aperçu";
        var value2 = "Fermer";
        var view_template = '<div id="player"><div class="overlay"></div><div class="modal"> <div id="dialogTitle">' + title + '</div><div id="dialogContent"> </div> <div id="dialogControls"><div id="cancelBtn" value="cancel" class="btn btn-default">' + value2 + '</div> </div></div></div>';
        $('body').append(view_template);
        $('#cancelBtn').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
            killAllSounds();
            $('#player').remove();
        });
    }
    function createContent() {
        var template = '<div id="content"><div class="imageViewer-small"><div class="imageViewer-content-small"></div></div><div id="header"><div class="title_serie_bilan road">Titre de la série</div></div><div id="wrapper-content-exo"><div id="content-exo"><div class="question"><div class="question-content"></div></div><div class="imageViewer"><div class="imageViewer-content"></div></div><div class="answer"><div class="answer-content"></div></div></div></div><div class="bilan"><div class="bilan-content"></div></div><div id="toolbar_container"><div id="toolbar_content"></div></div></div>';
        $('#dialogContent').append(template);
        $('#wrapper-content-exo').addClass('transition');

        // Bilan
        dom._bilan = $('.bilan');
        dom_bilan_content = $('.bilan-content');
        dom_bilan_content.append(addSvgBilan());
        dom_bilan_content.append(addTitleOfSerie());
        dom_bilan_content.append(addTitleBilan());
        dom_bilan_content.append(addMascot());
        dom_bilan_content.append(addMessage());
        dom_bilan_content.append(addResult());
        dom_bilan._title_serie_bilan = $('.title_serie_bilan');
        dom_bilan._message_bilan = $('.message_bilan');
        dom_bilan._mascote_bilan = $('.mascot_bilan');
        if (_image_position_bilan === "middle") {

        }
        if (_image_position_bilan === "left") {
            dom_bilan._mascote_bilan.addClass('left');
            dom_bilan._message_bilan.addClass('right');
        }
        if (_image_position_bilan === "right") {
            dom_bilan._mascote_bilan.addClass('right');
            dom_bilan._message_bilan.addClass('left');
        }
        dom._bilan.hide();

        // Question
        dom._questionViewer = $('.question');
        dom._questionViewer_content = $('.question-content');

        // ImageViewer
        dom._imageViewer = $('.imageViewer');
        dom._imageViewer_content = $('.imageViewer-content');
        // ImageViewer for small screen
        dom._imageViewer_small = $('.imageViewer-small');
        dom._imageViewer_content_small = $('.imageViewer-content-small');
        dom._icon_imageViewer_small = $('.icon-imageViewer-small');

        // Answer
        dom._answer = $('.answer');
        dom._answer_content = $('.answer-content');

        // Toolbar
        dom._toolbar = $('#toolbar_container');
        dom._toolbar_content = $('#toolbar_content');

        // Student
        dom._nav_student = $("#student-nav");

        createButton();
        // Button Toolbar
        dom._correction = $('#cor');

        $('#validate-primaire').css({ 'visibility': 'hidden' })
        $('#replay-primaire').css({ 'visibility': 'hidden' })
        $('#tryAgain').css({ 'visibility': 'hidden' })
        $('#validate').css({ 'visibility': 'hidden' })

        if ($('body').hasClass('primaire')) {
            dom._validation = $('#validate-primaire');
            dom._tryAgain = $('#replay-primaire');
        } else {
            dom._validation = $('#validate');
            dom._tryAgain = $('#tryAgain');
        }

        dom._myAnswer = $('#myAnswer');
        dom._prev = $('#prev');
        dom._next = $('#next');


    }
    function createButton() {

        var template_button_validate = '<div id="validate"><div class="validate-content"><div class="txt-content"><span class="button">' + _btn[0] + '</span></div></div></div>';
        dom._toolbar_content.append(template_button_validate);

        var template_button_myAnswer = '<div id="myAnswer"><div class="myAnswer-content"><div class="txt-content"><span class="button">' + _btn[5] + '</span></div></div></div>';
        dom._toolbar_content.append(template_button_myAnswer);

        if ($("body").hasClass('primaire')) {
            var template_button_next = '<div id="next"><div class="next-content"><div class="txt-content"><span class="button"><span class="text-button"> <svg version="1.1"  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 151 151" style="enable-background:new 0 0 151 151;" xml:space="preserve"><style type="text/css">.st0{fill:#0098DA;}</style><path class="st0" d="M72.9,64L72.9,64c-0.5-0.4-1.1-0.7-1.8-0.7c-1.4,0-2.6,1.2-2.6,2.6c0,0.8,0.3,1.4,0.8,1.9l0,0l8.3,7.6l-8.3,7.6l0,0c-0.5,0.5-0.8,1.1-0.8,1.9c0,1.4,1.2,2.6,2.6,2.6c0.7,0,1.3-0.3,1.8-0.7l0,0l10.4-9.5c0.5-0.5,0.8-1.2,0.8-1.9c0-0.7-0.3-1.4-0.8-1.9L72.9,64L72.9,64z"/></svg> </span></span></div></div></div>';
            var template_button_prev = '<div id="prev"><div class="prev-content"><div class="txt-content"><span class="button"><span class="text-button"> <svg version="1.1"  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 151 151" style="enable-background:new 0 0 151 151;" xml:space="preserve"><style type="text/css">.st0{fill:#0098DA;}</style><path class="st0" d="M80,64L80,64c0.5-0.4,1.1-0.7,1.8-0.7c1.4,0,2.6,1.2,2.6,2.6c0,0.8-0.3,1.4-0.8,1.9l0,0l-8.3,7.6l8.3,7.6l0,0c0.5,0.5,0.8,1.1,0.8,1.9c0,1.4-1.2,2.6-2.6,2.6c-0.7,0-1.3-0.3-1.8-0.7l0,0l-10.4-9.5c-0.5-0.5-0.8-1.2-0.8-1.9c0-0.7,0.3-1.4,0.8-1.9L80,64L80,64z"/></svg></span></span></div></div></div>';

        } else {
            var template_button_prev = '<div id="prev"><div class="prev-content"><div class="txt-content"><span class="button">' + _btn[3] + '</span></div></div></div>';
            var template_button_next = '<div id="next"><div class="next-content"><div class="txt-content"><span class="button">' + _btn[2] + '</span></div></div></div>';

        }
        dom._toolbar_content.append(template_button_prev);
        dom._toolbar_content.append(template_button_next);

        var template_button_cor = '<div id="cor"><div class="cor-content"><div class="txt-content"><span class="button">' + _btn[4] + '</span></div></div></div>';
        dom._toolbar_content.append(template_button_cor);

        var template_button_try = '<div id="tryAgain"><div class="try-content"><div class="txt-content"><span class="button">' + _btn[1] + '</span></div></div></div>';
        dom._toolbar_content.append(template_button_try);

        createButtonPrimaireValider();
        createButtonPrimaireReplay();



    }
    function hideSmallImage() {
        dom._imageViewer_small.hide();
    }

    function showSmallImage() {
        dom._imageViewer_small.show();
    }
    function createEventForToolbar() {

        dom._validation.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            killAllSounds();
            validateActivity()
        });


        dom._tryAgain.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            killAllSounds();
            tryAgainActivity();
        });

        dom._next.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            nextActivity()
        });
        dom._prev.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            prevActivity()
        });

        dom._myAnswer.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            $("#cor").css({ "visibility": "visible" });
            dom._myAnswer.css({ 'visibility': 'hidden' });
            killAllSounds();
            showMyAnswer();
        });

        dom._correction.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            $("#cor").css({ "visibility": "hidden" });
            dom._myAnswer.css({ 'visibility': 'visible' });
            killAllSounds();
            showCorrection()
        });


        dom._imageViewer_small.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            hideSmallImage()
        });

        dom._myAnswer.css({
            'visibility': 'hidden'
        });

        dom._correction.css({
            'visibility': 'hidden'
        });
        dom._prev.css({
            'visibility': 'hidden'
        });
        dom._attempt.css({ 'visibility': 'visible' });
        dom._tryAgain.css({ 'visibility': 'hidden' });

        dom._nav_student.css({
            'visibility': 'hidden'
        });

        if (totalActivities === 1) {
            dom._next.css({
                'visibility': 'hidden'
            })
        }
        if (_data_serie.serie_bilan != "0") {
            dom._next.css({
                'visibility': 'visible'
            })
        }

    }

    function getCoordinate(event) {
        var pageX, pageY;
        if (!!event.pageX) {
            pageX = event.pageX;
        } else if (!!event.originalEvent && !!event.originalEvent.touches && !!event.originalEvent.touches[0]) {
            pageX = event.originalEvent.touches[0].pageX;
        } else if (!!event.originalEvent && !!event.originalEvent.changedTouches && !!event.originalEvent.changedTouches[0]) {
            pageX = event.originalEvent.changedTouches[0].pageX;
        }

        if (!!event.pageY) {
            pageY = event.pageY;
        } else if (!!event.originalEvent && !!event.originalEvent.touches && !!event.originalEvent.touches[0]) {
            pageY = event.originalEvent.touches[0].pageY;
        } else if (!!event.originalEvent && !!event.originalEvent.changedTouches && !!event.originalEvent.changedTouches[0]) {
            pageY = event.originalEvent.changedTouches[0].pageY;
        }
        return { pageX: pageX, pageY: pageY };
    }

    function emptyContent() {
        dom._questionViewer_content.empty();
        dom._imageViewer_content.empty();
        dom._answer_content.empty();
    }


    /* THUMBNAIL */
    function createThumbnail(target, _w, _h) {
        var img = target;
        if (img.length) {
            var targetwidth = _w;
            var targetheight = _h;
            var maxWidth;
            var maxHeight;
            target.hide();
            img.on('load', function () {
                $('.click').length === 1 ? maxWidth = _dim_img._normal_desktop_primaire.w : maxWidth = _dim_img._normal_desktop_normal.w
                $('.click').length === 1 ? maxHeight = _dim_img._normal_desktop_primaire.h : maxHeight = _dim_img._normal_desktop_normal.h


                var width = $(this).width();
                var height = $(this).height();

                var ratioW = maxWidth / width;
                var ratioH = maxHeight / height;


                if (ratioH > ratioW) {
                    $(this).css("width", maxWidth);
                    $(this).css("height", height * ratioW);
                }
                else {
                    $(this).css("height", maxHeight);
                    $(this).css("width", width * ratioH);
                }
                $(this).show();
            });
        }
    }

    /* BIG IMAGE */
    function addImage(data, _w, _h, _position, _typo) {


        dom._imageViewer_small.empty();
        dom._imageViewer_content.empty();
        if (data.activity_image != "") {
            dom._imageViewer.show();
            var isMobile = false;

            if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {

                dom._icon_imageViewer_small.hide();
                //dom._icon_imageViewer_small.css({ 'display': 'inline-block' });
            } else {
                dom._icon_imageViewer_small.hide();

            }



            dom._imageViewer.css({ 'visibility': 'hidden' });
            dom._imageViewer_small.html(' <img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="" src="' + data.activity_image + '" style="" alt="Image">');
            if (_position === "top") {

                dom._imageViewer.removeClass("position-right").addClass("position-top");

                dom._imageViewer_content.html(' <div id="img_box" style=" width: ' + _w + 'px; height: ' + _h + 'px;overflow: hidden; position: relative;"><img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="big_image" src="' + data.activity_image + '" style="" alt="Image"></div>');
                dom._imageBox = $("#img_box");
                var img = $(".big_image");
                img.on('load', function () {
                    var srcwidth = img.width();
                    var srcheight = img.height();

                    if (srcwidth > srcheight && srcwidth < 600) {
                        $(this).addClass("responsive-width");

                    } else if (srcwidth < srcheight && srcwidth < 600) {
                        $(this).addClass("responsive-height")

                    } else {
                        $(this).css({ "max-width": "600px" })

                    }

                    exercice.Utils.setHeight(dom._imageBox, 'auto');
                    updatePositionBlock(_typo, data);
                    dom._imageViewer.css({ 'visibility': 'visible' });
                    dom._answer.css({ 'visibility': 'visible' });
                    if ($('.container_kinetics').length) {

                        if ($('body').hasClass('export')) {
                            $('.container_kinetics').css({
                                left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 40) + "px",
                            })
                        } else {
                            $('.container_kinetics').css({
                                left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 10) + "px",
                            })
                        }


                    }



                })

            } else if (_position === "right") {

                dom._imageViewer.removeClass("position-top").addClass("position-right");
                dom._imageViewer_content.html('<div id="img_box" style=" width: ' + _w / 1 + 'px; height: ' + _h + 'px;overflow: hidden; position: relative;"><img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="big_image" src="' + data.activity_image + '" style="" alt="Image"></div>');
                dom._imageBox = $("#img_box");
                var img = $(".big_image");
                img.on('load', function () {
                    var srcwidth = img.width();
                    var srcheight = img.height();
                    if (srcwidth > srcheight) {
                        $(this).addClass("responsive-width");
                        exercice.Utils.setHeight(dom._imageBox, 'auto');
                    } else if (srcwidth < srcheight) {
                        $(this).addClass("responsive-height")
                    } else {

                        $(this).css({ "max-width": "400px" })
                    }
                    updatePositionBlock(_typo, data);
                    dom._imageViewer.css({ 'visibility': 'visible' });

                    if ($('.container_kinetics').length) {

                        if ($('body').hasClass('export')) {
                            $('.container_kinetics').css({
                                left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 40) + "px",
                            })
                        } else {
                            $('.container_kinetics').css({
                                left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 10) + "px",
                            })
                        }


                    }



                    dom._answer.css({ 'visibility': 'visible' });

                })
            }
        }
        else {
            dom._imageViewer.hide();
            dom._icon_imageViewer_small.hide();
            updatePositionBlock(_typo, data);
            dom._answer.css({ 'visibility': 'visible' });
        }


    }

    /* SCALE IMAGE */
    function scaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {

        var result = { width: 0, height: 0, fScaleToTargetWidth: true };

        if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
            return result;
        }

        var scaleX1 = targetwidth;
        var scaleY1 = (srcheight * targetwidth) / srcwidth;

        var scaleX2 = (srcwidth * targetheight) / srcheight;
        var scaleY2 = targetheight;

        var fScaleOnWidth = (scaleX2 > targetwidth);
        if (fScaleOnWidth) {
            fScaleOnWidth = fLetterBox;
        }
        else {
            fScaleOnWidth = !fLetterBox;
        }

        if (fScaleOnWidth) {
            result.width = Math.floor(scaleX1);
            result.height = Math.floor(scaleY1);
            result.fScaleToTargetWidth = true;
        }
        else {
            result.width = Math.floor(scaleX2);
            result.height = Math.floor(scaleY2);
            result.fScaleToTargetWidth = false;
        }
        result.targetleft = Math.floor((targetwidth - result.width) / 2);
        result.targettop = Math.floor((targetheight - result.height) / 2);

        return result;
    }

    /* SHUFFLE ARRAY */
    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

    /* INIT ARRAY */
    function deleteContentArray() {
        _solutions_qc = [];
        _listOfWordsCorrects = [];
        _copyOfListOfWordsCorrects = [];
        _listOfWordsInputs = [];
        _goodAnswers = [];
        listOfWords = [];
        _anchors = [];
        _lines = [];
    }
    /* INIT VAR */
    function initVar() {
        _try = 1;
        enabledValid = 1;
        _end = 0;
        currentActivity = 0;
        _active_activity = 0;
        _totalPoints = 0;
        _points = 0;
        _score = {};
        _collection = {}
        _state = {};
        _positionAnswer = [];
        _positionAnswerLink = {}
        _casse = "yes";
        _can_click = 0;
        _modePlayer = "noCorrection";
        audio_feed = null

    }

    /* COMPARE ARRAY */
    function equalArray(a, b) {
        if (a.length === b.length) {
            for (var i = 0; i < a.length; i++) {
                if (a[i] !== b[i]) {
                    return false;
                }
            }
            return true;
        }
        else {
            return false;
        }
    }

    function isSameSet(arr1, arr2) {

        if (arr1.length && arr2.length) {
            if (arr1.length !== arr2.length)
                return false;
            for (var i = arr1.length; i--;) {

                if (String(arr1[i]).indexOf('Wirisformula') > -1 && String(arr2[i]).indexOf('Wirisformula') > -1) {
                    var v1 = arr1[i].replace('<p>', '').replace('</p>', '').replace('<', '').replace('>', '').replace('""', '').split(' ');
                    var v2 = arr2[i].replace('<p>', '').replace('</p>', '').replace('<', '').replace('>', '').replace('""', '').split(' ');

                    if (!equalArray(v1.sort(), v2.sort())) {
                        return false;
                    }
                } else if (arr1[i] !== arr2[i])
                    return false;
            }

            return true;
        }


    }

    /* FEEDBACKS */
    function createFeedBack() {
        var tpl = '<div id="balloon_popup" class="balloon_popup correct" style="opacity: 1; width: auto;">' +
            '<div id="balloon_popup_balloon_icon" class="balloon_icon feedbackIcon_correct">' +
            '<span id="correct" class="icon-right_icon"><svg id="icon-check_box_44" data-name="icon-check_box_04" xmlns="http://www.w3.org/2000/svg" width="24.2" height="20" viewBox="0 0 24.2 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-1" x1="7.76" y1="16.45" x2="22.7" y2="1.5"></line><line class="cls-1" x1="7.41" y1="16.45" x2="1.5" y2="10.53"></line></svg></span>' +
            '<span id="part" class="icon-part_correct"></span>' +
            '<span id="wrong" class="icon-wrong_icon"><svg id="icon-check_box_33" data-name="icon-check_box_03" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><title>Sans titre - 2</title><line class="cls-1" x1="1.5" y1="16.45" x2="16.45" y2="1.5"></line><line class="cls-1" x1="16.45" y1="16.45" x2="1.5" y2="1.5"></line></svg></span></div>' +
            '<div id="balloon_popup_content" class="balloon_popup_content max_width_icon" style="width: auto;">' +
            '<div class="textViewer textViewerStyle ltr" id="gen_id_38" style="direction: ltr; text-align: left; font-size: 19px; min-width: 90px;" mathfield="true">' +
            '<div id="gen_id_38_content" class="textViewer_content"><div><div id="gen_id_39" class="textViewerParagraph">' +
            '<span class="feedback">Bonne réponse</span>' +
            '</div></div></div></div></div>' +
            '<div id="balloon_popup_balloon_arrow" class="balloon_arrow top" style="left: 9.01562px;"></div>' +
            '</div>';
        dom._dialogContent.append(tpl);
        dom._balloon_popup = $(".balloon_popup");
        updatePositionBalloon();

    }


    function adjustElementWithResize() {
        var _h = $('.modal').height();
        var _h_toolbar = $('#toolbar_content').outerHeight();
        var _left = dom._validation.position().left;
        var _delta = 0
        if ($('body').hasClass('primaire')) {
            _delta = 25
        }



        dom._balloon_popup.css({
            'top': _h - _h_toolbar - 60,
            'left': _left + dom._validation.width() + 50 + _delta

        });

        if ($('.container_kinetics').length) {

            if ($('body').hasClass('export')) {
                $('.container_kinetics').css({
                    left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 40) + "px",
                })
            } else {
                $('.container_kinetics').css({
                    left: ($('.list').eq(0).offset().left + $('.list').eq(0).width() - 10) + "px",
                })
            }


        }
    }



    function updatePositionBalloon() {
        adjustElementWithResize();
        adjustBilan();
        window.addEventListener("resize", function () {
            adjustElementWithResize();
            adjustBilan();



        }, true);
    }

    function adjustBilan() {
        var height;

        if ($('body').hasClass('export')) {
            height = window.innerHeight ? window.innerHeight : $(window).height();
        } else {
            height = 540;
        }

        if (exercice.Utils.isTablet()) {
            $('#content-exo').css({ 'height': height - 130 + 'px' });
        } else {
            $('#content-exo').css({ 'height': height - 130 + 'px' });
        }

        dom._bilan.css({ 'height': height - 70 + 'px' });
    }

    function switchBalloon(typ) {

        if (typ === "semigood") {
            dom._balloon_popup.addClass('wrong');
            dom._balloon_popup.find('.icon-right_icon').hide();
            dom._balloon_popup.find('.icon-wrong_icon').css({
                'display': 'block'
            });
            dom._balloon_popup.find('.balloon_arrow').addClass('wrong');
            if (_data_serie.serie_feedbacks_txt_3 != "") {
                dom._balloon_popup.find('.feedback').html(_data_serie.serie_feedbacks_txt_3);
            } else {
                dom._balloon_popup.find('.feedback').html(_balloonTxt[2]);
            }


        } else if (typ === "wrong") {
            dom._balloon_popup.addClass('wrong');
            dom._balloon_popup.find('.icon-right_icon').hide();
            dom._balloon_popup.find('.icon-wrong_icon').css({
                'display': 'block'
            });
            dom._balloon_popup.find('.balloon_arrow').addClass('wrong');
            if (_data_serie.serie_feedbacks_txt_2 != "") {
                dom._balloon_popup.find('.feedback').html(_data_serie.serie_feedbacks_txt_2);
            } else {
                dom._balloon_popup.find('.feedback').html(_balloonTxt[0]);
            }


        } else {
            dom._balloon_popup.removeClass('wrong');
            dom._balloon_popup.find('.icon-right_icon').css({
                'display': 'block'
            });
            dom._balloon_popup.find('.icon-wrong_icon').hide();
            dom._balloon_popup.find('.balloon_arrow').removeClass('wrong');
            if (_data_serie.serie_feedbacks_txt_1 != "") {
                dom._balloon_popup.find('.feedback').html(_data_serie.serie_feedbacks_txt_1);
            } else {
                dom._balloon_popup.find('.feedback').html(_balloonTxt[1]);
            }

        }



    }

    /* ATTEMP */
    function createAttemp() {
        var template_attemp = '<div id="gen_id_91" class="attempt"><span id="gen_id_91_text" class="attempt_text">Tentatives : </span><span id="gen_id_91_content" class="attempt_content">1/2</span></div>';
        dom._dialogContent.append(template_attemp);
        dom._attempt = $('.attempt');

    }

    function updateAttempt(n) {
        $('.attempt_content').html(n + "/" + _data_serie.serie_try)
    }

    /* MEDIA (AUDIOS) */
    function MediaManager() {

        this.currentItem = "";
        this.mediaItems = {};
        this.volume = 1;


        this.attachControl = function () {

        },

            this.setMedia = function (media, isObject) {
                //pause the current media (the old one)
                if (this.currentItem) {
                    if (this.currentItem != media) {
                        this.pause();
                    }

                }

                //change currentItem to the new one
                if (this.currentItem != media) {
                    if (isObject) {
                        //in this case mediaItem is an object
                        this.currentItem = media;
                        this.currentItem.volume = this.volume;
                    } else {
                        //the mediaItem is not an object its a div, than media is actually Id
                        this.currentItem = Perf.select("#" + media)[0];
                        this.currentItem.volume = this.volume;
                    }
                }
            },
            this.register = function (mediaId, mediaConfig) {

                this.mediaItems[mediaId] = mediaConfig;
            },


            this.canPlayType = function (type) {
                return this.currentItem.canPlayType(type);
            },

            this.pauseAll = function () {
                for (var mediaId in this.mediaItems) {
                    $("#" + mediaId).pause();
                }
            },


            this.load = function () {
                this.currentItem.load();
            },
            this.loadAll = function () {
                for (var mediaId in this.mediaItems) {
                    Perf.select("#" + mediaId).load();
                }
            },

            this.play = function () {
                if (this.currentItem) {
                    this.currentItem.play();

                }
            },

            this.stop = function () {
                if (!this.currentItem) {
                    return;
                }


                this.pause();

                if (this.currentItem.readyState > 0) {
                    this.currentItem.currentTime = 0;
                }


            },
            this.togglePlay = function () {
                if (this.currentItem) {
                    if (this.currentItem.paused) {
                        this.currentItem.play();
                    } else {
                        this.currentItem.pause();
                    }
                }

            },
            this.pause = function () {
                if (this.currentItem && this.currentItem.readyState > 0) {
                    this.currentItem.pause();
                }
            },

            this.ended = function (callback) {

                this.currentItem.addEventListener("ended", callback, false);
            },

            this.addClass = function (clas) {
                this.currentItem.addClass(clas)
            }
        this.removeClass = function (clas) {
            this.currentItem.removeClass(clas)
        }


        this.pauseAll = function () {
            var arr_audio = document.getElementsByTagName('audio'),
                i = arr_audio.length;

            while (i--) {
                arr_audio[i].pause();
            }

            var arr_video = document.getElementsByTagName('video'),
                i = arr_video.length;

            while (i--) {
                arr_video[i].pause();
            }
        },
            this.addVideo = function (parentId, vidURL) {
                var vid, makevid;
                vid = document.createElement('video');
                vid.src = vidURL;
                vid.setAttribute('autoplay', true);
                Perf.select("#" + parentId).append(vid);
            },

            this.setVolume = function (volume) {

                if (volume !== 0 && !volume) {
                    volume = 1;
                }

                while (volume > 1) {
                    volume = volume / 100;
                }

                if (this.currentItem) {
                    this.currentItem.volume = volume;
                }

            },

            this.getVolume = function () {
                return this.volume;
            }

    }

    /* PROGRESSION */
    function createProgression() {
        dom._dialogContent = $('#dialogContent');
        dom._content = $('#content');
        var view_template = '<div class="wrap-progress-bar"><div id="container-progress-bar"><span class="progression-label"><b class="value">PROGRESSION</b></span><div id="progress_bar" class="ui-progress-bar ui-container"> <div class="ui-progress" id="appcache-downloading-bar" style="width: 0%;"> <span class="ui-label"><b class="value"></b></span> </div> </div></div></div>'
        $("#header").append(view_template);
        dom._progressBar = $('#progress_bar');
        dom._progress = $('.ui-progress');
        dom._progressLabel = $('.progression-label');
        updateProgression(1);
        //if (exercice.Utils.isTablet() || $('body').hasClass('primaire')) {
        // $("#container-progress-bar").hide();
        // }
    }

    function updateProgression(dir) {
        if (currentActivity === totalActivities + 1) {
            return
        }

        if (dir) {
            currentActivity++;
        } else {
            currentActivity--;
        }
        var n = Number(currentActivity / totalActivities) * dom._progressBar.width();
        dom._progress.css({
            'width': n
        });

        dom._progressLabel.html('<b class="value">PROGRESSION ' + currentActivity + '/' + totalActivities + '</b>')


    }

    function createButtonPrimaireValider() {
        var template_button_validate = '<div id="validate-primaire"><div class="validate-content-primaire"><div class="txt-content"><span class="button-primare"><svg   xmlns="http://www.w3.org/2000/svg" width="24.2" height="20" viewBox="0 0 24.2 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-1" x1="7.76" y1="16.45" x2="22.7" y2="1.5"></line><line class="cls-1" x1="7.41" y1="16.45" x2="1.5" y2="10.53"></line></svg></span></div></div></div>';
        dom._toolbar_content.append(template_button_validate);

    }

    function createButtonPrimaireReplay() {


        var template_button_validate = '<div id="replay-primaire"><div class="validate-content-primaire"><div class="txt-content"><span class="button-primaire"> <svg version="1.1" id="Calque_1r" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"viewBox="0 0 151 151" style="enable-background:new 0 0 151 151;" xml:space="preserve"><style type="text/css">.st10{fill:#FFFFFF;}</style><path class="st10" d="M75.3,48c6.2,0.1,12.3,2.5,16.9,6.9c2-1.9,3.9-3.8,5.9-5.8c0.4-0.4,1-0.7,1.7-0.7c1.4,0,2.6,1.1,2.6,2.5v15c0,1.4-1.1,2.5-2.5,2.5h-15c-2.2,0-3.3-2.6-1.8-4.2c1.7-1.8,3.5-3.6,5.3-5.4c-5.3-5-13-6.7-20-4.1c-7.7,2.8-12.8,10-12.8,18.2c0,3.7-5.6,3.7-5.6,0c0-10.5,6.6-19.8,16.4-23.4c2.5-0.9,5-1.4,7.5-1.5C74.4,48,74.8,48,75.3,48z M99.5,75.7c1.6,0,2.9,1.2,2.9,2.8c0,10.5-6.6,19.8-16.4,23.4c-2.5,0.9-5,1.4-7.5,1.5c-0.5,0-0.9,0-1.4,0c-6.2-0.1-12.3-2.5-16.9-6.9c-2,1.9-3.9,3.8-5.9,5.8c-0.4,0.4-1,0.7-1.7,0.7c-1.4,0-2.6-1.1-2.6-2.5v-15c0-1.4,1.1-2.5,2.5-2.5h15c2.2,0,3.3,2.6,1.8,4.2c-1.7,1.8-3.5,3.6-5.3,5.4c5.3,5,13,6.7,20,4.1c7.7-2.8,12.8-10,12.8-18.2C96.8,77,98,75.8,99.5,75.7z"/></svg></span></div></div></div>';
        dom._toolbar_content.append(template_button_validate);

    }

    /* BILAN */
    function addSvgBilan() {
        var _svg_icone
        if ($("body").hasClass('primaire')) {
            _svg_icone = '<div><svg version="1.1" id="svg_icone_bilan" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 151 151" style="enable-background:new 0 0 151 151;" xml:space="preserve"><style type="text/css">.st0{fill-rule:evenodd;clip-rule:evenodd;fill:#E6E7E8;}.st1{fill-rule:evenodd;clip-rule:evenodd;fill:#888888;}.st2{fill-rule:evenodd;clip-rule:evenodd;fill:#3E3639;}.st3{fill-rule:evenodd;clip-rule:evenodd;fill:#FFE544;}.st4{fill-rule:evenodd;clip-rule:evenodd;fill:#191919;}.st5{fill-rule:evenodd;clip-rule:evenodd;fill:#FFD01F;}.st6{fill-rule:evenodd;clip-rule:evenodd;fill:#FFB500;}.st7{fill-rule:evenodd;clip-rule:evenodd;fill:#0098DA;}.st8{fill-rule:evenodd;clip-rule:evenodd;fill:#0061CE;}</style><g><path class="st0" d="M76,125.3c16.7,0,30.3-2.8,30.3-6.3c0-3.5-13.6-6.3-30.3-6.3c-16.7,0-30.3,2.8-30.3,6.3 C45.7,122.4,59.3,125.3,76,125.3z"/><ellipse class="st1" cx="60.7" cy="118.9" rx="3.6" ry="0.8"/><path class="st2" d="M56.6,122.7c4.7,0,8.6-1.8,8.6-4.1c0-2.2-3.9-4.1-8.6-4.1s-8.6,1.8-8.6,4.1C48.1,120.8,51.9,122.7,56.6,122.7z"/><polygon class="st3" points="54.5,35.8 61.1,35.8 61.1,119.1 61.1,120.2 61.1,120.2 61.1,120.2 61.1,120.2 61.1,120.2 61,120.2 61,120.3 61,120.3 61,120.3 60.9,120.4 60.8,120.4 60.8,120.4 60.8,120.4 60.8,120.4 60.8,120.4 60.7,120.5 60.7,120.5 60.7,120.5 60.6,120.5 60.6,120.5 60.6,120.5 60.6,120.5 60.5,120.6 60.5,120.6 60.5,120.6 60.4,120.6 60.4,120.6 60.4,120.6 60.4,120.6 60.3,120.7 60.3,120.7 60.3,120.7 60.2,120.7 60.2,120.7 60.2,120.7 60.1,120.7 60.1,120.8 60.1,120.8 60.1,120.8 60,120.8 60,120.8 59.9,120.8 59.9,120.8 59.9,120.8 59.8,120.9 59.8,120.9 59.8,120.9 59.7,120.9 59.7,120.9 59.6,120.9 59.6,120.9 59.6,120.9 59.6,120.9 59.5,121 59.5,121 59.5,121 59.4,121 59.4,121 59.3,121 59.3,121 59.3,121 59.2,121 59.2,121 59.1,121.1 59.1,121.1 59.1,121.1 59,121.1 59,121.1 58.9,121.1 58.9,121.1 58.9,121.1 58.8,121.1 58.8,121.1 58.7,121.1 58.7,121.1 58.7,121.1 58.6,121.1 58.6,121.2 58.5,121.2 58.5,121.2 58.4,121.2 58.4,121.2 58.4,121.2 58.3,121.2 58.3,121.2 58.2,121.2 58.2,121.2 58.2,121.2 58.1,121.2 58.1,121.2 58,121.2 58,121.2 57.9,121.2 57.9,121.2 57.9,121.2 57.8,121.2 57.8,121.2 57.7,121.2 57.6,121.2 57.6,121.2 57.5,121.2 57.5,121.2 57.4,121.2 57.4,121.2 57.3,121.2 57.3,121.2 57.2,121.2 57.2,121.2 57.2,121.2 57.1,121.2 57.1,121.2 57.1,121.2 57,121.2 57,121.2 57,121.2 56.9,121.2 56.9,121.2 56.9,121.2 56.8,121.2 56.8,121.2 56.8,121.2 56.7,121.2 56.7,121.2 56.7,121.2 56.6,121.2 56.6,121.2 56.6,121.2 56.5,121.2 56.5,121.2 56.5,121.2 56.5,121.2 56.4,121.2 56.4,121.2 56.4,121.2 56.3,121.2 56.3,121.2 56.2,121.2 56.2,121.2 56.1,121.2 56.1,121.2 56.1,121.2 56,121.1 56,121.1 56,121.1 55.9,121.1 55.9,121.1 55.9,121.1 55.9,121.1 55.8,121.1 55.8,121.1 55.8,121.1 55.7,121.1 55.7,121.1 55.7,121.1 55.7,121.1 55.6,121.1 55.6,121.1 55.5,121.1 55.5,121.1 55.5,121 55.4,121 55.4,121 55.4,121 55.3,121 55.3,121 55.3,121 55.3,121 55.2,121 55.2,121 55.1,121 55.1,120.9 55.1,120.9 55.1,120.9 55,120.9 55,120.9 54.9,120.9 54.8,120.8 54.8,120.8 54.7,120.8 54.7,120.8 54.7,120.8 54.6,120.8 54.6,120.8 54.6,120.8 54.5,120.8 54.5,119 	"/><path class="st4" d="M54.5,35.8h6.6v0.6c-0.9,0.7-2.1,1.1-3.3,1.1c-1.2,0-2.4-0.4-3.3-1.1V35.8z"/><polygon class="st5" points="57.8,35.8 54.5,35.8 54.5,119.1 54.5,120.2 54.6,120.2 54.6,120.2 54.6,120.2 54.6,120.2 54.6,120.2 54.7,120.3 54.7,120.3 54.7,120.3 54.7,120.3 54.8,120.3 54.8,120.4 54.8,120.4 54.8,120.4 54.9,120.4 54.9,120.4 54.9,120.4 55,120.5 55,120.5 55,120.5 55,120.5 55,120.5 55.1,120.5 55.1,120.5 55.1,120.6 55.2,120.6 55.2,120.6 55.2,120.6 55.2,120.6 55.2,120.6 55.3,120.6 55.3,120.6 55.3,120.7 55.4,120.7 55.4,120.7 55.4,120.7 55.5,120.7 55.5,120.7 55.5,120.7 55.5,120.7 55.6,120.8 55.6,120.8 55.6,120.8 55.7,120.8 55.7,120.8 55.7,120.8 55.8,120.8 55.8,120.8 55.8,120.9 55.9,120.9 55.9,120.9 55.9,120.9 55.9,120.9 56,120.9 56,120.9 56,120.9 56.1,120.9 56.1,120.9 56.2,121 56.2,121 56.2,121 56.3,121 56.3,121 56.3,121 56.4,121 56.4,121 56.4,121 56.5,121 56.5,121 56.6,121.1 56.6,121.1 56.6,121.1 56.7,121.1 56.7,121.1 56.7,121.1 56.8,121.1 56.8,121.1 56.9,121.1 56.9,121.1 57,121.1 57,121.1 57.1,121.1 57.1,121.1 57.1,121.2 57.2,121.2 57.2,121.2 57.2,121.2 57.3,121.2 57.4,121.2 57.4,121.2 57.4,121.2 57.5,121.2 57.6,121.2 57.6,121.2 57.6,121.2 57.7,121.2 57.7,121.2 57.8,121.2 57.8,121.2 57.8,121.2 57.8,119.1 	"/><path class="st4" d="M57.8,35.8h-3.3v0.6c0.9,0.7,2.1,1.1,3.3,1.1L57.8,35.8z"/><circle class="st6" cx="57.8" cy="31.6" r="5.4"/><path class="st3" d="M55.1,36.3c-2.6-1.5-3.5-4.8-2-7.4c1.5-2.6,4.8-3.5,7.4-2L55.1,36.3z"/><path class="st3" d="M63.2,31.6c0,3-2.4,5.4-5.4,5.4c-3,0-5.4-2.4-5.4-5.4c0,3.9,4.9,4.2,5.4,4.2C59.6,35.8,63.2,35.1,63.2,31.6z"/><path class="st3" d="M52.4,31.6c0,3,2.4,5.4,5.4,5.4v-1.2C56,35.8,52.4,34.7,52.4,31.6z"/><path class="st7" d="M54.5,37c1.1,0.5,2.2,0.8,3.3,0.8c1.1,0,2.2-0.2,3.3-0.8h37.6l-5,15.8l5,15.8H61.1c-1,0.5-2.2,0.8-3.3,0.8c-1.1,0-2.4-0.4-3.3-0.8C54.5,58,54.5,47.5,54.5,37z"/><path class="st8" d="M57.8,37.9L57.8,37.9c1.1,0,2.2-0.2,3.3-0.8v31.5h0c-1,0.5-2.2,0.8-3.3,0.8V37.9z"/><polygon class="st8" points="87.2,37 98.7,37 93.8,52.8 98.7,68.6 72.4,68.6 	"/></g></svg></div>'

        } else {
            _svg_icone = '<div><svg id="svg_icone_bilan" data-name="svg_icone" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 45.5 37.75"><defs><style>.cls-12{fill:#59b0fe;}.cls-22,.cls-32{fill:none;stroke:#59b0fe;stroke-linecap:round;stroke-linejoin:round;}.cls-22{stroke-width:1.77px;}.cls-32{stroke-width:1.5px;}</style></defs><path class="cls-12" d="M463.18,322.21a1.26,1.26,0,0,0-1.09-1.9H440.51s0,0,0,0H438s0,0.05,0,.08v18.38H462.1a1.26,1.26,0,0,0,1.05-2l-4.24-7.25,4.28-7.31h0Z" transform="translate(-427.63 -318.5)"/><line class="cls-22" x1="10.65" y1="35.69" x2="10.65" y2="0.89"/><line class="cls-32" x1="0.75" y1="37" x2="44.75" y2="37"/></svg></div>'

        }

        return _svg_icone;

    }

    function addTitleOfSerie() {

        var _titleSerie = '<div class="title_serie_bilan">Titre de la série</div>';
        return _titleSerie;

    }

    function addTitleBilan() {
        var _title = '<div class="title_bilan">Bilan</div>';
        return _title;
    }

    function addMascot() {

        var _mascot = '<div class="mascot_bilan"></div>';
        return _mascot;
    }

    function addMessage() {
        var _message = '<div class="message_bilan">Message</div>';
        return _message;
    }

    function addResult() {
        var _result = '<div class="result_bilan">Tu as réussi ? exercices sur ?</div>';
        return _result;
    }

    /* STATE */
    function setState(_id, data) {

        var _temp = [];
        if (_data_activity.activity_typo.split('_')[0] === "Ordonner") {
            $(".letter_box").each(function () {
                _temp.push($(this).html())

            })
            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo.split('_')[0] === "QCU" || _data_activity.activity_typo.split('_')[0] === "QCM") {
            $(".option.selected").each(function () {
                _temp.push($(this).index())

            })
            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo.split('_')[0] === "Cliquer") {
            $(".option.selected").each(function () {
                _temp.push($(this).index())

            })
            populateState(_id, _temp)
        }

        if (_data_activity.activity_typo.split('_')[0] === "Légender") {
            $("#clozeArea_content").find(".subAnswer").each(function () {

                var _item;
                if ($(this).find(".textViewerParagraph").html() === undefined) {
                    _item = "";
                } else {
                    _item = $(this).find(".textViewerParagraph").html()
                }

                _temp.push(_item);
            })
            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo.split('_')[0] === "Classer") {
            var _items = []
            var _tplCol = {}
            for (var t = 0; t < $(".column__container").length; t++) {
                _items = [];
                for (var u = 0; u < $(".column__container").eq(t).find($(".normal")).length; u++) {
                    _items.push($(".column__container").eq(t).find($(".normal")).eq(u).html())
                }

                _tplCol["col" + Number(t + 1)] = _items;

            }
            _temp = _tplCol
            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo.split('_')[0] === "Relier") {

            var colA = [];
            var colB = [];
            $(".list[name='List A']").find(".link_item.selected").each(function () {
                colA.push($(this).index())

            })
            $(".list[name='List B']").find(".link_item.selected").each(function () {
                colB.push($(this).index())

            })
            _temp["colA"] = colA;
            _temp["colB"] = colB;
            _temp["lines"] = _lines;

            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo === "Compléter_SAISIE") {
            $("#content-exo input").each(function () {
                _temp.push($(this).val())
            })
            populateState(_id, _temp)
        }
        if (_data_activity.activity_typo === "Compléter_LABEL") {
            $("#clozeArea_content .subAnswer").each(function () {
                var _item;
                if ($(this).find(".textViewerParagraph").html() === undefined) {
                    _item = ""
                } else {
                    _item = $(this).find(".textViewerParagraph").html()
                }
                _temp.push(_item)
            })

            populateState(_id, _temp)
        }

    }

    function populateCollection(_id, _data) {

        _collection[_id] = {
            activity_id: _data_activity.activity_id,
            activity_data: _data
        }

    }



    function populateState(_id, _temp) {

        _state[_id] = {
            activity_id: _data_activity.activity_id,
            activity_answer: _temp,
            activity_typo: _data_activity.activity_typo,
            activity_try: _try,
            activity_correction: false

        }



    }

    /* SCORE */

    function calculateScore(x, y) {

        if (y === 0) {

        } else {
            return Math.ceil(((100 * (y - x + 1)) / y)) + "%";
        }




    }

    function setScore(_id, _point, _try, _time) {

        _score[_id] = { activity_score: _point, activity_try: _try, activity_time: _time }
        getTotalPoints()
    }
    function getScore() {
        return _score
    }
    function getTotalPoints() {
        _totalPoints = 0;
        _.each(getScore(), function (num, key) {

            _totalPoints += num.activity_score;

        });


    }
    function updateScore(id) {
        _.each(getScore(), function (num, key) {
            if (key > id) {
                _score[key].activity_score = 0;
            }
        });
        getTotalPoints();

    }


    function hasClass(elem, klass) {
        return (" " + elem.className + " ").indexOf(" " + klass + " ") > -1;
    }


    function applyEqualHeight(_bloc_1, _bloc_2, _bloc_1_content, _bloc_2_content) {
        var bloc_1_height = _bloc_1.height();
        var bloc_2_height = _bloc_2.height();
        if (bloc_1_height > bloc_2_height) {
            exercice.Utils.setStyle([_bloc_2], { 'height': bloc_1_height + "px" });
        } else if (bloc_2_height > bloc_1_height) {
            exercice.Utils.setStyle([_bloc_1], { 'height': bloc_2_height + "px" });

        }

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// LINK SYSTEM///////// //////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function createBoxForDragElement() {
        var TEMPLATE =
            "<div id='" + exercice.Utils.generateUUID() + "' class='bank not_selectable'>\
                <div id='side-toogle' class=''><div class='fold_btn'><div class='fold_content rotate'><div class='icon fold_arrow icon-nev_01_icon'></div></div>									</div></div>\
                <div id='" + exercice.Utils.generateUUID() + "_content' class='bank_content'></div>\
            </div>";

        var TEMPLATE_READONLY =
            "<div id='" + exercice.Utils.generateUUID() + "' class='bank not_draggable'>\
                <div id='" + exercice.Utils.generateUUID() + "_content' class='bank_content'></div>\
            </div>";
        if (exercice.Utils.isTablet()) {
            $('#content').append(TEMPLATE);
        } else {
            dom._answer_content.append(TEMPLATE);
        }


        dom._bank = $('.bank');
        for (var t = 0; t < _solutions_qc.length; t++) {
            $('.bank_content').append(generateSubAnswer());

        }

        for (var u = 0; u < _solutions_qc.length; u++) {
            $('.bank_content').find('.subAnswer').eq(u).find('.subAnswer_content').append(generateWord(_listOfWordsCorrects[u]));
        }

        $('#side-toogle').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
            $('.bank').toggleClass("open-sidebar");
        });


    }
    function generateWord(word) {
        var _template = '<div class="textViewer textViewerStyle ltr compact disabled" id="gen_id_' + exercice.Utils.generateUUID() + '" style="direction: ltr; text-align: left; font-size: 18px; min-width: 90px; max-width: auto; display: inline-block;" mathfield="true">' +
            ' <div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="textViewer_content"><div>' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="textViewerParagraph">' +
            '<span class="normal">' + exercice.Utils.doReplace(word) + '</span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        return _template;
    }
    function createTemplateExo(data) {

        var listA = ["mot_1_col_A", "mot_2_col_A", "mot_3_col_A", "mot_4_col_A"];
        var listB = ["mot_1_col_B", "mot_2_col_B", "mot_3_col_B", "mot_4_col_B"];
        var str = "";
        if (_modePlayer === "correction" && _collection[_active_activity] &&_.size(_collection[_active_activity].activity_data)) {
           

         
                listA = _collection[_active_activity].activity_data.listA;
                listB = _collection[_active_activity].activity_data.listB;
        
           
        } else {
            var t = data.activity_data;
            if (typeof (t) === 'object') {
                str = t;
                listA = shuffleArray(str.colA);
                listB = shuffleArray(str.colB);
               
            } else {
                str = JSON.parse(t);
                listA = shuffleArray(str.colA);
                listB = shuffleArray(str.colB);
            }
            _positionAnswerLink = { listA: listA, listB: listB }
            
           // populateCollection(_active_activity, { listA: listA, listB: listB })

        }


        var TEMPLATE_LISTS = "<div class='lists' id='" + exercice.Utils.generateUUID() + "'><div id=" + exercice.Utils.generateUUID() + "_content></div></div>";


        dom._answer_content.append(TEMPLATE_LISTS);

        var _lists = $('.lists');

        _lists.children().append(generateTemplateListForRelier("List A"));
        _lists.children().append(generateTemplateListForRelier("List B"));


        

        for (var i = 0; i < listA.length; i++) {
            _lists.find('.list').eq(0).children().append(generateTemplateItemsForRelier(listA[i].color));
        }
        for (var k = 0; k < listB.length; k++) {
            _lists.find('.list').eq(1).children().append(generateTemplateItemsForRelier(listB[k].color));
        }
        _lists.find('.list').eq(0).find('.link_item').each(function (index) {
            $(this).children().first().append(generateTextViewer('auto', '30', listA[index].content))
        });

        _lists.find('.list').eq(1).find('.link_item').each(function (index) {
            $(this).children().first().append(generateTextViewer('auto', '30', listB[index].content))
        });

        $(".small_image").each(function (i) {
            createThumbnail($(this), 120, 120)
        });
        buildCanvas();
        newPosition()
        addCanvasAndEvents();
        adjustElementWithResize();




    }


    function imgBasE64() {
        $("img[src*='base64']").each(function () {
            if ($(this).attr("data-latex").indexOf('angle') > -1) {
                $(this).css({
                    'vertical-align': 'middle',
                    'margin-bottom': '0px',
                    'margin-left': '-20px'
                })
            } else {
                $(this).css({
                    'vertical-align': 'middle',
                    'margin-bottom': '11px',
                    'margin-left': '-20px'
                })
            }

        });
    }

    function newPosition() {
        var _lists = $('.lists');
        var _listA = _lists.find('.list').eq(0);
        var _listB = _lists.find('.list').eq(1);
        var nbr_items_A = _listA.children().children().length;
        var nbr_items_B = _listB.children().children().length;
        var t = 0;
        var _refB = 0;
        var _refA = 0;
        if (nbr_items_B === nbr_items_A) {
            for (t; t < nbr_items_A; t++) {

                _refA = (_listA.children().children().eq(t).height() - _listB.children().children().eq(t).height()) / 2;
                _refB = (_listB.children().children().eq(t).height() - _listA.children().children().eq(t).height()) / 2;
                if (_refA > 0 && _refB < 0) {
                    _listB.children().children().eq(t).css({ 'height': _listA.children().children().eq(t).height() })
                    _listB.children().children().eq(t).children().first().css({ "position": "relative", 'height': _listA.children().children().eq(t).height(), "padding-top": (_listA.children().children().eq(t).height() - _listB.children().children().eq(t).children().first().height()) / 2 })
                } else if (_refB > 0 && _refA < 0) {
                    _listA.children().children().eq(t).css({ 'height': _listB.children().children().eq(t).height() })
                    _listA.children().children().eq(t).children().first().css({ "position": "relative", 'height': _listB.children().children().eq(t).height(), "padding-top": (_listB.children().children().eq(t).height() - _listA.children().children().eq(t).children().first().height()) / 2 })

                } else if (_refA === 0 && _refB === 0) {

                    _listA.children().children().eq(t).children().first().css({ "position": "relative", 'height': _listB.children().children().eq(t).height(), "padding-top": (_listB.children().children().eq(t).height() - _listA.children().children().eq(t).children().first().height()) / 2 })
                    _listB.children().children().eq(t).children().first().css({ "position": "relative", 'height': _listA.children().children().eq(t).height(), "padding-top": (_listA.children().children().eq(t).height() - _listB.children().children().eq(t).children().first().height()) / 2 })



                }

            }

        } else {


            for (var u = 0; u < nbr_items_A; u++) {
                _listA.children().children().eq(u).children().first().css({ "position": "relative", 'height': _listA.children().children().eq(u).height(), "padding-top": (_listA.children().children().eq(u).height() - _listA.children().children().eq(u).children().first().height()) / 2 })

            }
            for (var v = 0; v < nbr_items_B; v++) {
                _listB.children().children().eq(v).children().first().css({ "position": "relative", 'height': _listB.children().children().eq(v).height(), "padding-top": (_listB.children().children().eq(v).height() - _listB.children().children().eq(v).children().first().height()) / 2 })

            }
        }

    }
    function createTemplateLink(data, _typo) {

        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position, _typo);

    }
    function updatePositionOfLink() {

        var _lists = $('.lists');
        var _listA = _lists.find('.list').eq(0);
        var _listB = _lists.find('.list').eq(1);
        var _heightA = _listA.height();
        var _heightB = _listB.height();
        var _totalHeight = 0;

        if (_heightA > _heightB) {

            exercice.Utils.setStyle([_listB], { 'height': _heightA });
            var _elts = _listB.find('.link_item');
            _elts.each(function () {
                _totalHeight += $(this).height() + 20;
            });


        } else if (_heightB > _heightA) {
            exercice.Utils.setStyle([_listA], { 'height': _heightB });
            var _elts = _listA.find('.link_item');
            _elts.each(function () {
                _totalHeight += $(this).height() + 20;
            });

        }


    }
    function generateTemplateListForRelier(name) {
        var TEMPLATE_LIST =
            "<div class='list compact' name='" + name + "' id='" + exercice.Utils.generateUUID() + "'>\
            <div id=" + exercice.Utils.generateUUID() + "_content></div>\
            </div>";
        return TEMPLATE_LIST
    }
    function generateTemplateItemsForRelier(color) {
        var TEMPLATE_ITEM =
            "<div class='link_item' id='" + exercice.Utils.generateUUID() + "'>\
             <div id='" + exercice.Utils.generateUUID() + "_content'></div>\
             <div data-color='" + color + "' id='" + exercice.Utils.generateUUID() + "' class='link_anchor'>\
             <span id='correct' class='icon-right_icon'>\
             <svg id='icon-check_box_04' data-name='icon-check_box_04' xmlns='http://www.w3.org/2000/svg' width='24.2' height='20' viewBox='0 0 24.2 20'><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class='cls-1' x1='7.76' y1='16.45' x2='22.7' y2='1.5'/><line class='cls-1' x1='7.41' y1='16.45' x2='1.5' y2='10.53'/></svg></span>\
             </span>\
             <span id='incorrect' class='icon-wrong_icon'>\
              <svg id='icon-check_box_03' data-name='icon-check_box_03' xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 20 20'><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class='cls-1' x1='1.5' y1='16.45' x2='16.45' y2='1.5'/><line class='cls-1' x1='16.45' y1='16.45' x2='1.5' y2='1.5'/></svg>\
             </div>\
             </div>";
        return TEMPLATE_ITEM
    }
    function generateTextViewer(w, h, txt) {
        w = 'auto';
        h = '30px';
        var clas = "";

        if (w) {
            _w = w;
        }
        if (h) {
            _h = h;
        } else {
            _h = "auto"
        }


        if ((/\.(?=gif|jpeg|jpg|png)/gi).test(txt)) {
            var func = createBoxImage;
            clas = "boxImage";
            _h = '120px';
        } else if ((/\.(?=mp3|ogg)/gi).test(txt)) {
            var func = createBoxAudio;
            clas = "boxAudio";
            _h = 'auto';
        } else {
            var func = createBoxText;
            clas = "boxText";
            _h = "auto"
        }

        var TEMPLATE_TEXT_VIEWER =
            "<div class='textViewer " + clas + "' id='" + exercice.Utils.generateUUID() + "' \
                  style='width:" + _w + ";height:" + _h + ";'>\
                <div id='" + exercice.Utils.generateUUID() + "_content' class='textViewer_content'>" + func(txt) + "</div>\
            </div>";
        return TEMPLATE_TEXT_VIEWER;




    }
    function generateTextViewerParagraph() {
        var TEMPLATE_TEXT_VIEWER_PARAGRAPH = "<div class='textViewerParagraph'> </div>";
        return TEMPLATE_TEXT_VIEWER_PARAGRAPH
    }
    function buildCanvas() {
        loadAnchorsRect();
        _linkingEvents = {
            'startLink': exercice.Utils.isTablet() ? 'touchstart.link' : 'mousedown.link',
            'drawLink': exercice.Utils.isTablet() ? 'touchmove.link' : 'mousemove.link',
            'endLink': exercice.Utils.isTablet() ? 'touchend.link' : 'mouseup.link',
            'deleteLink': exercice.Utils.isTablet() ? 'tap.link' : 'click.link'

        };
        var maxRight = 16, playerWidth = 800,
            minLeft = playerWidth;
        _anchors.forEach(function (anchor) {

            if (anchor.right > maxRight) {
                maxRight = anchor.right;
            }

            if (anchor.left < minLeft) {
                minLeft = anchor.left;
            }
        });

        _stageId = exercice.Utils.generateUUID();
        var canvasPos = '', canvasWidth = (maxRight - minLeft);
        canvasPos = 'left:' + Number((minLeft - dom._answer.offset().left)) + 'px';
        if ($('.container_kinetics').length) {
            $('.container_kinetics').remove();
        }
        var canvas_container = $('<div class="container_kinetics" id="container_' + _stageId +
            '" style="position: absolute;margin: 0; padding: 0; top: 0; ' + canvasPos + '" ></div>');
        $(".answer-content").append(canvas_container);

        _layer = new Kinetic.Layer({
            clearBeforeDraw: true
        });

        var _lists = $('.lists');

        if (!exercice.Utils.isTablet()) {
            $('.list').css({
                'width': '405px',
                'max-width': '405px'


            })
        } else {
            $('.list').css({
                'width': '200px',
                'max-width': '200px'

            })
        }

    }
    function addCanvasAndEvents() {
        var _lists = $('.lists');
        var _listA = _lists.find('.list').eq(0);
        var _listB = _lists.find('.list').eq(1);
        var _heightA = _listA.height();
        var _heightB = _listB.height();
        if (_heightA > _heightB) {
            var _hC = _heightA
        } else if (_heightB > _heightA) {
            var _hC = _heightB
        } else {
            _hC = _heightA
        }
        _stage = new Kinetic.Stage({
            id: 'stage' + _stageId,
            container: 'container_' + _stageId,
            width: 200,
            height: _hC,
            listening: true,
            visible: true,
            draggable: false
        });

        var background = new Kinetic.Rect({
            x: 0,
            y: 0,
            width: _stage.getWidth(),
            height: _stage.getHeight(),
            fill: "transparent"
        });
        _layer.add(background);
        _stage.add(_layer);
        _layer.setZIndex(10);
        bindEvents();
    }
    function bindEvents() {

        _stage.on(_linkingEvents.startLink, onMouseDown.bind(this));
        _stage.on(_linkingEvents.drawLink, onMouseMove.bind(this));
        _stage.on(_linkingEvents.deleteLink, onMouseClick.bind(this));
        $(_stage.content).on(_linkingEvents.endLink, onMouseUp.bind(this));
        $('body').on(_linkingEvents.endLink, onMouseUp.bind(this));
    }
    function getAnchorById(anchor_id) {
        var i = 0;
        for (i; i < _anchors.length; i++) {
            if (_anchors[i].id === anchor_id) {
                return _anchors[i];
            }
        }
        return null;
    }
    function onMouseUp(e) {

        if (!_moving) {
            return;
        }
        _moving = false;
        var __ret = getOverAnchor('mouseUp');
        _lastMovePositon = {};
        var mousePos = __ret.mousePos;
        var over_anchor = __ret.over_anchor;

        if (!over_anchor) {
            deleteLine();
            return true;
        }

        var elTarget = document.getElementById(over_anchor.id),
            do_drawLine = false;

        if ($(elTarget).hasClass('link_anchor')) {
            if (_line && _line.target_1) {
                var target_1 = _line.target_1,

                    anchor = getAnchorById(target_1);

                if (!$(elTarget).parent().hasClass('selected')) {
                    if (anchor) {

                        do_drawLine = !(anchor.list_id == over_anchor.list_id);
                    }
                } else {

                    if (_linkingMode === "oneToMany") {
                        if (over_anchor.isDefinitionAnchor()) {
                            do_drawLine = true;
                        }
                    }
                }

                var tmp_1 = _.where(_lines, { target_1: target_1, target_2: over_anchor.id });
                if (tmp_1.length) {
                    do_drawLine = !true;
                } else {
                    do_drawLine = true;
                }

                if ($('#' + target_1).parent().parent().parent().attr('name') === $('#' + over_anchor.id).parent().parent().parent().attr('name')) {
                    do_drawLine = false;
                }


            }
        } else {
            if (!_line) {

                if ($(elTarget).parent().hasClass('correct') || $(elTarget).parent().hasClass('incorrect')) {
                    return true;
                }

                $(elTarget).parent().removeClass('selected');
                $(elTarget).parent().find('.link_anchor').removeClass('selected');
            } else {
                deleteLine();

            }
        }
        if (do_drawLine) {
            $(elTarget).parent().addClass('selected');
            $(elTarget).parent().find('.link_anchor').addClass('selected');
            _line.target_2 = over_anchor.id;
            moveLineToTargets(_line);
            _layer.drawScene();
            _line = null;


        } else {
            deleteLine();
        }

    }
    function calcPoints(anchor1_rect, container_rect, anchor2_rect, connection_style) {
        var dividerX = 2, dividerY = 2;
        var points = [
            (anchor1_rect.right - container_rect.left) - (anchor1_rect.width / dividerX),
            (anchor1_rect.bottom - container_rect.top) - (anchor1_rect.height / dividerY),
            (anchor2_rect.left - container_rect.left) + (anchor2_rect.width / dividerX * (connection_style ? 0 : 1)),
            (anchor2_rect.top - container_rect.top) + (anchor2_rect.height / dividerY)
        ];
        return points;
    }
    function moveLineToTargets(line) {
        if (!line) {
            return;
        }

        var idOfAnchor1 = line.target_1, idOfAnchor2 = line.target_2,
            container_rect = _stage.getContainer().getBoundingClientRect(),
            anchor1_rect = document.getElementById(idOfAnchor1).getBoundingClientRect(),
            anchor2_rect = document.getElementById(idOfAnchor2).getBoundingClientRect(),
            points = calcPoints(anchor1_rect, container_rect, anchor2_rect);

        line.setPoints(points);
        _layer.drawScene();

    }
    function removeSelectedIfNeeded(line_target) {
        var anchor = getAnchorById(line_target);
        if (!anchor.isDefinitionAnchor()) {
            $('#' + line_target).parent().removeClass('selected');
            $('#' + line_target).parent().find('.link_anchor').removeClass('selected');
        } else {
            if (!hasConnectedLine(line_target)) {
                $('#' + line_target).parent().removeClass('selected');
                $('#' + line_target).parent().find('.link_anchor').removeClass('selected');

            }
        }
    }
    function onMouseClick(e) {

        if (!enabledValid) {
            return
        }

        if (_lastMovePositon.x) {
            return;
        }
        var __ret = getOverAnchor('mouseDown');
        var over_anchor = __ret.over_anchor;
        if (!over_anchor) {
            return true;
        }

        var elTarget = document.getElementById(over_anchor.id);
        if (!($(elTarget).parent().hasClass('_correctconnected') || $(elTarget).parent().hasClass('correct'))) {
            $(elTarget).parent().removeClass('selected');
            $(elTarget).parent().find('.link_anchor').removeClass('selected');
        }

        var linesToRemove = [], i = 0;
        for (i; i < _lines.length; i++) {
            if (_lines[i].target_1 === over_anchor.id && _lines[i].attrs.name != "correct") {
                linesToRemove.push(_lines[i]);
            } else if (_lines[i].target_2 === over_anchor.id && _lines[i].attrs.name != "correct") {
                linesToRemove.push(_lines[i]);
            }
        }

        var linesToRemoveLength = linesToRemove.length,
            i = 0;
        for (i; i < linesToRemoveLength; i++) {
            linesToRemove[i].destroy();
            _layer.drawScene();
            _lines = _.without(_lines, linesToRemove[i]);
            linesToRemove[i].target_1 && removeSelectedIfNeeded(linesToRemove[i].target_1);
            linesToRemove[i].target_2 && removeSelectedIfNeeded(linesToRemove[i].target_2);
        }
    }
    function onMouseMove(e) {

        if (!enabledValid) {
            return
        }
        var evt = e.evt ? e.evt : e;
        this.mouseMove_preventDefault = evt.preventDefault;

        var mousePos = _stage.getPointerPosition();
        var xPos = mousePos ? mousePos.x : evt.pageX;
        var yPos = mousePos ? mousePos.y : evt.pageY;

        _lastMovePositon = { x: xPos, y: yPos };
        if (_moving && _line) {
            evt.preventDefault = this.mouseMove_preventDefault;
            var newPoints = _line.getPoints();
            newPoints[2] = xPos;
            newPoints[3] = yPos;
            _line.setPoints(newPoints);
            _moving = true;
            _layer.drawScene();

        } else {
            evt.preventDefault = null;
        }
    }
    function onMouseDown(e) {

        if (!enabledValid) {
            return
        }
        var evt = e.evt ? e.evt : e;
        this.mouseDown_preventDefault = evt.preventDefault;
        evt.preventDefault = null;
        _lastMovePositon = {};
        if (_moving) {
            _moving = false;
        } else {
            var __ret = getOverAnchor('mouseDown');
            var mousePos = __ret.mousePos;
            var over_anchor = __ret.over_anchor;
            if (!over_anchor) {
                return true;
            }
            var elTarget = document.getElementById(over_anchor.id),
                isValidLineStart = true;
            if (_linkingMode === "oneToMany") {
                if ($(elTarget).parent().hasClass('selected')) {
                    if (over_anchor.isDefinitionAnchor()) {
                        isValidLineStart = true;
                    }
                } else {
                    isValidLineStart = true;
                }
            }
            else if (!$(elTarget).parent().hasClass('selected')) {
                isValidLineStart = true;

            } else {

                if ($(elTarget).parent().hasClass('correct') || $(elTarget).parent().hasClass('incorrect') || $(elTarget).parent().hasClass('_correctconnected')) {
                    return true;
                }
                $(elTarget).parent().removeClass('selected');
                $(elTarget).parent().find('.link_anchor').removeClass('selected');



                var tmp = _.where(_lines, { target_1: elTarget.id });
                if (!tmp.length) {
                    tmp = _.where(_lines, { target_2: elTarget.id });
                }

                if (tmp.length) {
                    tmp[0].destroy();
                    $('#' + tmp[0].target_1).parent().find('.link_anchor').removeClass('selected');
                    $('#' + tmp[0].target_2).parent().find('.link_anchor').removeClass('selected');
                    tmp[0].target_1 && $('#' + tmp[0].target_1).parent().removeClass('selected');
                    tmp[0].target_2 && $('#' + tmp[0].target_2).parent().removeClass('selected');

                    _lines = _.without(_lines, tmp[0]);


                }


            }
            if (isValidLineStart) {
                $(elTarget).parent().addClass('selected');
                $(elTarget).parent().find('.link_anchor').addClass('selected');
                addLine(over_anchor, mousePos, evt);
                _moving = true;
                _layer.drawScene();
            }
        }
    }
    function hasConnectedLine(line_target) {
        if (!line_target) {
            return false;
        }
        var tmp = _.where(_lines, { target_1: line_target });
        if (!tmp.length) {
            tmp = _.where(_lines, { target_2: line_target });
        }
        return tmp.length ? true : false;
    }
    function deleteLine() {

        if (_line) {
            var lineTarget1 = _line.target_1;
            var lineTarget2 = _line.target_2;
            _line.destroy();
            _lines = _.without(_lines, _line);
            if (lineTarget1 && !hasConnectedLine(lineTarget1)) {
                $(document.getElementById(lineTarget1)).parent().removeClass('selected');
                $(document.getElementById(lineTarget1)).parent().find('.link_anchor').removeClass('selected');

            }

            if (lineTarget2 && !hasConnectedLine(lineTarget2)) {
                $(document.getElementById(lineTarget2)).parent().removeClass('selected');
                $(document.getElementById(lineTarget2)).parent().find('.link_anchor').removeClass('selected');
            }
            _line = null;
            _moving = false;
            _layer.drawScene();

        }
    }
    function deleteLines() {

        if (_lines.length) {
            _lines.forEach(function (line) {
                var lineTarget1 = line.target_1;
                lineTarget1 && $(document.getElementById(lineTarget1)).parent().removeClass('selected');
                $(document.getElementById(lineTarget1)).parent().find('.link_anchor').removeClass('selected');

                var lineTarget2 = line.target_2;
                lineTarget2 && $(document.getElementById(lineTarget2)).parent().removeClass('selected');
                $(document.getElementById(lineTarget2)).parent().find('.link_anchor').removeClass('selected');

                line.destroy();
            });
            _layer.drawScene();
            _lines = [];
        }


    }
    function drawLines() {
        var _line;
        for (var i = 0; i < _lines.length; i++) {
            _line = new Kinetic.Line({
                points: [_lines[i].attrs.points[0], _lines[i].attrs.points[1], _lines[i].attrs.points[2], _lines[i].attrs.points[3]],
                strokeWidth: 3,
                stroke: "#808080",
                lineCap: 'round',
                lineJoin: 'round'
            });
            _layer.add(_line);
            _layer.draw();
        }
    }
    function deleteInCorrectLines() {
        var linesToRemove = _.filter(_lines, function (line) {
            return line.feedback != 'correct'
        }), thi$ = this;

        linesToRemove.forEach(function (line, index) {
            var lineTarget1 = line.target_1;
            if (lineTarget1 && !$(document.getElementById(lineTarget1)).parent().hasClass("_correctconnected")) {
                $(document.getElementById(lineTarget1)).parent().removeClass('selected');
                $(document.getElementById(lineTarget1)).parent().find('.link_anchor').removeClass('selected');
            }

            var lineTarget2 = line.target_2;
            lineTarget2 && $(document.getElementById(lineTarget2)).parent().removeClass('selected');
            $('#' + lineTarget1).removeClass('correct').removeClass('wrong');
            $('#' + lineTarget2).removeClass('correct').removeClass('wrong');
            $('#' + lineTarget1).find('#incorrect').hide();
            $('#' + lineTarget2).find('#incorrect').hide();
            line.destroy();
            _lines = _.without(_lines, line);
        });

        linesToRemove = null;
        _layer.drawScene();
        _lines.forEach(function (line, index) {
            var lineTarget1 = line.target_1;
            var lineTarget2 = line.target_2;

            $('#' + lineTarget2).addClass('correct');
            $('#' + lineTarget2).find('#correct').show();

            $('#' + lineTarget1).addClass('correct');
            $('#' + lineTarget1).find('#correct').show();


        });


    }
    function addLine(over_anchor, mousePos, e) {
        _line = new Kinetic.Line({
            points: [0, 0, 0, 0],
            strokeWidth: 3,
            stroke: "#808080",
            lineCap: 'round',
            lineJoin: 'round'
        });
        _layer.add(_line);
        _line.target_1 = over_anchor.id;
        _lines.push(_line);

        var newPoints = [];
        newPoints[0] = mousePos ? mousePos.x : e.pageX;
        newPoints[1] = mousePos ? mousePos.y : e.pageY;
        newPoints[2] = mousePos ? mousePos.x : e.pageX;
        newPoints[3] = mousePos ? mousePos.y : e.pageY;
        _line.setPoints(newPoints);


    }
    function loadAnchorsRect() {
        _anchors = _.map(document.querySelector('#content').querySelectorAll('.link_anchor'), function (anchor) {
            var rect = anchor.getBoundingClientRect(),
                containingList = $(anchor).closest('.list');
            rect.id = anchor.id;

            rect.list_id = containingList.attr('id');

            rect.list_type = containingList.attr('name') === "List A" ? "definitions" : "options";

            rect.isDefinitionAnchor = function () {
                return this.list_type === "definitions";
            };
            return rect;
        });
    }
    function getOverAnchor(type) {
        loadAnchorsRect();

        var mousePos = _stage.getPointerPosition(), over_anchor,
            container_rect = _stage.getContainer().getBoundingClientRect();

        if (type === 'mouseUp' && _lastMovePositon) {
            mousePos = mousePos || {};
            mousePos.y = _lastMovePositon.y;
            mousePos.x = _lastMovePositon.x;
        }

        var yPointer = container_rect.top + mousePos.y,
            xPointer = container_rect.left + mousePos.x;

        var over_anchors = _.filter(_anchors, function (anchor) {
            return ((anchor.top <= yPointer) && (anchor.bottom > yPointer) &&
                (anchor.left <= xPointer) && (anchor.right > xPointer));
        });

        if (over_anchors.length) {
            over_anchor = over_anchors[0];
        }

        return { mousePos: mousePos, over_anchor: over_anchor };
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// COMPLETE DD SYSTEM /////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function createTemplateCompleteDD(data, _typo) {
        _listOfWordsCorrects = [];
        _goodAnswers = [];
        _solutions_qc = [];
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        dom._imageViewer_content.html('');
        if ($('body').hasClass('preview')) {
            var wrap = $("#content-exo");
            var _bank;
            wrap.on("scroll", function (e) {
                _bank = $(".bank");

                if (Math.floor($('.answer').offset().top) < 163) {
                    _bank.addClass("fix-search");
                    _bank.offset({
                        top: 163
                    })

                } else {
                    _bank.removeClass("fix-search");
                    _bank.css({
                        top: '0px'
                    })
                }

            });
        }

        var TEMPLATE = '<div id="' + exercice.Utils.generateUUID() + '" class="clozeArea" id="clozeArea"><div id="clozeArea_content"></div></div>';
        dom._answer_content.append(TEMPLATE);
        dom._clozeArea = $(".clozeArea");
        dom._clozeArea_content = $("#clozeArea_content");
        dom._clozeArea_content.append(generateTextViewer());
        dom._clozeArea_content_textViewer_content = dom._clozeArea_content.find('.textViewer_content');
        dom._clozeArea_content_textViewer_content.html(generateTextViewerParagraph());
        dom._clozeArea_content_textViewerParagraph = dom._clozeArea_content.find('.textViewer').find('.textViewerParagraph');
        addImage(data, 600, 300, data.activity_image_position, _typo);
        var t = data.activity_data;
        try {
            parsedData = JSON.parse(t);
            dom._clozeArea_content_textViewerParagraph.append(exercice.Utils.doReplace(parsedData));
        } catch (e) {
            dom._clozeArea_content_textViewerParagraph.append(exercice.Utils.doReplace(t));
        }
        ;
        dom._clozeArea_content_textViewerParagraph.find("span").each(function () {

            if ($(this).attr('class') === "editor_delete_word") {
                $(this).remove();
            }

            if ($(this).attr('class') === "editor_word") {
                var str = $(this).html().split('⊗').join('');
                _goodAnswers.push(str);
                _listOfWordsCorrects.push(str);
                _solutions_qc = shuffleArray(_listOfWordsCorrects);
                $(this).before(createBoxTarget());
                $(this).remove();
            }
        });
        createBoxForDragElement();
        createEventsForCompleteDD();


    }

    function createBoxTarget() {
        if ($('body').hasClass('primaire')) {
            var tpl = '<div class="subAnswer 0 custom-alignment drop-target " id="gen_id_' + exercice.Utils.generateUUID() + '" style="width: 128px; height: 45px;">			' +
                '<div class="subAnswer_content_wrap " id="gen_id_' + exercice.Utils.generateUUID() + '_content_wrap" style="width: 128px; height: 40px;">									' +
                '<div class="status_icon">					' +
                '<span id="correct" class="icon-right_icon"></span>' +
                '<span id="wrong" class="icon-wrong_icon"></span>' +
                '</div>				' +
                '<div class="subAnswer_content shadow" id="gen_id_' + exercice.Utils.generateUUID() + '_content" style="width: 128px; height:40px;">' +
                '<div class="textViewer textViewerStyle ltr compact" id="gen_id_' + exercice.Utils.generateUUID() + '" style="direction: ltr; text-align: left;height: 40px; font-size: 18px; min-width: 98px; display: none;line-height: 40px;">            ' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="textViewer_content"><div>' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="textViewerParagraph">' +
                '<span contenteditable="false" class="normal"></span>' +
                '</div>' +
                '</div>' +
                '</div>' +
                ' </div>' +
                '</div>											' +
                '</div>	';
        } else {
            var tpl = '<div class="subAnswer 0 custom-alignment drop-target " id="gen_id_' + exercice.Utils.generateUUID() + '" style="width: 128px; height: 40px;">			' +
                '<div class="subAnswer_content_wrap " id="gen_id_' + exercice.Utils.generateUUID() + '_content_wrap" style="width: 128px; height: 35px;">									' +
                '<div class="status_icon">					' +
                '<span id="correct" class="icon-right_icon"></span>' +
                '<span id="wrong" class="icon-wrong_icon"></span>' +
                '</div>				' +
                '<div class="subAnswer_content shadow" id="gen_id_' + exercice.Utils.generateUUID() + '_content" style="width: 128px; height: 35px;">' +
                '<div class="textViewer textViewerStyle ltr compact" id="gen_id_' + exercice.Utils.generateUUID() + '" style="direction: ltr; text-align: left;height: 35px; font-size: 18px; min-width: 98px; display: none;line-height: 35px;">            ' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="textViewer_content"><div>' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="textViewerParagraph">' +
                '<span contenteditable="false" class="normal"></span>' +
                '</div>' +
                '</div>' +
                '</div>' +
                ' </div>' +
                '</div>											' +
                '</div>	';
        }



        return tpl;
    }

    function createEventsForCompleteDD() {
        dom._draggable = $("#content").find(".draggable");
        dom._target = $(".drop-target");
        dom._draggable.bind("mousedown touchstart", startDragging);
        if ($(".classer").length) {
            dom._target.bind("mousedown touchstart", '.column__item', targetDownItem)
        } else {
            dom._target.bind("mousedown touchstart", targetDown);
        }
        bankOffsetTop = $(".bank").offset().top;
        bankOffsetLeft = $(".bank").offset().left;
    }

    function targetDownItem(evt) {
        evt.preventDefault()
        var _id = "";
        var _target





        if (evt.target.className === "normal") {

            _target = $(evt.target).parent().parent()
            _id = _target.parent().parent().attr('id')


        } else if (evt.target.className === "textViewerParagraph") {

            _target = $(evt.target).parent()
            _id = _target.parent().parent().attr('id')

        }



        if (_id != "") {

            _target.parent().parent().remove();
            dom._draggable.each(function () {

                if (_id === $(this).parent().parent().attr('id')) {

                    $(this).removeClass('pop');
                    $(this).css({
                        "left": 0,
                        "top": 0,
                        "opacity": 1,
                        "visibility": "visible"

                    });
                }


            })
        }

    }



    function targetDown(evt) {

        if ($(this).find(".textViewer").text().trim() != "") {
            var target = $(this);
            if (target.hasAnyClass('correct') || target.hasAnyClass('wrong')) {
                return;
            }
            var t = target.attr('data-id'); // onclick
            dom._draggable.each(function () {

                if (t === $(this).parent().parent().attr('id')) {
                    target.attr('data-id', 'l');
                    target.removeClass('full').removeClass('occuped').removeClass('up');
                    target.find('.textViewer').html("");
                    $(this).removeClass('pop');
                    $(this).css({
                        "left": 0,
                        "top": 0,
                        "opacity": 1,
                        "visibility": "visible"

                    });
                }


            })

        }
    }

    function updateopop() {
        coordinates_drag = [];
        coordinates = [];
        createEventsForCompleteDD();
    }

    function startDragging(e) {

        e.preventDefault();
        e.stopPropagation();
        if (!enabledValid) {
            return
        }

        dom._draggable.each(function () {
            var lefttop = $(this).offset();
            coordinates_drag.push({
                dom: $(this),
                left: lefttop.left,
                top: lefttop.top,
                right: lefttop.left + $(this).width(),
                bottom: lefttop.top + $(this).height(),
                id: 0
            });
        });

        var t = $(this).parent().parent().attr('id');
        var _mo = $(this);
        dom._target.each(function () {
            if (t === $(this).attr('data-id')) {
                $(this).attr('data-id', 'l');
                $(this).removeClass('full').removeClass('occuped').removeClass('up');
                $(this).find('.textViewer').html("");
            }
            var lefttop = $(this).offset();
            idDrop.push($(this).attr('id'));
            coordinates.push({
                dom: $(this),
                left: lefttop.left,
                top: lefttop.top,
                right: lefttop.left + $(this).width(),
                bottom: lefttop.top + $(this).height(),
                id: 0
            });
        });

        if (e.type == "mousedown" || e.type == "touchstart") {

            dragged = $(this);
            if ($(this).addClass('pop')) {
                $(this).removeClass('pop').css({ 'opacity': 1 })

            }
            var __ret = getCoordinate.apply(this, [e]),
                pageX = __ret.pageX,
                pageY = __ret.pageY;


            drg_h = dragged.outerHeight(),
                drg_w = dragged.outerWidth(),
                pos_y = dragged.offset().top + drg_h - pageY,
                pos_x = dragged.offset().left + drg_w - pageX;

            $(document).bind("mousemove touchmove", continueDragging);
            $(document).bind("mouseup touchend", endDragging);
        }
    }

    function endDragging(e) {
        // Remove document event listeners
        var __ret = getCoordinate.apply(this, [e]),
            pageX = __ret.pageX,
            pageY = __ret.pageY;

        $(document).unbind("mousemove touchmove", continueDragging);
        $(document).unbind("mouseup touchend", endDragging);
        targetActive = $('.somethingover');
        if (targetActive.length) {

            if ($(".classer").length) {
                targetActive.append('<div id="' + dragged.parent().parent().attr('id') + '" class="column__item">' + dragged.find('.textViewer').html() + '</div>');
            } else {

                targetActive.parent().parent().addClass('textviewer full occuped up');
                targetActive.find('.textViewer').css({ 'display': 'block' });
                targetActive.find('.textViewer').addClass('occuped');
                targetActive.find('.textViewer').html(dragged.find('.textViewer').html());
            }



            targetActive.removeClass('somethingover');

            if (!$(".classer").length) {
                if (targetActive.parent().parent().attr('data-id') != "") {
                    $('.subAnswer_content').each(function (index) {
                        if ($(this).parent().parent().attr('id') === targetActive.parent().parent().attr('data-id')) {
                            $(this).removeClass('pop');
                            $(this).css({
                                "left": 0,
                                "top": 0,
                                "opacity": 1,
                                "visibility": "visible"
                            });
                        }

                    });
                } else {

                }
            }

            targetActive.parent().parent().attr('data-id', dragged.parent().parent().attr('id'));

            dragged.offset({
                "left": target.left,
                "top": target.top

            });
            dragged.css({
                "opacity": 0,
                "visibility": "hidden",
                "z-index": "10"

            });
            dragged.addClass('pop')
        } else {
            dragged.removeClass('pop');
            dragged.css({
                "left": 0,
                "top": 0

            });
        }


    }

    function continueDragging(e) {
        e.preventDefault();
        e.stopPropagation();

        $('.bank').removeClass("open-sidebar");


        $(".subAnswer").each(function () {
            if ($(this).attr('data-id') === dragged.parent().parent().attr('id')) {
                $(this).find('.textViewer').html("");
                $(this).attr('data-id', 'l');
                $(this).removeClass('occuped').removeClass('up');
            }
        });
        var __ret = getCoordinate.apply(this, [e]),
            pageX = __ret.pageX,
            pageY = __ret.pageY;
        var top = Number(pageY) + Number(pos_y) - Number(drg_h),
            left = Number(pageX) + Number(pos_x) - Number(drg_w);
        dragged.css({
            "z-index": "100000000"
        })
        dragged
            .offset({
                top: top,
                left: left
            });

        for (var i in coordinates) {

            coordinates[i].dom.find('.subAnswer_content_wrap').find('.subAnswer_content').removeClass("somethingover");
            if (!coordinates[i].dom.hasClass('occuped') && !coordinates[i].dom.hasClass('correct')) {
                coordinates[i].dom.removeClass('textviewer full');
                coordinates[i].dom.find('.textViewer').css({ 'display': 'none' });
                coordinates[i].dom.find('.textViewer').html("")
            }

            if (mousex >= coordinates[i].left && mousex <= coordinates[i].right && !coordinates[i].dom.hasClass('correct')) {



                if (mousey >= coordinates[i].top && mousey <= coordinates[i].bottom) {
                    target = coordinates[i];

                    if ($(".classer").length) {
                        coordinates[i].dom.addClass("somethingover");
                    } else {
                        coordinates[i].dom.find('.subAnswer_content_wrap').find('.subAnswer_content').addClass("somethingover");
                    }




                }
            } else {
                if ($(".classer").length) {
                    coordinates[i].dom.removeClass("somethingover");
                } else {
                    coordinates[i].dom.find('.subAnswer_content_wrap').find('.subAnswer_content').removeClass("somethingover");
                }
            }
        }



        mousex = pageX;
        mousey = pageY;

    }

    function getDropBoxes() {

        _listOfWordsInputs = [];
        var _b = ""
        dom._clozeArea_content.find('.subAnswer').find('.textViewer').each(function (i) {
            if ($(this).find('.normal').length) {
                _b = $(this).find('.normal').html();
            } else {
                _b = $(this).html();
            }
            _listOfWordsInputs.push(_b)
        });

        return _listOfWordsInputs.length > 0 ? _listOfWordsInputs : null;


    }

    function getContentTxt(elt) {
        var elts = [];
        for (var i = 0; i < $(elt).length; i++) {
            elts.push($(elt).eq(i).text());
        }

        return elts.length > 0 ? elts : null;
    }

    function getCheckedBoxes(chkboxName) {
        var checkboxes = document.getElementsByClassName(chkboxName);
        var checkboxesChecked = [];
        for (var i = 0; i < checkboxes.length; i++) {

            if (hasClass(checkboxes[i], "selected")) {
                checkboxesChecked.push(true);
            } else {
                checkboxesChecked.push(false);
            }
        }
        return checkboxesChecked.length > 0 ? checkboxesChecked : null;


    }

    function updateCoordinates() {
        if ($(".bank").offset().top > bankOffsetTop) {

            if ($('.pop').length) {
                $('.pop').each(function () {
                    var lefttop = $(this).offset()


                    $(this)
                        .offset({
                            top: lefttop.top + bankOffsetTop - $(".bank").offset().top,
                            left: lefttop.left + bankOffsetLeft - $(".bank").offset().left
                        });

                });
                bankOffsetTop = $(".bank").offset().top
            }
        } else if ($(".bank").offset().top < bankOffsetTop) {
            if ($('.pop').length) {
                $('.pop').each(function () {
                    var lefttop = $(this).offset()
                    $(this)
                        .offset({
                            top: bankOffsetTop - $(".bank").offset().top,
                            left: bankOffsetLeft - $(".bank").offset().left
                        });

                });
                bankOffsetTop = $(".bank").offset().top
            }
        }



    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// COMPLETE SAISIE SYSTEM /////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function deletePunctuation(str) {
        return str.replace(/(~|`|!|@|#|$|%|^|&|\*|\(|\)|{|}|\[|\]|;|:|\"|'|<|,|\.|>|\?|\/|\\|\||-|_|\+|=)/g, "")
    }

    function createTemplateComplete(data, _typo) {

        _listOfWordsCorrects = [];
        _copyOfListOfWordsCorrects = [];
        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        // image
        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position, _typo);

        // Area
        var TEMPLATE = '<div id="' + exercice.Utils.generateUUID() + '" class="clozeArea"><div id="clozeArea_content"></div></div>';
        dom._answer_content.append(TEMPLATE);
        dom._clozeArea_content = $('#clozeArea_content');
        dom._clozeArea = $('.clozeArea');
        //textViewerParagraph
        dom._clozeArea_content.append(generateTextViewer());
        $('#clozeArea_content .textViewer_content').html(generateTextViewerParagraph());
        if (data.activity_image === "") {
            dom._clozeArea_content.find('.textViewer').css({ 'width': '100%' });
        }

        _casse = data.activity_casse;

        var u = data.activity_data;

        try {
            parsedData = JSON.parse(u);
            $('#clozeArea_content .textViewerParagraph').append(exercice.Utils.doReplace(parsedData));
        } catch (e) {
            $('#clozeArea_content .textViewerParagraph').append(exercice.Utils.doReplace(u));
        }

        $('#clozeArea_content .textViewerParagraph').find("span").each(function () {
            if ($(this).attr('class') === "editor_delete_word") {
                $(this).remove();
            }

            if ($(this).attr('class') === "editor_word") {

                if (_casse === "yes") {
                    _listOfWordsCorrects.push($(this).text().split('⊗')[0].trim());
                    _copyOfListOfWordsCorrects.push($(this).text().split('⊗')[0].trim());
                } else {
                    _listOfWordsCorrects.push(deletePunctuation($(this).text().split('⊗')[0].trim().toLowerCase()));
                    _copyOfListOfWordsCorrects.push($(this).text().split('⊗')[0].trim());
                }

                $(this).before(generateSubAnswerFoInput());
                $(this).remove();
            }
        }
        );

        for (var t = 0; t < _listOfWordsCorrects.length; t++) {
            $('#clozeArea_content .textViewerParagraph').find('.subAnswer').eq(t).find('.subAnswer_content').append(createBoxForExoComplete(_listOfWordsCorrects[t]));

        }
        $('input[type="text"]').keyup(resizeInput)


    }
    function resizeInput() {
        var _this = $(this)
        var _t = setTimeout(function () { _this.attr('size', _this.val().length + 5); }, 300)

    }

    function createBoxForExoComplete() {
        var Tpl = "<div class='miniTextEditor' id='" + exercice.Utils.generateUUID() + "'><input id='" + exercice.Utils.generateUUID() + "_te' type='text' value='' size='6' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false'> </div>"
        return Tpl

    }

    function generateSubAnswer() {
        var TEMPLATE =
            "<div class='subAnswer textviewer full compact' id='" + exercice.Utils.generateUUID() + "' ><div class='subAnswer_content_wrap' id='" + exercice.Utils.generateUUID() + "_content_wrap' ><div class='status_icon'><span id='correct' class='icon-right_icon'></span><span id='wrong' class='icon-wrong_icon'></span>\
                        </div><div class='subAnswer_content not_droppable disabled' id='" + exercice.Utils.generateUUID() + "_content'></div><div class='subAnswer_content draggable' id='" + exercice.Utils.generateUUID() + "_content'></div></div></div>"

        return TEMPLATE
    }

    function generateSubAnswerFoInput() {
        var TEMPLATE = "<div class='subAnswer texteditor full compact' id='" + exercice.Utils.generateUUID() + "' >" +
            "<div class='subAnswer_content_wrap' id='" + exercice.Utils.generateUUID() + "_content_wrap' >\
            <div class='status_icon'>\
            <span id='correct' class='icon-right_icon'></span>\
            <span id='wrong' class='icon-wrong_icon'></span>\
            </div>\
            <div class='subAnswer_content' id='" + exercice.Utils.generateUUID() + "_content'></div>" +
            "</div>" +
            "</div>";
        return TEMPLATE
    }

    function getInputBoxes(input) {
        _listOfWordsInputs = [];
        $('.miniTextEditor').each(function (i) {
            if (_casse === "yes") {
                _listOfWordsInputs.push($(this).find('input').val());
            } else {
                _listOfWordsInputs.push(deletePunctuation($(this).find('input').val().toLowerCase()));
            }

        });
        return _listOfWordsInputs.length > 0 ? _listOfWordsInputs : null;


    }



    function createAudioConsigne(data) {
        var currentPlayed;
        var curPlaying = 0;
        var _path;
        if ($('.audioconsigne_player').length) {
            $('.audioconsigne_player').remove();
        }
        if ($('.icon-imageViewer-small').length) {
            $('.icon-imageViewer-small').remove();
        }
        if (data.activity_audio != "") {
            _path = 'uploads/' + data.activity_audio;
        } else {
            _path = "";
        }
        var _id = exercice.Utils.generateUUID();
        var template_audio = '<div id="gen_id_' + _id + '" class="mediaPlayer audioControl soundButton audioconsigne_player icon-sound_02_icon" style="">' +
            '<audio src="uploads/' + data.activity_audio + '" id="gen_id_' + exercice.Utils.generateUUID() + '_soundButtonMedia" preload="none">' +
            '</audio>' +
            '</div>';
        dom._questionViewer.after(template_audio);
        dom._questionViewer.after('<div class="icon-imageViewer-small"><a class="svg"><object data="images/mms.svg" type="image/svg+xml" class="mailicon"></object></a></div>');
        dom._icon_imageViewer_small = $('.icon-imageViewer-small');
        dom._icon_imageViewer_small.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            showSmallImage()
        });
        if (data.activity_audio.length) {
            $('.audioconsigne_player').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                var mediaplayer = $(this).find('.mediaPlayer');
                $(".mediaPlayer").removeClass("playing");
                curPlaying = 0;
                mediaManager.setMedia(document.getElementById($(this).find('audio').attr('id')), true);
                mediaManager.load();
                if (currentPlayed === document.getElementById($(this).find('audio').attr('id'))) {

                } else {
                    $('#gen_id_' + _id).removeClass('playing');
                    if (currentPlayed) {
                        if (currentPlayed.readyState > 0) {

                        }
                    }

                    currentPlayed = document.getElementById($(this).find('audio').attr('id'))

                }

                if ($('#gen_id_' + _id).hasClass('playing')) {
                    $('#gen_id_' + _id).removeClass('playing');

                } else {

                    $('#gen_id_' + _id).addClass('playing');

                }

                if (!curPlaying) {
                    mediaManager.play();
                    curPlaying = 1;
                } else {
                    mediaManager.pause();
                    curPlaying = 0;
                }
                // mediaManager.play();
                mediaManager.ended(function () {
                    if (currentPlayed.readyState > 0) {
                        currentPlayed.pause();
                        currentPlayed.readyState.currentTime = 0;
                        curPlaying = 0;

                    }

                    $('#gen_id_' + _id).removeClass('playing');
                });


            })
        } else {
            $('.audioconsigne_player').hide();
        }
    }
    function createAudioTTSConsigne(data) {
        var currentPlayed;
        var curPlaying = 0;
        var _path;
        if ($('.audiotts_player').length) {
            $('.audiotts_player').remove();
        }
        if (data.activity_audio_tts != "") {
            _path = 'uploads/' + data.activity_audio + '.mp3';
        } else {
            _path = "";
        }
        var _id = exercice.Utils.generateUUID();
        var template_audio = '<div id="gen_id_' + _id + '" class="mediaPlayer audioControl soundButton audiotts_player icon-sound_02_icon" style="">' +
            '<audio src="uploads/' + data.activity_audio_tts + '.mp3' + '" id="gen_id_' + exercice.Utils.generateUUID() + '_soundButtonMedia" preload="none">' +
            '</audio>' +
            '</div>';
        $('.question-content').find('p').first().append(template_audio);
        if (data.activity_audio_tts) {
            if (data.activity_audio_tts.length) {
                $('.audiotts_player').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                    var mediaplayer = $(this).find('.mediaPlayer');
                    $(".mediaPlayer").removeClass("playing");
                    curPlaying = 0;
                    mediaManager.setMedia(document.getElementById($(this).find('audio').attr('id')), true);
                    mediaManager.load();
                    if (currentPlayed === document.getElementById($(this).find('audio').attr('id'))) {

                    } else {
                        $('#gen_id_' + _id).removeClass('playing');
                        if (currentPlayed) {
                            if (currentPlayed.readyState > 0) {

                            }
                        }

                        currentPlayed = document.getElementById($(this).find('audio').attr('id'))

                    }

                    if ($('#gen_id_' + _id).hasClass('playing')) {
                        $('#gen_id_' + _id).removeClass('playing');

                    } else {

                        $('#gen_id_' + _id).addClass('playing');

                    }

                    if (!curPlaying) {
                        mediaManager.play();
                        curPlaying = 1;
                    } else {
                        mediaManager.pause();
                        curPlaying = 0;
                    }
                    // mediaManager.play();
                    mediaManager.ended(function () {
                        if (currentPlayed.readyState > 0) {
                            currentPlayed.pause();  // make sure it stopped.
                            currentPlayed.readyState.currentTime = 0;
                            curPlaying = 0;

                        }

                        $('#gen_id_' + _id).removeClass('playing');
                    });


                })
            } else {
                $('.audiotts_player').hide();
            }
        } else {
            $('.audiotts_player').hide();
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// QCM AND QCU SYSTEM ////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function createTemplateQC(data, typo) {

        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);

        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position, typo);



    }

    var _positionAnswer = []
    var _positionAnswerLink = {}

    function getPositionAnswer(section){
        if(section==="link") {
            return _positionAnswerLink
        } else {
            return _positionAnswer
        }
           
    }




    function createExoQC(data) {

        createContainerBox();
        _solutions_qc = []


        var str;
        if (typeof (data.activity_data) === 'object') {
            str = data.activity_data;
        } else {
            str = JSON.parse(data.activity_data)
        }
        var str_2 = [];


        var _finded = 0;
        var _tmp_1 = [];
        var _tmp_2 = [];
        var _tmp = [];
        var _pop = []


        if (_modePlayer === "correction" && _collection[_active_activity] &&_.size(_collection[_active_activity].activity_data)) {
            for (var t = 0; t < _collection[_active_activity].activity_data.length; t++) {
                createBox(_collection[_active_activity].activity_data[t].answer);
                _solutions_qc.push(_collection[_active_activity].activity_data[t].checked);
            }
        } else {


            if (str.length > _qcm_qcu_max) {

                _tmp_1.push(_.filter(str, function (o) { return o.checked === true; }));
                _tmp_2.push(_.filter(str, function (o) { return o.checked === false; }));

                _tmp = _.union(shuffleArray(_tmp_1[0]), shuffleArray(_tmp_2[0]));

                for (var u = 0; u < _qcm_qcu_max; u++) {
                    str_2.push(_tmp[u])

                }

                str_2 = shuffleArray(str_2);
                _pop = str_2;
                for (var t = 0; t < _qcm_qcu_max; t++) {
                    createBox(str_2[t].answer);
                    _solutions_qc.push(str_2[t].checked);
                }

            } else {
                str = shuffleArray(str)
                _pop = str;
                for (var t = 0; t < str.length; t++) {
                    createBox(str[t].answer);
                    _solutions_qc.push(str[t].checked);
                }
            }
            _positionAnswer = _pop
           // populateCollection(_active_activity, _pop)
        }


    }

    function getMaxWidthBoxOfQC(elts) {
        max = 0;
        elts.each(function () {
            c_width = parseInt($(this).width());
            if (c_width > max) {
                max = c_width;
            }
        });
        return max;


    }

    function createEventForExoQC() {
        var currentPlayed;
        var curPlaying = 0;
        if ($('.textViewer_content').length) {
            $('.textViewer_content').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                e.stopPropagation();
                if (e.target.className === "soundButton_content" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown playing" || e.target.className === "calque_sound on" || e.target.className === "calque_sound off") {
                    var mediaplayer = $(this).find('.mediaPlayer');

                    mediaManager.setMedia(document.getElementById($(this).find('.soundButton_content').find('audio').attr('id')), true);
                    mediaManager.load();
                    if (currentPlayed === document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))) {


                    } else {
                        $('.mediaPlayer').removeClass('playing');
                        $('.mediaPlayer').find('.off').show();
                        $('.mediaPlayer').find('.on').hide();
                        if (currentPlayed) {
                            if (currentPlayed.readyState > 0) {
                                currentPlayed.currentTime = 0;
                            }
                        }

                        currentPlayed = document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))

                    }

                    if (mediaplayer.hasClass('playing')) {
                        mediaplayer.removeClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.pause();
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });

                    } else {
                        mediaplayer.addClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.play();
                        exercice.Utils.setStyle([_target_off], { 'display': 'none' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'flex' });


                    }


                    mediaManager.ended(function () {
                        if (document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).readyState > 0) {
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).pause();  // make sure it stopped.
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).currentTime = 0;


                        }
                        var _target_off = mediaplayer.find('.off');
                        var _target_on = mediaplayer.find('.on');
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }



                if (!enabledValid) {
                    return
                }


            });
        }

        if ($('.option_body').length) {
            $('.option_body').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                e.stopPropagation();

                if (e.target.className === "soundButton_content" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown playing" || e.target.className === "calque_sound on" || e.target.className === "calque_sound off") {
                    var mediaplayer = $(this).find('.mediaPlayer');



                    mediaManager.setMedia(document.getElementById($(this).find('.soundButton_content').find('audio').attr('id')), true);
                    mediaManager.load();
                    if (currentPlayed === document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))) {


                    } else {
                        $('.mediaPlayer').removeClass('playing');
                        $('.mediaPlayer').find('.off').show();
                        $('.mediaPlayer').find('.on').hide();
                        if (currentPlayed) {
                            if (currentPlayed.readyState > 0) {
                                currentPlayed.currentTime = 0;
                            }
                        }

                        currentPlayed = document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))

                    }

                    if (mediaplayer.hasClass('playing')) {
                        mediaplayer.removeClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.pause();
                        // exercice.Utils.setStyle([_target_off], { 'display': 'block' });
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });

                    } else {
                        mediaplayer.addClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.play();
                        exercice.Utils.setStyle([_target_off], { 'display': 'none' });
                        // exercice.Utils.setStyle([_target_on], { 'display': 'block' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'flex' });


                    }


                    mediaManager.ended(function () {

                        if (document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).readyState > 0) {
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).pause();  // make sure it stopped.
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).currentTime = 0;


                        }
                        var _target_off = mediaplayer.find('.off');
                        var _target_on = mediaplayer.find('.on');
                        // exercice.Utils.setStyle([_target_off], { 'display': 'block' });
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }


                if (!enabledValid) {
                    return
                }

                if (_data_activity.activity_typo.split('_')[0] === "QCU") {
                    $('.option').removeClass('selected');

                }

                if ($(this).find('.option_icon').find('#selectRight').css('display') != 'none') {
                    return
                }

                if (!$(this).parent().hasClass('selected')) {
                    $(this).parent().addClass('selected');
                    $(this).find('.icon-check_box_02').css({ 'display': 'inline-block' })
                    $('.click').length === 1 ? $(this).parent().addClass('blue') : null



                } else {
                    $(this).parent().removeClass('selected');
                    $(this).find('.icon-check_box_02').css({ 'display': 'none' })
                    $('.click').length === 1 ? $(this).parent().removeClass('blue') : null
                }


            });
        }

    }

    function createContainerBox() {
        var template_container_box = '<div class="options" id="options"><div class="options_content"  id="options_content"></div></div>';
        dom._answer_content.append(template_container_box)
    }

    function createBox(txt) {

        var _audio = 0;
        // audio or texte or image
        if ((/\.(?=gif|jpeg|jpg|png)/gi).test(txt)) {
            var func = createBoxImage
        } else if ((/\.(?=mp3|ogg)/gi).test(txt)) {
            var func = createBoxAudio;
            _audio = 1;

        } else {
            var func = createBoxText
        }

        var template_box = '<div id=" ' + exercice.Utils.generateUUID() + '" class="option disabled false mmc">' +
            '<div class="status_icon">' +
            '<span id="correct" class="icon-right_icon"></span>' +
            '<span id="wrong" class="icon-wrong_icon"></span></div>' +
            '<div class="option_body">' +
            '<div class="option_icon">' +
            '<span id="select" class="icon-check_box_02"><svg id="icon-check_box_04" data-name="icon-check_box_04" xmlns="http://www.w3.org/2000/svg" width="24.2" height="20" viewBox="0 0 24.2 20"><defs><style>.cls-H-1{fill:none;stroke:#59affd;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-H-1" x1="7.76" y1="16.45" x2="22.7" y2="1.5"/><line class="cls-H-1" x1="7.41" y1="16.45" x2="1.5" y2="10.53"/></svg></span></span>' +
            '<span id="selectWrong" class="icon-check_box_03"><svg id="icon-check_box_03" data-name="icon-check_box_03" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-1" x1="1.5" y1="16.45" x2="16.45" y2="1.5"/><line class="cls-1" x1="16.45" y1="16.45" x2="1.5" y2="1.5"/></svg></span>' +
            '<span id="selectRight" class="icon-check_box_04"><svg id="icon-check_box_04" data-name="icon-check_box_04" xmlns="http://www.w3.org/2000/svg" width="24.2" height="20" viewBox="0 0 24.2 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-1" x1="7.76" y1="16.45" x2="22.7" y2="1.5"/><line class="cls-1" x1="7.41" y1="16.45" x2="1.5" y2="10.53"/></svg></span>' +
            '<span id="unSelect" class="icon-check_box_01"><svg id="icon-check_box_04" data-name="icon-check_box_04" xmlns="http://www.w3.org/2000/svg" width="24.2" height="20" viewBox="0 0 24.2 20"><defs><style>.cls-1{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><line class="cls-1" x1="7.76" y1="16.45" x2="22.7" y2="1.5"/><line class="cls-1" x1="7.41" y1="16.45" x2="1.5" y2="10.53"/></svg></span>' +
            '</div>' +
            '<div class="option_content_wrap">' +
            '<div class="option_content">' + func(txt) + '</div>' +
            '</div> ' +
            '</div>' +
            '</div>';

        $('.options_content').append(template_box);
        if (_audio) {
            $('.option_body').addClass('dim_fixed');
            $('.option_content_wrap').addClass('dim_fixed');

        } else {
            $('.option_content_wrap').removeClass('dim_fixed');
        }
        $(".small_image").each(function (i) {
            if ($('.click').length) {
                createThumbnail($(this), 180, 220)
            } else {
                createThumbnail($(this), 120, 120)
            }



        })


    }

    function createBoxAudio(data) {
        var template_audio = '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="mediaPlayer soundButton soundButtonType mouseDown" style="">' +
            '<div id="gen_id_16_content" class="soundButton_content">' +
            '<span class="calque_sound off"><svg xmlns="http://www.w3.org/2000/svg"  class="calque_sound_off" id="calque_sound_off" data-name="calque_sound_off" width="27" height="18.27" viewBox="0 0 26.89 18.27"><defs><style>.cls-10{fill:#59affd;}.cls-20{fill:none;stroke:#59affd;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><title></title><path class="cls-10" d="M359.38,82L355,85.24h-4a1.2,1.2,0,0,0-1.2,1.2V94.8A1.2,1.2,0,0,0,351,96h4l4.38,3.28a1.19,1.19,0,0,0,1.92-1V82.92a1.2,1.2,0,0,0-1.92-1" transform="translate(-349.8 -81.48)"/><path class="cls-20" d="M372,98.26A10.8,10.8,0,0,0,372,83" transform="translate(-349.8 -81.48)"/><path class="cls-20" d="M366.8,95.89a7.45,7.45,0,0,0,0-10.54" transform="translate(-349.8 -81.48)"/></svg></span>' +
            '<span class="calque_sound on"><svg id="calque_sound_on" class="calque_sound_on" data-name="Calque 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="27" height="17.81" viewBox="0 0 26.81 17.81"><defs><style>.cls-11,.cls-41{fill:none;}.cls-21{clip-path:url(#clip-path);}.cls-31{fill:#59affd;}.cls-41{stroke:#59affd;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style><clipPath id="clip-path" transform="translate(-350.8 -81.47)"><rect class="cls-11" x="341.8" y="68.24" width="44" height="44"/></clipPath></defs><title></title><g class="cls-21"><path class="cls-31" d="M360.38,81.72L356,85h-4a1.2,1.2,0,0,0-1.2,1.2v8.36a1.2,1.2,0,0,0,1.2,1.2h4L360.38,99a1.19,1.19,0,0,0,1.92-1V82.68a1.2,1.2,0,0,0-1.92-1" transform="translate(-350.8 -81.47)"/></g><line class="cls-41" x1="16" y1="13.56" x2="25.31" y2="4.25"/><line class="cls-41" x1="25.31" y1="13.56" x2="16" y2="4.25"/></svg>' +
            '<audio src="uploads/' + data + '" id="gen_id_' + exercice.Utils.generateUUID() + '_soundButtonMedia" preload="none">' +
            '</audio>' +
            '</div>' +
            '</div>';
        return template_audio;
    }

    function createBoxText(data) {
        var template_txt = '<div class="textViewer">' + exercice.Utils.doReplace(data) + '</div>';
        return template_txt
    }

    function createBoxImage(data) {
        var template_img
        if ($('.click').length) {
            template_img = '<div class="imageSmallViewer" id="gen_id_' + exercice.Utils.generateUUID() + '" style="display: block;">' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="imageViewer_content">' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_imageContainer" class="imageContainer" style="width:180px;height:220px">' +
                '<div class="image_small_container"><img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="small_image" src="uploads/' + data + '" style="" alt="Image"></div> ' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="loading"></div>' +
                '</div>' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="zoomButton">' +
                '</div>' +
                '</div>' +
                '</div>';
        } else {
            template_img = '<div class="imageSmallViewer" id="gen_id_' + exercice.Utils.generateUUID() + '" style="display: block;">' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="imageViewer_content">' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '_imageContainer" class="imageContainer" style="width:120px;height:120px">' +
                '<div class="image_small_container"><img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="small_image" src="uploads/' + data + '" style="" alt="Image"></div> ' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="loading"></div>' +
                '</div>' +
                '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="zoomButton">' +
                '</div>' +
                '</div>' +
                '</div>';
        }




        return template_img
    }


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// LEGEND SYSTEM //////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function createTemplateLegend(data) {
        _listOfWordsCorrects = [];
        _solutions_qc = [];
        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        // image
        dom._imageViewer_content.html('');
        //addImage(data, 600, 300, data.activity_image_position);
        dom._imageViewer.css({ 'visibility': 'hidden' });
        // Area
        var TEMPLATE = '<div id="' + exercice.Utils.generateUUID() + '" class="clozeArea"><div id="clozeArea_content"></div></div>';
        dom._answer_content.append(TEMPLATE);
        dom._clozeArea = $(".clozeArea");
        dom._clozeArea_content = $("#clozeArea_content");
        dom._clozeArea_content.append(generateTextViewer());
        $('#clozeArea_content .textViewer_content').html(generateTextViewerParagraph());

        var t = data.activity_data;
        try {
            parsedData = JSON.parse(t)

        } catch (e) {
            parsedData = t
        }

        $('#clozeArea_content .textViewerParagraph').append('<div id="img_box_legend" style=" width: ' + 600 + 'px; height: ' + 400 + 'px;overflow: hidden; position: relative;"></div>')
        $('#clozeArea_content .textViewerParagraph').append('<div id="container_plots" style=" width: ' + 600 + 'px; height: ' + 400 + 'px;overflow: hidden; position: absolute;top:0;left:0"></div>');
        //data.activity_image
        $("#img_box_legend").css({
            'background-image': 'url(' + data.activity_image + ')',
            'background-size': 'contain',
            'background-position': '50% 50%',
            'background-repeat': 'no-repeat'
        });


        var img = new Image;
        var imgW
        var imgH
        var newW, newH;
        img.onload = function () {
            imgW = img.width;
            imgH = img.height;
            if (imgW > imgH) {
                newW = $('#img_box_legend').width(); //100;
                newH = imgH / imgW * newW;
            } else {
                newH = $('#img_box_legend').height(); //100
                newW = imgW / imgH * newH;
            }
            if (newH < 395) {
                if($('.clozeArea').length)exercice.Utils.setStyle([$('.clozeArea')], { 'margin-top': '-20px' });

            }
        };

        img.src = data.activity_image;
        var _stageId = exercice.Utils.generateUUID();
        $('#clozeArea_content .textViewerParagraph').append('<div id="container_' + _stageId + '" style="position: absolute;top:0;left:0;width : 600px;height:400px;" ></div>');
        dom._layer_kinetic = new Kinetic.Layer({
            clearBeforeDraw: true
        });
        document.getElementById('wrapper-content-exo').scrollTop = 0;
        createLabels(parsedData);
        dom._stage = new Kinetic.Stage({
            id: 'stage' + _stageId,
            container: 'container_' + _stageId,
            width: 600,
            height: 400,
            listening: true,
            visible: true,
            draggable: false
        });

        var background = new Kinetic.Rect({
            x: 0,
            y: 0,
            width: dom._stage.getWidth(),
            height: dom._stage.getHeight(),
            fill: "transparent"
        });
        dom._layer_kinetic.add(background);
        dom._stage.add(dom._layer_kinetic);
        dom._layer_kinetic.setZIndex(10);

        if (parsedData.content) {
            for (var y = 0; y < parsedData.content.length; y++) {

                _listOfWordsCorrects.push(parsedData.content[y].answer);
                _goodAnswers.push(parsedData.content[y].answer);

            }
            for (var y = 0; y < parsedData.lines.length; y++) {
                var pts = parsedData.lines[y].points;
                _line = new Kinetic.Line({
                    points: [pts[0] + 20, pts[1] - 8, pts[2] + 20, pts[3]],
                    strokeWidth: 1,
                    stroke: "#808080",
                    lineCap: 'round',
                    lineJoin: 'round'
                });
                dom._layer_kinetic.add(_line);
                _line.target_1 = parsedData.lines[y].target_1;
                _line.target_2 = parsedData.lines[y].target_2;



            }

            dom._layer_kinetic.drawScene();
            $(".textViewer").css({ 'padding': '0' });
            _solutions_qc = shuffleArray(_listOfWordsCorrects);
            createBoxForDragElement();
            createEventsForCompleteDD();
            createAnchors(parsedData);
            dom._answer_content.css({ 'text-align': 'left' });
        }




    }

    function createAnchors(data) {
        if (data.markers) {
            if (data.markers.length) {
                for (var i = 0; i < data.markers.length; i++) {
                    var pos = {
                        posX: data.markers[i].posX,
                        posY: data.markers[i].posY
                    };
                    $('#container_plots').append(createPlot(pos));

                }
            }
        }

    }

    function createLabels(data) {
        if (data.content) {
            if (data.content.length) {
                for (var i = 0; i < data.content.length; i++) {
                    var pos = {
                        posX: data.content[i].position.posX,//+14 ,//- 11,
                        posY: data.content[i].position.posY//+10 //- 200 - 100 + data.delta
                    };

                    $('#container_plots').append(addLabels(pos))

                }
            }
        }


    }

    function addLabels(pos) {
        var tpl = '<div class="subAnswer 0 custom-alignment drop-target " id="gen_id_' + exercice.Utils.generateUUID() + '" style="position: absolute; left: ' + pos["posX"] + 'px;top: ' + pos["posY"] + 'px;width: 164px; height: 42px;">			' +
            '<div class="subAnswer_content_wrap " id="gen_id_' + exercice.Utils.generateUUID() + '_content_wrap" style="width: 164px; height: 42px;">									' +
            '<div class="status_icon">					' +
            '<span id="correct" class="icon-right_icon"></span>' +
            '<span id="wrong" class="icon-wrong_icon"></span>' +
            '</div>				' +
            '<div class="subAnswer_content shadow" id="gen_id_' + exercice.Utils.generateUUID() + '_content" style="width: 164px; height: 42px;">' +
            '<div class="textViewer textViewerStyle ltr compact" id="gen_id_' + exercice.Utils.generateUUID() + '" style="direction: ltr; text-align: left;height: 40px; font-size: 18px; min-width: 98px; display: none;line-height: 30px;" mathfield="true">            ' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="textViewer_content"><div>' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="textViewerParagraph">' +
            '<span contenteditable="false" class="normal"></span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            ' </div>' +
            '</div>											' +
            '</div>	';

        return tpl;
    }

    function createPlot(pos) {

        var tpl = '<div style="position: absolute; left: ' + pos["posX"] + 'px; margin: 0px; padding: 0px; top: ' + pos["posY"] + 'px; opacity: 1;" id="' + exercice.Utils.generateUUID() + '" class="link_anchor small placed legend">' +
            '<span id="correct" class="icon-right_icon"></span>' +
            '<span id="incorrect" class="icon-wrong_icon" style="visibility: visible;"></span>' +
            '</div>';

        return tpl

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// CLASSER SYSTEM /////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function createTemplateClasser(data, type) {

        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position, type);


        var TEMPLATE = '<div id="' + exercice.Utils.generateUUID() + '" class="clozeArea" id="clozeArea"><div id="clozeArea_content"></div></div>';
        dom._answer_content.append(TEMPLATE);
        dom._clozeArea = $(".clozeArea");
        dom._clozeArea_content = $("#clozeArea_content");




        _listOfWordsCorrects = []
        _solutions_qc = [];




        //_solutions_qc = shuffleArray(_listOfWordsCorrects);
        var t = data.activity_data;
        var parsedData;
        _words = {};
        try {
            parsedData = JSON.parse(t);

        } catch (e) {
            parsedData = t;
            //dom._clozeArea_content_textViewerParagraph.append(exercice.Utils.doReplace(t));
        }
        if (parsedData[0]) {
            var _drag_words = parsedData[0].words;
            var _drop_header = parsedData[0].items; //array


            dom._clozeArea_content.append('<div class="columns__container"></div>')
            for (var i = 0; i < _drop_header.length; i++) {
                $('.columns__container').append(
                    generateTemplateColumn(_drop_header[i]))
            }

            try {
                _words = JSON.parse(_drag_words);

            } catch (e) {
                _words = _drag_words;

            }
            var _temp_solutions_qc = []
            for (var u = 0; u < _.size(_words); u++) {
                for (var v = 0; v < _words["col" + Number(u + 1)].length; v++) {
                    _temp_solutions_qc.push(_words["col" + Number(u + 1)][v])
                }
            }

            if (_.size(_words) === 3) {

                $('.column__container').css({
                    "margin-left": "5px",
                    "margin-right": "5px",
                    "width": "190px",


                })
                $('.imageContainer').css({
                    "width": "190px"
                })
            } else if (_.size(_words) >= 4) {
                $('.column__container').css({
                    "margin-left": "2px",
                    "margin-right": "2px",
                    "width": "150px",


                })
                /* $('.columns__container').css ({
                        
                         "width": dom._answer_content.width()-340+"px"
                 })*/
                $('.imageContainer').css({
                    "width": "150px"
                })
            }

            else {
                $('.column__container').css({
                    "margin-left": "20px",
                    "margin-right": "20px",
                    "width": "250px"

                })
                $('.imageContainer').css({
                    "width": "250px"
                })
            }


            _solutions_qc = shuffleArray(_temp_solutions_qc);//mélange
            _listOfWordsCorrects = _solutions_qc


            createEventsForClass();
            createBoxForDragElement();
            createEventsForCompleteDD();

            if ($('body').hasClass('preview')) {
                var wrap = $("#content-exo");
                var _bank;
                var _top = 163;
                if ($("body").hasClass('primaire')) {
                    _top = 240
                } else {
                    _top = 163;
                }
                wrap.on("scroll", function (e) {
                    _bank = $(".bank");


                    if (Math.floor($('.answer').offset().top) < _top) {
                        _bank.addClass("fix-search");
                        _bank.offset({
                            top: _top
                        })

                    } else {
                        _bank.removeClass("fix-search");
                        _bank.css({
                            top: '0px'
                        })
                    }

                });
            }
        }






    }

    function createEventsForClass() {
        var currentPlayed;
        var curPlaying = 0;
        if ($('.textViewer_content').length) {
            $('.textViewer_content').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                e.stopPropagation();
                if (e.target.className === "soundButton_content" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown playing" || e.target.className === "calque_sound on" || e.target.className === "calque_sound off") {
                    var mediaplayer = $(this).find('.mediaPlayer');

                    mediaManager.setMedia(document.getElementById($(this).find('.soundButton_content').find('audio').attr('id')), true);
                    mediaManager.load();
                    if (currentPlayed === document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))) {


                    } else {
                        $('.mediaPlayer').removeClass('playing');
                        $('.mediaPlayer').find('.off').show();
                        $('.mediaPlayer').find('.on').hide();
                        if (currentPlayed) {
                            if (currentPlayed.readyState > 0) {
                                currentPlayed.currentTime = 0;
                            }
                        }

                        currentPlayed = document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))

                    }

                    if (mediaplayer.hasClass('playing')) {
                        mediaplayer.removeClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.pause();
                        // exercice.Utils.setStyle([_target_off], { 'display': 'block' });
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });

                    } else {
                        mediaplayer.addClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.play();
                        exercice.Utils.setStyle([_target_off], { 'display': 'none' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'flex' });
                        // exercice.Utils.setStyle([_target_on], { 'display': 'block' });


                    }


                    mediaManager.ended(function () {
                        if (document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).readyState > 0) {
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).pause();  // make sure it stopped.
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).currentTime = 0;


                        }
                        var _target_off = mediaplayer.find('.off');
                        var _target_on = mediaplayer.find('.on');
                        // exercice.Utils.setStyle([_target_off], { 'display': 'block' });
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }



                if (!enabledValid) {
                    return
                }


            });
        }

        if ($('.option_body').length) {
            $('.option_body').on(exercice.Utils.appEvents().globalEvents.mousedown, function (e) {
                e.stopPropagation();

                if (e.target.className === "soundButton_content" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown" || e.target.className === "mediaPlayer soundButton soundButtonType mouseDown playing" || e.target.className === "calque_sound on" || e.target.className === "calque_sound off") {
                    var mediaplayer = $(this).find('.mediaPlayer');



                    mediaManager.setMedia(document.getElementById($(this).find('.soundButton_content').find('audio').attr('id')), true);
                    mediaManager.load();
                    if (currentPlayed === document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))) {


                    } else {
                        $('.mediaPlayer').removeClass('playing');
                        $('.mediaPlayer').find('.off').show();
                        $('.mediaPlayer').find('.on').hide();
                        if (currentPlayed) {
                            if (currentPlayed.readyState > 0) {
                                currentPlayed.currentTime = 0;
                            }
                        }

                        currentPlayed = document.getElementById($(this).find('.soundButton_content').find('audio').attr('id'))

                    }

                    if (mediaplayer.hasClass('playing')) {
                        mediaplayer.removeClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.pause();

                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });

                    } else {
                        mediaplayer.addClass('playing');
                        var _target_off = $(this).find('.off');
                        var _target_on = $(this).find('.on');
                        mediaManager.play();
                        exercice.Utils.setStyle([_target_off], { 'display': 'none' });

                        exercice.Utils.setStyle([_target_on], { 'display': 'flex' });


                    }


                    mediaManager.ended(function () {

                        if (document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).readyState > 0) {
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).pause();  // make sure it stopped.
                            document.getElementById(mediaplayer.find('.soundButton_content').find('audio').attr('id')).currentTime = 0;


                        }
                        var _target_off = mediaplayer.find('.off');
                        var _target_on = mediaplayer.find('.on');
                        exercice.Utils.setStyle([_target_off], { 'display': 'flex' });
                        exercice.Utils.setStyle([_target_on], { 'display': 'none' });
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }

            })
        }
    }

    function generateTemplateColumn(type) {
        w = 'auto';
        h = '30px';
        var clas = "";

        if (w) {
            _w = w;
        }
        if (h) {
            _h = h;
        } else {
            _h = "auto"
        }

        if ((/\.(?=gif|jpeg|jpg|png)/gi).test(type)) {
            var func = createColumnImage;
            clas = "boxImage";
            _h = '120px';
        } else if ((/\.(?=mp3|ogg)/gi).test(type)) {
            var func = createColumnAudio;
            clas = "boxAudio";
            _h = 'auto';
        } else {
            var func = createColumnText;
            clas = "boxText";
            _h = "auto"
        }

        return "<div class='textViewer " + clas + "' id='" + exercice.Utils.generateUUID() + "' \
                  style='width:" + _w + ";height:" + _h + ";'>\
                <div id='" + exercice.Utils.generateUUID() + "_content' class='textViewer_content'>" + func(type) + "</div>\
            </div>";






    }

    function createColumnImage(data) {
        var TEMPLATE_COLUMN = '<div class="column__container"><div class="column__content">' +
            '<div class="column__header">' +
            '<div class="imageSmallViewer" id="gen_id_' + exercice.Utils.generateUUID() + '" style="display: block;">' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '_content" class="imageViewer_content">' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '_imageContainer" class="imageContainer" style="width:250px;height:60px">' +
            '<div class="image_small_container"><img id="gen_id_' + exercice.Utils.generateUUID() + '_img" class="small_image" src="uploads/' + data + '" style="" alt="Image"></div> ' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="loading"></div>' +
            '</div>' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="zoomButton">' +
            '</div>' +
            '</div>' +
            '</div>'
            + '</div>' +
            '<div class="drop-target"></div>' +
            '</div></div>'
        return TEMPLATE_COLUMN
    }
    function createColumnAudio(data) {
        var TEMPLATE_COLUMN = '<div class="column__container"><div class="column__content">' +
            '<div class="column__header">' +
            '<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="mediaPlayer soundButton soundButtonType mouseDown" style="">' +
            '<div id="gen_id_16_content" class="soundButton_content">' +
            '<span class="calque_sound off"><svg xmlns="http://www.w3.org/2000/svg"  class="calque_sound_off" id="calque_sound_off" data-name="calque_sound_off" width="27" height="18.27" viewBox="0 0 26.89 18.27"><defs><style>.cls-10{fill:#59affd;}.cls-20{fill:none;stroke:#59affd;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style></defs><title></title><path class="cls-10" d="M359.38,82L355,85.24h-4a1.2,1.2,0,0,0-1.2,1.2V94.8A1.2,1.2,0,0,0,351,96h4l4.38,3.28a1.19,1.19,0,0,0,1.92-1V82.92a1.2,1.2,0,0,0-1.92-1" transform="translate(-349.8 -81.48)"/><path class="cls-20" d="M372,98.26A10.8,10.8,0,0,0,372,83" transform="translate(-349.8 -81.48)"/><path class="cls-20" d="M366.8,95.89a7.45,7.45,0,0,0,0-10.54" transform="translate(-349.8 -81.48)"/></svg></span>' +
            '<span class="calque_sound on"><svg id="calque_sound_on" class="calque_sound_on" data-name="Calque 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="27" height="17.81" viewBox="0 0 26.81 17.81"><defs><style>.cls-11,.cls-41{fill:none;}.cls-21{clip-path:url(#clip-path);}.cls-31{fill:#59affd;}.cls-41{stroke:#59affd;stroke-linecap:round;stroke-linejoin:round;stroke-width:3px;}</style><clipPath id="clip-path" transform="translate(-350.8 -81.47)"><rect class="cls-11" x="341.8" y="68.24" width="44" height="44"/></clipPath></defs><title></title><g class="cls-21"><path class="cls-31" d="M360.38,81.72L356,85h-4a1.2,1.2,0,0,0-1.2,1.2v8.36a1.2,1.2,0,0,0,1.2,1.2h4L360.38,99a1.19,1.19,0,0,0,1.92-1V82.68a1.2,1.2,0,0,0-1.92-1" transform="translate(-350.8 -81.47)"/></g><line class="cls-41" x1="16" y1="13.56" x2="25.31" y2="4.25"/><line class="cls-41" x1="25.31" y1="13.56" x2="16" y2="4.25"/></svg>' +
            '<audio src="uploads/' + data + '" id="gen_id_' + exercice.Utils.generateUUID() + '_soundButtonMedia" preload="none">' +
            '</audio>' +
            '</div>' +
            '</div></div>' +
            '<div class="drop-target"></div>' +
            '</div></div>'
        return TEMPLATE_COLUMN
    }
    function createColumnText(data) {
        var TEMPLATE_COLUMN = '<div class="column__container"><div class="column__content">' +
            '<div class="column__header">' + data + '</div>' +
            '<div class="drop-target"></div>' +
            '</div></div>'
        return TEMPLATE_COLUMN
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// ORDER SYSTEM ///////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function createTemplateOrder(data, type) {

        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(exercice.Utils.doReplace(txt));
        createAudioConsigne(data);
        createAudioTTSConsigne(data);
        // image
        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position, type);

        // Area
        var TEMPLATE = '<div id="' + exercice.Utils.generateUUID() + '" class="orderArea"><div id="orderArea_content"></div></div>';
        dom._answer_content.append(TEMPLATE);
        dom._clozeArea = $(".orderArea");
        dom._clozeArea_content = $("#orderArea_content");
        dom._clozeArea_content.append('<ul id="list-1"></ul>')


        var t = data.activity_data;
        try {
            parsedData = JSON.parse(t)

        } catch (e) {
            parsedData = t
        }

        _solutions_qc = [];

        var _solutions_order = [];
        var _listOfLettersCorrects = [];
        var myObj;

        if (parsedData.length) {
            myObj = parsedData.split('&amp;')



            $.map(myObj, function (value, index) {
                _solutions_qc.push(value.trim().replace('<p>', '').replace('</p>', ''))
                _solutions_order.push(value.trim().replace('<p>', '').replace('</p>', ''))
            });

            _listOfWordsCorrects = _solutions_order;
            for (var i = _listOfWordsCorrects.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = _listOfWordsCorrects[i];
                _listOfWordsCorrects[i] = _listOfWordsCorrects[j];
                _listOfWordsCorrects[j] = temp;
            }
        }






        for (var i = 0; i < _listOfWordsCorrects.length; i++) {

            if (_listOfWordsCorrects[i].replace('<br>', "") != "") {
                $('#list-1').append('<li class="letter_box" style=" min-width:100px;width: ' + 'auto' + '; height: ' + 100 + 'px;overflow: hidden; position: relative;"></li>')
                var s = '<span>' + _listOfWordsCorrects[i] + '<span>'
                var htmlObj = $(s);
                $('.letter_box').eq(i).html(htmlObj);

            } else {
                $("#list-1").hide();
            }

            $("#list-1").sortable({
                connectWith: "#list-2",

            })
                .disableSelection();



            if (type === "letter") {
                $(".letter_box").css({
                    'width': 'auto',
                    'height': '100px',
                    'padding': '10px',

                })





            }
            else {
                if ($('body').hasClass('primaire')) {
                    $(".letter_box").css({
                        'width': '100%',
                        'height': '80px',
                        'font-size': '32px',
                        'padding': '10px',
                        'margin-left': 0,
                        'margin-right': 0,
                        'margin-top': '10px',
                        'margin-bottom': '10px'
                    })
                } else {
                    $(".letter_box").css({
                        'width': '100%',
                        'height': '50px',
                        'font-size': '22px',
                        'padding': '10px',
                        'margin-left': 0,
                        'margin-right': 0,
                        'margin-top': '5px',
                        'margin-bottom': '5px'
                    })
                }


            }


        }

        var _total = 0;
        if (type === "letter") {
            for (var t = 0; t < _listOfWordsCorrects.length; t++) {
                _total += ($(".letter_box").eq(t).width() + 34);

            }

            $("#list-1").css({ "width": (_total + 23) + "px" })
        } else {
            for (var t = 0; t < _listOfWordsCorrects.length; t++) {
                _total += ($(".letter_box").eq(t).height() + 44);

            }

            if ($('body').hasClass('primaire')) {
                $("#list-1").css({ "height": (_total + 23) + "px" })
            } else {
                $("#list-1").css({ "height": (_total) + "px" })
            }



        }


        $(".letter_box").on(exercice.Utils.appEvents().globalEvents.mousedown, function () {

            if (enabledValid) $(this).removeClass("green red")
        })





    }



    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// MANAGE ACTIVITIES (INIT - CHANGE - NEXT - PREV - TRY AGAIN)/////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function deleteActivity() {
        emptyContent();

        manageActivities(_data_activity);


    }

    function manageActivities(data) {

        killAllSounds();
        _positionAnswer = [];
        _positionAnswerLink = {}
        _casse = "yes";
        $("#content-exo").show();
        dom._validation.css({ 'visibility': 'visible' });
        dom._correction.css({ 'visibility': 'hidden' });
        dom._attempt.css({ 'visibility': 'visible' });
        dom._tryAgain.css({ 'visibility': 'hidden' });
        dom._answer.css({ 'visibility': 'hidden' });


        var val2 = data.activity_typo;

        var _type = "";
        var _adapt = "";

        if (val2.split("_")[0] === "QCM") {
            _type = val2.split("_")[1];
            val2 = "QCM";



        } else if (val2.split("_")[0] === "Cliquer") {
            _type = val2.split("_")[1];
            val2 = "QCM";
            _adapt = "click " + _type.toLowerCase()

        } else if (val2.split("_")[0] === "QCU") {
            _type = val2.split("_")[1];
            val2 = "QCU";


        } else if (val2.split("_")[0] === "Compléter") {
            _type = val2.split("_")[1];
            val2 = val2;


        }
        else if (val2.split("_")[0] === "Relier") {
            _type = val2.split("_")[1];
            val2 = "Relier";

        }
        else if (val2.split("_")[0] === "Légender") {
            _type = val2.split("_")[1];
            val2 = val2;

        }
        else if (val2.split("_")[0] === "Ordonner") {
            _type = val2.split("_")[1];
            val2 = val2;

        }
        else if (val2.split("_")[0] === "Classer") {
            _type = val2.split("_")[1];
            val2 = val2;

        }
        dom._answer_content.removeClass('multi ccs ccl qc linking lnp lp click classer image texte audio order classer_image classer_audio classer_texte');
        dom._answer.removeClass('multi ccs ccl qc linking lnp lp click image classer texte audio order');


        switch (val2) {
            case "QCU":
                dom._answer.addClass('qc');
                dom._answer_content.addClass('qc');
                createTemplateQC(data, 'qc');
                createExoQC(data);
                createEventForExoQC();

                break;
            case "QCM":
                dom._answer.addClass('qc');
                dom._answer.addClass('multi');
                dom._answer_content.addClass('qc ' + _adapt);
                createTemplateQC(data, 'qc');
                createExoQC(data);
                createEventForExoQC();

                break;
            case "Relier":
                dom._answer.addClass('linking');
                dom._answer_content.addClass('linking');
                createTemplateLink(data, 'linking');
                createTemplateExo(data, 'linking');
                createEventForExoQC();
                updatePositionBlock("linking", data);
                break;
            case "Classer_MOT":
                dom._answer.addClass('classer');
                dom._answer_content.addClass('classer_texte');
                createTemplateClasser(data, 'texte');
                updatePositionBlock("classer");
                dom._answer.css({ 'visibility': 'visible' });
                break;
            case "Classer_AUDIO":
                dom._answer.addClass('classer');
                dom._answer_content.addClass('classer_audio');
                createTemplateClasser(data, 'audio');
                updatePositionBlock("classer");
                dom._answer.css({ 'visibility': 'visible' });
                break;
            case "Classer_IMAGE":
                dom._answer.addClass('classer');
                dom._answer_content.addClass('classer_image');
                createTemplateClasser(data, 'image');
                updatePositionBlock("classer");
                dom._answer.css({ 'visibility': 'visible' });
                break;

            case "Ordonner_MOT":
                dom._answer.addClass('order');
                dom._answer_content.addClass('order');
                createTemplateOrder(data, 'letter');
                updatePositionBlock("order",data);
                dom._answer.css({ 'visibility': 'visible' });
                break;
            case "Ordonner_PHRASE":
                dom._answer.addClass('order');
                dom._answer_content.addClass('order');
                createTemplateOrder(data, 'texte');
                updatePositionBlock("order",data);
                dom._answer.css({ 'visibility': 'visible' });
                break;
            case "Compléter_LABEL":
                dom._answer.addClass('ccl');
                dom._answer_content.addClass('ccl');
                createTemplateCompleteDD(data, 'ccl');
                break;
            case "Compléter_SAISIE":
                dom._answer.addClass('ccs');
                dom._answer_content.addClass('ccs');
                createTemplateComplete(data, "ccs");
                break;

            case "Légender_POINTEUR":
                dom._answer.addClass('lp');
                dom._answer_content.addClass('lp');
                createTemplateLegend(data, 'lp');
                dom._imageViewer.hide();
                updatePositionBlock("lp", data);
                dom._answer.css({ 'visibility': 'visible' });

                break;
            case "Légender_NOPOINTEUR":
                dom._answer.addClass('lnp');
                dom._answer_content.addClass('lnp');
                createTemplateLegend(data, 'lp');
                dom._imageViewer.hide();
                updatePositionBlock("lnp", data);
                dom._answer.css({ 'visibility': 'visible' });
                break;
            default:
                break
        }

        cloneImage();
        $('img').load(function () {
            $(this).parent().parent().find('.loading').remove();
        });


    }

    function cloneImage() {
        var $img = $(".imageViewer-content").children("img").clone();
        $(".imageViewer-content-small").empty().append($img);
    }

    function tryAgainActivity() {
        _modePlayer = "noCorrection";
        dom._tryAgain.css({ 'visibility': 'hidden' });
        dom._validation.css({ 'visibility': 'visible' });
        if (dom._bilan.css('display') != 'none') {
            dom._bilan.css({ 'display': 'none' });
            dom._attempt.css({ 'visibility': 'hidden' });
            $(".road").css({ 'visibility': 'visible' });
            dom._next.css({
                'visibility': 'visible'
            });
            emptyContent();
            currentActivity = 0;
            enabledValid = 1;
            _active_activity = 0;
            _end = 0;
            _points = 0;
            _try = 1;
            _score = {};
            if ($('body').hasClass("primaire")) {
                $("#student-nav").css({
                    'visibility': 'visible'
                });
                $(".wrap-progress-bar").hide();
            } else {
                $("#student-nav").css({
                    'visibility': 'hidden'
                });
                $(".wrap-progress-bar").show();
            }


            if (_mode === "multiple") {
                _data_activity = _data_total_activities.activities[_active_activity];

            }
            _can_click = 0;
            if (Number(_active_activity) === 0) {
                dom._prev.css({ 'visibility': 'hidden' });
            }

            $("#list-activity li").removeClass('selectStu');
            $("#list-activity li").first().addClass('selectStu');
            updateProgression(1);
            updateAttempt(1);
            manageActivities(_data_activity);
            dom._validation.css({ 'visibility': 'visible' });
            // dom._validation.show()
            dom._attempt.css({ 'visibility': 'visible' });
            // dom._attempt.show()
            return;
        }

        if (enabledValid) {
            return
        }

        dom._balloon_popup.css({ 'visibility': 'hidden' });
        dom._correction.css({ 'visibility': 'hidden' });
        dom._attempt.css({ 'visibility': 'visible' });
        if (_try <= Number(_data_serie.serie_try) || Number(_data_serie.serie_try) === 0) {

            // end of exo rebegin
            if (_try === Number(_data_serie.serie_try)) {
                _try = 0;

            }

            if (!_try) {
                if (_points) {
                    _points = 0;
                }
                deleteActivity();
            } else {
                // link
                $(".link_anchor").each(function (i) {
                    $(this).removeClass('selected').removeClass('wrong');
                    $(this).find('#incorrect').hide();


                });
                if (_lines.length) {
                    deleteInCorrectLines();
                }


                // drag and drop or legend
                if (dom._clozeArea_content) {
                    if (dom._clozeArea_content.find('.subAnswer').find('.textViewer').length) {
                        dom._clozeArea_content.find('.subAnswer').find('.textViewer').each(function (i) {
                            if ($(this).parent().parent().parent().hasAnyClass('correct')) {

                                if ($(this).text() != "") {
                                    var t = $(this).find('.textViewerParagraph').html();
                                } else {
                                    var t = "";
                                }
                                $(this).parent().parent().parent().removeClass('occuped wrong');
                                dom._draggable.each(function (i) {

                                    if ($(this).find('.textViewerParagraph').html() === t && _id === $(this).parent().parent().attr('id')) {
                                        $(this).css({
                                            "visibility": "hidden"

                                        });

                                    }

                                });

                            } else if ($(this).parent().parent().parent().hasAnyClass(' wrong')) {
                                if ($(this).text() != "") {
                                    var t = $(this).find('.textViewerParagraph').html();
                                } else {
                                    var t = "";
                                }
                                var _id = $(this).parent().parent().parent().attr('data-id');

                                $(this).parent().parent().parent().removeClass('full wrong up');
                                dom._draggable.each(function (i) {


                                    if ($(this).find('.textViewerParagraph').html() === t && _id === $(this).parent().parent().attr('id') || t === " ") {
                                        $(this).css({
                                            "left": 0,
                                            "top": 0,
                                            "opacity": 1,
                                            "visibility": "visible"

                                        });
                                    }
                                });
                                $(this).html("");

                            }
                        });
                    }
                }

                //order
                if ($(".order").length) {
                    $(".letter_box").each(function (i) {

                        if ($(this).hasClass('red')) {
                            $(this).removeClass("red blue selected");
                        }

                    })
                }

                // classer
                if ($(".classer").length) {

                    $(".column__item").each(function (i) {

                        if ($(this).hasClass('red')) {
                            var t = $(this)
                            t.remove();

                            $('.draggable').find('.normal').each(function () {

                                if ($(this).html() === t.find('.normal').html()) {
                                    $(this).parent().parent().parent().parent().parent().css({
                                        "left": 0,
                                        "top": 0,
                                        "opacity": 1,
                                        "visibility": "visible"

                                    });

                                }
                            })
                        }

                    })
                }

                // complete
                if ($(".answer input").length) {
                    $('.subAnswer.texteditor').each(function (i) {
                        if ($(this).hasClass('subAnswer texteditor full compact wrong') || $(this).hasClass('subAnswer texteditor full compact  wrong')) {
                            $(this).removeClass('wrong');
                            $(this).find('input').attr('disabled', false);
                        } else if ($(this).hasClass('subAnswer texteditor full compact correct')) {
                            $(this).find('input').attr('disabled', true);
                        } else {
                            $(this).find('input').attr('disabled', false);
                        }
                    })

                }

                // qcm/qcu

                if ($(".click").length) {
                    $(".option").each(function (i) {

                        if ($(this).hasClass('red')) {
                            $(this).removeClass("red blue selected");
                        }

                    })
                } else {
                    if ($(".option").length) {
                        $(".option").each(function (i) {
                            if ($(this).find('#selectRight').css('display') != 'none') {
                                $(this).find('#selectWrong').hide();
                                $(this).find('#select').hide();
                            } else {
                                $(this).removeClass('selected');
                                $(this).find('#selectWrong').hide();
                                $(this).find('#select').hide();
                            }


                        })
                    }
                }



            }

            enabledValid = 1;
            updateAttempt(_try += 1);
        }

        else {

        }


    }

    function nextActivity() {

        if (_modePlayer === "noCorrection") {

            dom._prev.css({
                'visibility': 'visible'
            });
            dom._balloon_popup.css({
                'visibility': 'hidden'
            });

            dom._myAnswer.css({
                'visibility': 'hidden'
            });

            var _scores = getScore();
            var _scoresLength = _.size(_scores)


            if (Number(_data_serie.serie_bilan) && _active_activity === totalActivities - 1) {



                if (_totalPoints >= 1 && Number(_data_serie.serie_try) === 0) {
                    $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercices sur " + totalActivities);
                } else if (_totalPoints === 0 && Number(_data_serie.serie_try) === 0) {
                    $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercice sur " + totalActivities);
                } else if (Number(_data_serie.serie_try) > 0 && _scoresLength > 0) {
                    createListScore(_scores)
                } else {
                    $('.result_bilan').html("Tu n'as réalisé aucun exercice.");
                }

                _end = 0;
                _totalPoints = 0;
                _score = {};


                if ($('.bank').length) {
                    $('.bank').remove()
                }
                dom._bilan.show();

                $("#content-exo").hide();
                _modePlayer = "correction";
                enabledValid = 0;
                _active_activity++;
                if ($('.bank').length) {
                    $('.bank').remove()
                }
                // if($('body').hasAnyClass('primaire')){
                //  dom._tryAgainPrimaire.css({ 'visibility': 'visible' });
                //  } else {
                dom._tryAgain.css({ 'visibility': 'visible' });
                //  }
                killAllSounds();
                _can_click = 1;
                $("#student-nav").css({ 'visibility': 'visible' });
                $("#list-activity li").removeClass('selectStu');
                $("#list-activity li").last().addClass('selectStu');
                $(".wrap-progress-bar").hide();
                dom._correction.css({ 'visibility': 'hidden' });
                dom._attempt.css({ 'visibility': 'hidden' });


                dom._validation.css({
                    'visibility': 'hidden'
                });
                dom._next.css({
                    'visibility': 'hidden'
                });
                dom._prev.css({
                    'visibility': 'visible'
                });
                return
            } else {

                if (_active_activity === totalActivities - 1) {
                    _end = 1;
                    dom._next.css({
                        'visibility': 'hidden'
                    });
                    return
                }
            }


            updateProgression(1);
            enabledValid = 1;
            _try = 1;
            changeActivity(1);


        } else {

            enabledValid = 0;
            dom._prev.css({ 'visibility': 'visible' });
            dom._bilan.hide();
            dom._correction.addClass('bilan-answer');
            dom._myAnswer.addClass('bilan-answer');
            $(".wrap-progress-bar").hide();
            $("#list-activity li").removeClass('selectStu');

            dom._answer_content.removeClass('linking');
            dom._answer_content.empty();
            if ($('.bank').length) {
                $('.bank').remove()
            }
            _active_activity++;
            _data_activity = _data_total_activities.activities[_active_activity];
            $("#list-activity li").eq(_active_activity).addClass('selectStu')

            if (_active_activity === totalActivities) {
                dom._bilan.show()
                $("#content-exo").hide();
                dom._next.css({
                    'visibility': 'hidden'
                });
                dom._correction.css({
                    'visibility': 'hidden'
                });
                dom._tryAgain.css({
                    'visibility': 'visible'
                });

            } else {
                manageActivities(_data_activity);
                showMyAnswer();
                if ($('.selectStu').hasClass('activity-mi') && _active_activity != totalActivities) {
                    $("#cor").css({ "visibility": "hidden" });
                    dom._myAnswer.css({ 'visibility': 'hidden' });
                }
                else if ($('.selectStu').hasClass('activity-error') && _active_activity != totalActivities) {
                    $("#cor").css({ "visibility": "visible" });
                    dom._myAnswer.css({ 'visibility': 'hidden' });
                } if ($('.selectStu').hasClass('activity-good') && _active_activity != totalActivities) {
                    $("#cor").css({ "visibility": "hidden" });
                    dom._myAnswer.css({ 'visibility': 'hidden' });
                } else if (_active_activity != totalActivities) {
                    $("#cor").css({ "visibility": "visible" });
                    dom._myAnswer.css({ 'visibility': 'hidden' });
                }

            }


            if (Number(_active_activity) === 0) {
                dom._prev.css({
                    'visibility': 'hidden'
                });
            }

            dom._attempt.css({
                'visibility': 'hidden'
            });
            dom._validation.css({
                'visibility': 'hidden'
            });
        }

    }

    function createListScore(score) {
        var str = "";
        var _try_success;
        for (var u = 1; u < totalActivities + 1; u++) {
            if (!score[u]) {
                setScore(u, -1, 0, "")
            }
        }


        _.each(score, function (num, key) {
            $('.result_bilan').html('<div class="container-listScores"><ul id="listScores"></ul></div>');

            if (num.activity_score === -1) {
                _try_success = num.activity_try;
                str += '<li> Activité ' + key + " : " + "non réalisée" + '</li>'

            }
            else if (num.activity_score === 1) {
                _try_success = num.activity_try;
                str += '<li> Activité ' + key + " : " + calculateScore(_try_success, _data_serie.serie_try) + '</li>'

            } else {
                _try_success = Number(_data_serie.serie_try) + 1;
                str += '<li> Activité ' + key + " : " + calculateScore(_try_success, _data_serie.serie_try) + '</li>'

            }

        });

        $('#listScores').append(str);

    }

    function prevActivity() {

        if (_modePlayer === "noCorrection") {
            updateProgression(0);

            enabledValid = 1;
            _try = 1;
            changeActivity(0);
            dom._next.css({
                'visibility': 'visible'
            });
            dom._balloon_popup.css({
                'visibility': 'hidden'
            });
            dom._myAnswer.css({
                'visibility': 'hidden'
            });
            dom._bilan.hide();
            dom._attempt.css({ 'visibility': 'visible' });
        } else {
            enabledValid = 0;
            dom._next.css({ 'visibility': 'visible' });
            dom._bilan.hide();
            dom._correction.addClass('bilan-answer');
            dom._myAnswer.addClass('bilan-answer');
            $(".wrap-progress-bar").hide();
            $("#list-activity li").removeClass('selectStu');

            dom._answer_content.removeClass('linking');
            dom._answer_content.empty();
            if ($('.bank').length) {
                $('.bank').remove()
            }
            _active_activity--;
            _data_activity = _data_total_activities.activities[_active_activity];
            $("#list-activity li").eq(_active_activity).addClass('selectStu')
            manageActivities(_data_activity);
            showMyAnswer();

            if (Number(_active_activity) === 0) {
                dom._prev.css({
                    'visibility': 'hidden'
                });
            }


            if ($('.selectStu').hasClass('activity-mi') && _active_activity != totalActivities) {
                $("#cor").css({ "visibility": "hidden" });
                dom._myAnswer.css({ 'visibility': 'hidden' });
            }
            else if ($('.selectStu').hasClass('activity-error') && _active_activity != totalActivities) {
                $("#cor").css({ "visibility": "visible" });
                dom._myAnswer.css({ 'visibility': 'hidden' });
            } if ($('.selectStu').hasClass('activity-good') && _active_activity != totalActivities) {
                $("#cor").css({ "visibility": "hidden" });
                dom._myAnswer.css({ 'visibility': 'hidden' });
            } else if (_active_activity != totalActivities) {
                $("#cor").css({ "visibility": "visible" });
                dom._myAnswer.css({ 'visibility': 'hidden' });
            }
            dom._attempt.css({
                'visibility': 'hidden'
            });
            dom._validation.css({
                'visibility': 'hidden'
            });

        }



    }

    function changeActivity(dir) {
        dom._answer_content.removeClass('linking');
        dom._answer_content.empty();
        if ($('.bank').length) {
            $('.bank').remove()
        }
        deleteContentArray();
        updateAttempt(_try = 1);
        if (dir) {
            _active_activity++;
            _data_activity = _data_total_activities.activities[_active_activity];
            manageActivities(_data_activity);
        } else {
            _active_activity--;
            updateScore(_active_activity)
            _data_activity = _data_total_activities.activities[_active_activity];
            manageActivities(_data_activity);
        }
        $("#list-activity li").removeClass('selectStu')
        $("#list-activity li").eq(_active_activity).addClass('selectStu');

        if (_active_activity === totalActivities - 1) {

            if (Number(_data_serie.serie_bilan)) {

                dom._next.css({
                    'visibility': 'visible'
                })
            } else {
                dom._next.css({
                    'visibility': 'hidden'
                })
            }


        }
        if (_active_activity === 0) {
            dom._prev.css({
                'visibility': 'hidden'
            })
        }


    }

    function updatePositionBlock(type, data) {


        var bloc_1 = "";
        var bloc_1_content = "";

        var bloc_2 = "";
        var bloc_2_content = "";


        if (type === "qc" && data.activity_typo === "Cliquer_TEXTE" || type === "qc" && data.activity_typo === "Cliquer_IMAGE" || type === "qc" && data.activity_typo === "Cliquer_AUDIO") {




            if ($("#img_box img").length && $("#img_box img").attr('src') != "") {




                if ($('.option').length >= 4 && $('.imageViewer').hasClass('position-right')) {
                    exercice.Utils.setStyle([$(".imageViewer")], { 'width': "20%", 'float': 'right' });
                    exercice.Utils.setStyle([$(".answer")], { 'width': "80%", 'float': 'left' });

                }
                else if ($('.option').length === 3 && $('.imageViewer').hasClass('position-right')) {
                    exercice.Utils.setStyle([$(".imageViewer")], { 'width': "40%", 'float': 'right' });
                    exercice.Utils.setStyle([$(".answer")], { 'width': "60%", 'float': 'left' });
                }
                else if ($('.option').length < 3 && $('.imageViewer').hasClass('position-right')) {
                    exercice.Utils.setStyle([$(".imageViewer")], { 'width': "50%", 'float': 'right' });
                    exercice.Utils.setStyle([$(".answer")], { 'width': "50%", 'float': 'left' });
                } else {
                    if ($(".imageViewer").length) {
                        exercice.Utils.setStyle([$(".imageViewer")], { 'width': "100%" });
                    }
                    exercice.Utils.setStyle([$(".answer")], { 'width': "100%" });
                }
            } else {
                if ($(".imageViewer").length) {
                    exercice.Utils.setStyle([$(".imageViewer")], { 'width': "100%" });
                }

                exercice.Utils.setStyle([$(".answer")], { 'width': "100%" });
                if ($('options_content').length) { exercice.Utils.setStyle([$('options_content')], { 'justify-content: ': "start" }); }

            }

        }


        // Qcm-qcu
        // left : answer + answer_content
        // right imageviewer
        // top imageviewer
        // case with image

        else if (type === "qc") {

            var _display = "";
            bloc_1 = dom._answer;
            bloc_1_content = dom._answer_content;

            bloc_2 = dom._imageViewer;
            bloc_2_content = dom._imageViewer_content;

            var _option = $('.option');
            var _option_content_wrap = $('.option_content_wrap');
            var _totalWidthOfOption_content_wrap = 0;

            _option_content_wrap.each(function (index) {
                _totalWidthOfOption_content_wrap += $(this).width() + 65;
            });

            if (data.activity_image_position === "top" && dom._imageViewer.find('img').length) {
                exercice.Utils.setStyle([bloc_1, bloc_2], { 'width': '100%' });
                if (_totalWidthOfOption_content_wrap > bloc_1_content.width()) {
                    _display = "inline";
                } else {
                    _display = "inline";

                }

                var _array_option = [];
                _option.each(function (index) {
                    _array_option.push($(this))
                });

                exercice.Utils.setStyle(_array_option, { 'display': _display });
                exercice.Utils.setStyle([bloc_1, bloc_2], { 'height': 'auto', 'padding-top': "0px" });


            } else if (data.activity_image_position === "right" && dom._imageViewer.find('img').length) {
                if (_totalWidthOfOption_content_wrap > bloc_1_content.width()) {
                    _display = "inline";
                } else {
                    _display = "inline";

                }

                var _array_option = [];
                _option.each(function (index) {
                    _array_option.push($(this))
                });
                exercice.Utils.setStyle(_array_option, { 'display': "inline" });
                if (bloc_1_content.height() > bloc_2.height()) {
                    exercice.Utils.setStyle([bloc_2], { 'padding-top': Math.floor((bloc_1_content.height() - bloc_2.height()) / 2) + "px" });
                    exercice.Utils.setStyle([bloc_1], { 'padding-top': "0px" });
                } else {
                    exercice.Utils.setStyle([bloc_1], { 'padding-top': Math.floor((bloc_2.height() - bloc_1_content.height()) / 2) + "px" });
                    exercice.Utils.setStyle([bloc_2], { 'padding-top': "0px" });
                }
                if (!dom._imageViewer.find('img').length) {
                    exercice.Utils.setStyle([bloc_1], { 'width': '100%', 'float': 'left' });
                    exercice.Utils.setStyle([bloc_2], { 'padding-top': "0px" });
                } else {
                    exercice.Utils.setStyle([bloc_1], { 'width': '50%', 'float': 'left', 'height': 'auto' });
                    exercice.Utils.setStyle([bloc_2], { 'width': '50%', 'float': 'right', 'height': 'auto' });
                    exercice.Utils.setStyle([bloc_1_content, bloc_2_content], { 'width': '100%' });
                    exercice.Utils.setStyle([bloc_1], { 'padding-top': "0px" });
                    applyEqualHeight(bloc_1, bloc_2, bloc_1_content, bloc_2_content);
                }


            } else {
                exercice.Utils.setStyle([bloc_1], { 'width': '100%', 'float': 'left', 'padding-top': "0px" });
            }

        }




        // Complete saisie
        // left : answer + answer_content
        // right imageviewer
        // top : imageViewer
        else if (type === "ccs") {

            bloc_1 = dom._answer;
            bloc_1_content = dom._answer_content;

            bloc_2 = dom._imageViewer;
            bloc_2_content = dom._imageViewer_content;

            var _subAnswer_content_wrap = $('.subAnswer_content_wrap');
            var _array_subAnswer_content_wrap = [];
            _subAnswer_content_wrap.each(function (index) {
                _array_subAnswer_content_wrap.push($(this))
            });


            if (data.activity_image_position === "top") {
                exercice.Utils.setStyle([bloc_1, bloc_2], { 'width': '100%' });
                exercice.Utils.setStyle([bloc_2], { 'height': 'auto' });
            } else {
                applyEqualHeight(bloc_1, bloc_2, bloc_1_content, bloc_2_content);


                exercice.Utils.setStyle([bloc_1], { 'width': '50%', 'float': 'left' });
                exercice.Utils.setStyle([bloc_2], { 'width': '50%', 'float': 'right' });
                exercice.Utils.setStyle([bloc_1_content, bloc_2_content], { 'width': '100%' });


            }

        }

        // drag and drop
        // left : clozearea + clozearea_content
        // right : bank + bank_content
        // top : imageViewer
        else if (type === "ccl") {
            bloc_1 = dom._answer;
            bloc_1_content = dom._answer_content;

            bloc_2 = dom._imageViewer;
            bloc_2_content = dom._imageViewer_content;

            dom._clozeArea = $(".clozeArea");
            var bloc_3 = dom._clozeArea;
            var bloc_4 = dom._bank;

            exercice.Utils.setStyle([bloc_1, bloc_2], { 'width': '100%' });
            exercice.Utils.setStyle([bloc_2], {
                'padding-top': '0px',
                'float': 'none'
            });
            exercice.Utils.setStyle([bloc_1_content], { 'width': '100%' });
            exercice.Utils.setStyle([$(".clozeArea")], {
                'width': $('#wrapper-content-exo').width() - 400 + 'px',
                'float': 'left'
            });
            window.addEventListener("resize", function () {
                exercice.Utils.setStyle([bloc_3], {
                    'width': $('#wrapper-content-exo').width() - 400 + 'px',
                    'float': 'left'
                });

            }, true);


        }

        // Link
        // left : answer + answer_content
        // top : imageViewer
        else if (type === "linking") {


            bloc_1 = dom._answer;
            bloc_1_content = dom._answer_content;

            bloc_2 = dom._imageViewer;
            bloc_2_content = dom._imageViewer_content;
            exercice.Utils.setStyle([bloc_1], { 'width': '100%', 'float': 'none', 'height': 'auto', 'padding-top': '0' });
            exercice.Utils.setStyle([bloc_1_content], { 'width': '100%', 'text-align': 'center', 'margin': '0 auto' });
            exercice.Utils.setStyle([bloc_2], { 'width': '100%', 'float': 'none', 'padding-top': '0', 'height': 'auto' });


        }

        else if (type === "lp" || type === "lnp") {
            bloc_1 = dom._answer;
            bloc_1_content = dom._answer_content;

            bloc_2 = dom._imageViewer;
            bloc_2_content = dom._imageViewer_content;

            var bloc_3 = dom._clozeArea;
            var bloc_4 = dom._bank;
            exercice.Utils.setStyle([bloc_1], { 'width': '100%', 'padding-top': '0' });
            exercice.Utils.setStyle([bloc_1_content], { 'width': '100%', 'text-align': 'center' });
            exercice.Utils.setStyle([bloc_3], { 'width': 'auto', 'display': 'inline-block' });
            exercice.Utils.setStyle([bloc_4], {
                'width': '295px',
                'vertical-align': 'top',
                'display': 'inline-block',
                'position': 'relative'
            });

        }
       
        else if (type === "order") {
            var _order = $('.order ul');
            if(data.activity_typo==="Ordonner_MOT"){
                exercice.Utils.setStyle([_order], { 'display': 'flex' });
            }else  if(data.activity_typo==="Ordonner_PHRASE"){
                exercice.Utils.setStyle([_order], { 'display': 'block' });
            

            }
            bloc_1 = dom._answer;
            exercice.Utils.setStyle([bloc_1], { 'width': '100%' });

         

           

        }

        else if (type === "classer") {
            bloc_1 = dom._answer;
            exercice.Utils.setStyle([bloc_1], { 'width': '100%' });
            dom._clozeArea = $(".clozeArea");
            var bloc_3 = dom._clozeArea;
            var _marge = 0;
            if ($('body').hasClass("tablet")) {
                _marge = 0;
            } else {
                _marge = 340;
            }

            exercice.Utils.setStyle([bloc_3], {
                'width': $('#wrapper-content-exo').width() - _marge + 'px',

            });
            window.addEventListener("resize", function () {
                exercice.Utils.setStyle([bloc_3], {
                    'width': $('#wrapper-content-exo').width() - _marge + 'px',

                });


            }, true);


        }


    }

    function createScreenChangeOrientation(str) {

        if (str === "portrait") {
            var _tpl = '<div class="info-device"><div class="info-content-device">Veuillez passer en mode paysage.</div></div>';
            $("#content").append(_tpl);

        } else {
            $(".info-device").remove();
            window.scrollTo(0, 0);
        }
    }
    function doOnOrientationChange() {


        switch (window.orientation) {
            case -90:
            case 90:
                createScreenChangeOrientation("landscape");
                break;
            default:
                createScreenChangeOrientation("portrait");
                break;
        }

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// VALIDATATION ///////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    function getAnswserOfStudent() {

        if (_.size(_state) != 0) {
            for (var key in _state) {

                var value = _state[key];
                if (value.activity_id === _data_activity.activity_id) {

                    return value

                }

            }
        }

    }

    function validateActivity() {


        setState(_data_activity.activity_id)
        _tempRepForLines = [];
        _points = 0;

        dom._validation.css({ 'visibility': 'visible' });
        var _typo = _data_activity.activity_typo;
        var val2 = _data_activity.activity_typo;
        if (_end) {
            return
        }

        if (!enabledValid) {
            return
        }
        enabledValid = 0;

        if (val2.split("_")[0] === "Classer") {

            var _founded = 0;
            var _totalWords = 0;

            for (var t = 0; t < $('.column__container').length; t++) {
                var _n = t
                _totalWords += Number(_words["col" + Number(_n + 1)].length);
                $('.column__container').eq(t).find('.normal').each(function (index, t) {
                    var txt = $(this).html();


                    for (var u = 0; u < _words["col" + Number(_n + 1)].length; u++) {

                        $(this).parent().parent().parent().parent().addClass('red')
                        if (_words["col" + Number(_n + 1)][u] === txt) {
                            $(this).parent().parent().parent().parent().removeClass('red').addClass('green');
                            _founded++;
                            break;
                        } else {

                        }
                    }
                })

            }

            var allIsFounded = 0;

            if (_totalWords === _founded) {

                allIsFounded = 1;
                _points = 1;
            } else {
                allIsFounded = 0;
                _points = 0;
            }
            if (allIsFounded) {

                dom._attempt.css({ 'visibility': 'hidden' });
                showFeedBack("good")
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({ 'visibility': 'visible' });
                }

            } else {
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });

                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }
                if (Number(_data_serie.serie_try) === 0) {
                    //dom._correction.css({ 'visibility': 'visible' });
                    // dom._attempt.css({ 'visibility': 'hidden' });
                }

                showFeedBack("bad")
            }




        }
        else if (val2.split("_")[0] === "Ordonner") {
            var _tmp = [];

            for (var i = 0; i < _solutions_qc.length; i++) {
                $('#temp').html(_solutions_qc[i]);
                _tmp.push($('#temp').text())
            }

            if (isSameSet(_tmp, getContentTxt(".letter_box"))) {
                _points++;
                dom._attempt.css({ 'visibility': 'hidden' });
                showFeedBack("good")
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({ 'visibility': 'visible' });
                }

            } else {
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });

                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }
                if (Number(_data_serie.serie_try) === 0) {
                    //dom._correction.css({ 'visibility': 'visible' });
                    //dom._attempt.css({ 'visibility': 'hidden' });
                }

                showFeedBack("bad")
            }

            if (Number(_data_serie.serie_feedbacks_img)) {
                $(".letter_box").removeClass('green red');
                $(".letter_box").each(function (i) {

                    if ($(this).find("span").first().html() === _solutions_qc[i] + "<span></span>") {
                        $(this).addClass('green')
                    } else {
                        $(this).addClass('red')
                    }


                });
            }

        }




        else if (val2.split("_")[0] === "QCM" || val2.split("_")[0] === "QCU" || val2.split("_")[0] === "Cliquer") {

            populateCollection(_active_activity, getPositionAnswer(""))

            if (isSameSet(_solutions_qc, getCheckedBoxes("option"))) {
                _points++;
                dom._attempt.css({ 'visibility': 'hidden' });
                showFeedBack("good");
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({ 'visibility': 'visible' });
                }

            } else {
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });

                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }
                if (Number(_data_serie.serie_try) === 0) {
                    //  dom._correction.css({ 'visibility': 'visible' });
                    //  dom._attempt.css({ 'visibility': 'hidden' });
                }

                showFeedBack("bad")


            }

            if (Number(_data_serie.serie_feedbacks_img)) {
                $(".option").each(function (i) {
                    if (!_solutions_qc[i] && $(this).hasClass('selected')) {

                        if ($('.click').length) {
                            $(this).addClass('red')
                        } else {
                            $(this).find('#select').hide();
                            $(this).find('#selectWrong').css({ 'display': 'inline-block' });
                        }

                    } else if (_solutions_qc[i] && $(this).hasClass('selected')) {

                        if ($('.click').length) {
                            $(this).addClass('green')
                        } else {
                            $(this).find('#select').hide();
                            $(this).find('#selectRight').css({ 'display': 'inline-block' });
                        }

                    }

                });
            }


        }
        else if (val2 === "Compléter_LABEL" || val2 === "Légender_POINTEUR" || val2 === "Légender_NOPOINTEUR") {



            if (isSameSet(_goodAnswers, getDropBoxes())) {
                _points++;

                dom._attempt.css({ 'visibility': 'hidden' });
                showFeedBack("good")
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({ 'visibility': 'visible' });
                }




            } else {
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });
                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }

                if (Number(_data_serie.serie_try) === 0) {
                    //   dom._correction.css({ 'visibility': 'visible' });
                    //   dom._attempt.css({ 'visibility': 'hidden' });
                }
                showFeedBack("bad")

            }

            if (Number(_data_serie.serie_feedbacks_img)) {
                var _b = "";
                $(".clozeArea .subAnswer .textViewer").each(function (i) {
                    if ($(this).find('.normal').length) {
                        _b = $(this).find('.normal').html();
                    } else {
                        _b = $(this).html();
                    }

                    if (_b.indexOf('Wirisformula') > -1 && _goodAnswers[i].indexOf('Wirisformula') > -1) {
                        var v1 = _b.replace('<p>', '').replace('</p>', '').replace('<', '').replace('>', '').replace('""', '').split(' ');
                        var v2 = _goodAnswers[i].replace('<p>', '').replace('</p>', '').replace('<', '').replace('>', '').replace('""', '').split(' ');

                        if (equalArray(v1.sort(), v2.sort())) {
                            $(this).parent().parent().parent().addClass('correct');
                            $(this).attr('disabled', true)
                        } else {
                            $(this).parent().parent().parent().addClass('wrong');
                            $(this).attr('disabled', true)
                        }
                    } else {
                        if (_b === _goodAnswers[i]) {
                            $(this).parent().parent().parent().addClass('correct');
                            $(this).attr('disabled', true)
                        } else {
                            $(this).parent().parent().parent().addClass('wrong');
                            $(this).attr('disabled', true)
                        }
                    }



                });
            }
        }

        else if (val2 === "Compléter_SAISIE") {

            if (isSameSet(_listOfWordsCorrects, getInputBoxes())) {

                _points++;
                dom._attempt.css({ 'visibility': 'hidden' });
                showFeedBack("good")
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({ 'visibility': 'visible' });
                }


            } else {

                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });
                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }
                if (Number(_data_serie.serie_try) === 0) {
                    //  dom._correction.css({ 'visibility': 'visible' });
                    //  dom._attempt.css({ 'visibility': 'hidden' });
                }
                showFeedBack("bad")

            }
            if (Number(_data_serie.serie_feedbacks_img)) {
                var _txt = "";
                $(".answer input").each(function (i) {
                    if (_casse === "yes") {
                        _txt = $(this).val();
                    } else {
                        _txt = deletePunctuation($(this).val().toLowerCase())
                    }

                    if (_txt === _listOfWordsCorrects[i]) {
                        $(this).parent().parent().parent().parent().addClass('correct');
                        $(this).attr('disabled', true)
                    } else {
                        $(this).parent().parent().parent().parent().addClass('wrong');
                        $(this).attr('disabled', true)
                    }


                });
            }

        }
        else if (val2 === "Relier_TEXTE_TEXTE" || val2 === "Relier_AUDIO_AUDIO" || val2 === "Relier_IMAGE_IMAGE" || val2 === "Relier_TEXTE_AUDIO" || val2 === "Relier_AUDIO_TEXTE" || val2 === "Relier_TEXTE_IMAGE" || val2 === "Relier_IMAGE_TEXTE" || val2 === "Relier_IMAGE_AUDIO" || val2 === "Relier_AUDIO_IMAGE") {
            
            populateCollection(_active_activity, getPositionAnswer("link"))
            
            if (!_lines.length) {
                $(".link_anchor").each(function (i) {
                    $(this).addClass('wrong');
                    $(this).find('#incorrect').show();
                    $(this).find('#correct').hide();

                });
                dom._tryAgain.css({ 'visibility': 'visible' });
                showFeedBack("bad")
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._tryAgain.css({ 'visibility': 'hidden' });
                    dom._attempt.css({ 'visibility': 'hidden' });
                }

                return;
            }




            _lines.forEach(function (line, index) {
                var lineTarget1 = line.target_1;
                var lineTarget2 = line.target_2;
                if ($('#' + lineTarget1).data().color === $('#' + lineTarget2).data().color && $('#' + lineTarget1).data().color != "none" && $('#' + lineTarget2).data().color != "none") {

                    $('#' + lineTarget2).addClass('correct');
                    $('#' + lineTarget2).find('#correct').show();
                    $('#' + lineTarget2).find('#incorrect').hide();

                    $('#' + lineTarget1).addClass('correct');
                    $('#' + lineTarget1).find('#correct').show();
                    $('#' + lineTarget1).find('#incorrect').hide();
                    line.feedback = 'correct';


                }

            });

            _lines.forEach(function (line, index) {
                var lineTarget1 = line.target_1;
                var lineTarget2 = line.target_2;
                if ($('#' + lineTarget1).data().color != $('#' + lineTarget2).data().color && $('#' + lineTarget1).data().color != "none" && $('#' + lineTarget2).data().color != "none") {
                    $('#' + lineTarget2).removeClass('correct').addClass('wrong');
                    $('#' + lineTarget2).find('#incorrect').show();
                    $('#' + lineTarget2).find('#correct').hide();
                    _tempRepForLines.push(lineTarget2);
                    $('#' + lineTarget1).removeClass('correct').addClass('wrong');
                    $('#' + lineTarget1).find('#incorrect').show();
                    $('#' + lineTarget1).find('#correct').hide();
                    _tempRepForLines.push(lineTarget1);
                    line.feedback = 'incorrect';


                }
            });
            var allLinked = true;
            var cpt = 0;
            $(".link_anchor").each(function (i) {
                if ($(this).data().color != "none" && !$(this).hasAnyClass('selected') && !$(this).hasAnyClass('correct')) {
                    allLinked = false;
                    cpt++;
                    return;
                }

            })

            var searchAnswer = false;
            _lines.forEach(function (line, index) {
                if (line.feedback === 'incorrect') {
                    searchAnswer = true
                }
            });


            if (!searchAnswer) {

                if (!allLinked) {
                    if (Number(_data_serie.serie_feedbacks_txt)) {
                        if (cpt === 1) {
                            showFeedBack("bad")

                        } else {
                            showFeedBack("semigood")

                        }

                        dom._balloon_popup.css({ 'visibility': 'visible' })
                    }



                    if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                        dom._correction.css({ 'visibility': 'visible' });
                        dom._attempt.css({ 'visibility': 'hidden' });
                    } else {
                        dom._tryAgain.css({ 'visibility': 'visible' });
                    }
                    if (Number(_data_serie.serie_try) === 0) {
                        //  dom._correction.css({ 'visibility': 'visible' });
                        //  dom._attempt.css({ 'visibility': 'hidden' });
                    }



                }

                else {

                    _points++;
                    dom._attempt.css({ 'visibility': 'hidden' });
                    showFeedBack("good")
                    if (Number(_data_serie.serie_try) === 0) {
                        dom._validation.css({ 'visibility': 'visible' });
                    }
                }



            } else {
                if (_try === Number(_data_serie.serie_try) && Number(_data_serie.serie_try) != 0) {
                    dom._correction.css({ 'visibility': 'visible' });
                    dom._attempt.css({ 'visibility': 'hidden' });
                } else {
                    dom._tryAgain.css({ 'visibility': 'visible' });
                }
                if (Number(_data_serie.serie_try) === 0) {
                    // dom._correction.css({ 'visibility': 'visible' });
                    //  dom._attempt.css({ 'visibility': 'hidden' });
                }

                showFeedBack("bad")

            }


        }
        if (Number(_data_serie.serie_try) === 0) {
            setScore(currentActivity, _points, 0, null);
        } else {
            setScore(currentActivity, _points, _try, null);
        }


    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// Feedbacks /////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function manageStateNavigationForStudent(state) {

        if (state === "good" && _try === 1) {
            $("#list-activity li").eq(currentActivity - 1).removeClass('activity-error').removeClass('activity-mi').addClass('activity-good')

        } else if (state === "good" && _try === 2) {
            $("#list-activity li").eq(currentActivity - 1).removeClass('activity-error').removeClass('activity-good').addClass('activity-mi')

        } else if (state === "good" && _try === 3) {
            $("#list-activity li").eq(currentActivity - 1).removeClass('activity-mi').removeClass('activity-good').addClass('activity-error')

        } else if (state === "bad") {
            $("#list-activity li").eq(currentActivity - 1).removeClass('activity-mi').removeClass('activity-good').addClass('activity-error')

        }


    }
    function showFeedBack(type) {


        if (type === "good") {
            manageStateNavigationForStudent("good");

            if (Number(_data_serie.serie_feedbacks_audio) && _data_serie.serie_feedbacks_audio_1 != "") {
                audio_feed = new Audio("uploads/" + _data_serie.serie_feedbacks_audio_1);

                if (audio_feed) audio_feed.play();

            } else if (Number(_data_serie.serie_feedbacks_audio)) {
                audio_feed = new Audio('audio/good.mp3');

                if (audio_feed) audio_feed.play();


            }


            if (Number(_data_serie.serie_feedbacks_txt) != "") {
                switchBalloon("good");
                dom._balloon_popup.css({
                    'visibility': 'visible'
                })
            }




        } else if (type === "bad") {
            manageStateNavigationForStudent("bad");
            if (Number(_data_serie.serie_feedbacks_audio) && _data_serie.serie_feedbacks_audio_3 != "") {
                audio_feed = new Audio("uploads/" + _data_serie.serie_feedbacks_audio_3);
                if (audio_feed) audio_feed.play();
            } else if (Number(_data_serie.serie_feedbacks_audio)) {
                audio_feed = new Audio('audio/bad.mp3');
                if (audio_feed) audio_feed.play();

            }

            if (Number(_data_serie.serie_feedbacks_txt)) {

                switchBalloon("wrong");
                dom._balloon_popup.css({
                    'visibility': 'visible'
                })
            }
        } else {
            manageStateNavigationForStudent("bad");

            if (Number(_data_serie.serie_feedbacks_audio) && _data_serie.serie_feedbacks_audio_2 != "") {
                audio_feed = new Audio("uploads/" + _data_serie.serie_feedbacks_audio_2);
                if (audio_feed) audio_feed.play();
            } else if (Number(_data_serie.serie_feedbacks_audio)) {

                audio_feed = new Audio('audio/bad.mp3');
                if (audio_feed) audio_feed.play();

            }
            if (Number(_data_serie.serie_feedbacks_txt)) {

                switchBalloon("semigood");
                dom._balloon_popup.css({
                    'visibility': 'visible'
                })
            }
        }

    }

    function killAllSounds() {


        if (audio_feed && !isNaN(audio_feed.duration)) {
            audio_feed.pause();
            audio_feed.currentTime = 0.0;
            audio_feed = null

        }
        var audios = document.getElementsByTagName('audio');
        for (var i = 0, len = audios.length; i < len; i++) {
            if (!isNaN(audios[i].duration)) {
                audios[i].pause();
                audios[i].currentTime = 0.0;

            }



        }


    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// CORRECTION /////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function showCorrection() {

        _try = 1;
        enabledValid = 0;
        dom._balloon_popup.css({ 'visibility': 'hidden' });
        dom._validation.css({ 'visibility': 'hidden' });
        // COMPLETE SAISIE
        var val2 = _data_activity.activity_typo;


        if (val2.split("_")[0] === "Classer") {

            for (var t = 0; t < $('.column__container').length; t++) {
                $('.column__container').eq(t).find('.drop-target').empty()
                var _n = t;
                for (var u = 0; u < _words["col" + Number(_n + 1)].length; u++) {
                    $('.column__container').eq(t).find('.drop-target').append('<div class="column__item">' + _words["col" + Number(_n + 1)][u] + '</div>')
                    $('.draggable').css({ "visibility": "hidden" });


                }

            }

        }

        else if (val2.split("_")[0] === "Ordonner") {
            $(".letter_box").removeClass('green red');
            $(".letter_box").each(function (i) {
                $(this).html(_solutions_qc[i])
                $(this).addClass('green');
                $("#list-1").sortable('disable')


            });
        }






        else if (val2.split("_")[0] === "QCM" || val2.split("_")[0] === "QCU" || val2.split("_")[0] === "Cliquer") {
            $(".option").each(function (i) {


                if ($(".click").length) {
                    $(this).removeClass('selected blue red');
                    if (_solutions_qc[i]) {
                        $(this).addClass('selected green');
                    } else {
                        $(this).addClass('selected red');
                    }
                } else {
                    $(this).find('#selectWrong').hide();
                    $(this).find('#selectRight').hide();
                    $(this).find('#select').hide();
                    $(this).find('#unSelect').css({ 'display': 'block' });
                    if (_solutions_qc[i]) {
                        $(this).find('#unSelect').hide();
                        $(this).find('#selectRight').css({ 'display': 'block' });


                    }
                }




            });

        }
        else if (val2 === "Compléter_SAISIE") {
            var _subAnswer = $(".subAnswer.texteditor");
            _subAnswer.removeClass('wrong').addClass('correct');
            $(".answer input").attr('disabled', true);
            $('.miniTextEditor').each(function (i) {
                $(this).find('input').val(_copyOfListOfWordsCorrects[i])
                $(this).find('input').attr('size', $(this).find('input').val().length + 1.5);
            });

        }
        else if (val2 === "Compléter_LABEL" || val2 === "Légender_NOPOINTEUR" || val2 === "Légender_POINTEUR") {

            dom._clozeArea_content.find('.subAnswer').find('.textViewer').each(function (i) {
                $(this).parent().parent().parent().removeClass('full wrong').addClass('full correct');
                $(this).html(_goodAnswers[i].trim());
                $(this).show();


            });
        } else if (val2 === "Relier_TEXTE_TEXTE" || val2 === "Relier_AUDIO_AUDIO" || val2 === "Relier_IMAGE_IMAGE" || val2 === "Relier_TEXTE_AUDIO" || val2 === "Relier_AUDIO_TEXTE" || val2 === "Relier_TEXTE_IMAGE" || val2 === "Relier_IMAGE_TEXTE" || val2 === "Relier_IMAGE_AUDIO" || val2 === "Relier_AUDIO_IMAGE") {
            _layer.removeChildren();
            var _lists = $('.lists');
            _lists.find('.list').eq(0).find('.link_anchor').each(function (i) {
                var _targetA = $(this);
                var _listAColor = _targetA.data().color;
                _lists.find('.list').eq(1).find('.link_anchor').each(function () {
                    var _targetB = $(this);
                    if (_targetB.data().color === _listAColor && _targetB.data().color != "none" && _listAColor != "none") {


                        _targetB.find('#correct').show();
                        _targetB.find('#incorrect').hide();
                        _targetB.addClass('correct');
                        _targetA.addClass('correct');
                        _targetA.find('#correct').show();
                        _targetA.find('#incorrect').hide();
                        var idOfAnchor1 = _targetA.attr('id');
                        var idOfAnchor2 = _targetB.attr('id');
                        var container_rect = _stage.getContainer().getBoundingClientRect(),
                            anchor1_rect = document.getElementById(idOfAnchor1).getBoundingClientRect(),
                            anchor2_rect = document.getElementById(idOfAnchor2).getBoundingClientRect(),
                            points = calcPoints(anchor1_rect, container_rect, anchor2_rect);
                        var _line = new Kinetic.Line({
                            points: points,
                            strokeWidth: 3,
                            stroke: "#808080",
                            lineCap: 'round',
                            lineJoin: 'round'
                        });


                        _correction_lines.push(_line)
                        _layer.add(_line);




                    }

                })


            })
            _layer.drawScene();

        }

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// INIT AND PARSE /////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function createNavigationForStudent(total) {

        $("#header").append("<div id='student-nav'></div>");
        $("#student-nav").append("<ul id='list-activity'></ul>");
        for (var u = 0; u < total + 1; u++) {
            $("#list-activity").append('<li class="activity-dot"></li>')
        }
        $('.activity-dot').last().addClass('activity-dot-bilan');
        addEventsForNavigationStudent();
        if (Number(_data_serie.serie_bilan) === 0) {
            $('.activity-dot-bilan').hide()
        }
    }
    function addEventsForNavigationStudent() {
        /* NAVIGATION */
        $("#list-activity li").first().addClass('selectStu');


        $("#list-activity li").on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            _points = 0;
            _try = 1;
            dom._myAnswer.css({ 'visibility': 'hidden' });
            dom._balloon_popup.css({ 'visibility': 'hidden' });
            killAllSounds();
            dom._next.css({
                'visibility': 'visible'
            });
            dom._prev.css({
                'visibility': 'visible'
            });

            if (_modePlayer === "noCorrection") {
                enabledValid = 1;
                dom._correction.css({ 'visibility': 'hidden' });
                dom._attempt.css({ 'visibility': 'hidden' });
            } else {
                enabledValid = 0;
                dom._correction.css({ 'visibility': 'visible' });
                dom._attempt.css({ 'visibility': 'hidden' });
            }
            var _scores = getScore();
            var _scoresLength = _.size(_scores)

            if (_totalPoints >= 1 && Number(_data_serie.serie_try) === 0) {
                $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercices sur " + totalActivities);
            } else if (_totalPoints === 0 && Number(_data_serie.serie_try) === 0) {
                $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercice sur " + totalActivities);
            } else if (Number(_data_serie.serie_try) > 0 && _scoresLength > 0) {
                createListScore(_scores)
            } else {
                $('.result_bilan').html("Tu n'as réalisé aucun exercice.");
            }


            if ($(this).hasClass('activity-dot-bilan')) {
                _modePlayer = "correction";
                dom._bilan.show();

                if ($('.bank').length) {
                    $('.bank').remove()
                }
                $("#content-exo").hide();
                dom._balloon_popup.css({ 'visibility': 'hidden' });
                dom._validation.css({ 'visibility': 'hidden' });

                $("#list-activity li").removeClass('selectStu');
                $(this).addClass('selectStu');
                dom._next.css({
                    'visibility': 'hidden'
                });
                $("#cor").css({ "visibility": "hidden" });
                // if($('body').hasAnyClass('primaire')){
                // dom._tryAgainPrimaire.css({ 'visibility': 'visible' });
                //  dom._tryAgain.css({ 'visibility': 'hidden' });
                //  } else {
                dom._tryAgain.css({ 'visibility': 'visible' });
                // dom._tryAgainPrimaire.css({ 'visibility': 'hidden' });
                //  }
                if (_mode === "multiple") {
                    _active_activity = $(this).index();
                    currentActivity = $(this).index() + 1;
                } else {
                    _active_activity = 0;
                    currentActivity = 1
                }

            } else {


                dom._bilan.hide();
                dom._correction.addClass('bilan-answer');
                dom._myAnswer.addClass('bilan-answer');
                $(".wrap-progress-bar").hide();
                $("#list-activity li").removeClass('selectStu');
                $(this).addClass('selectStu');
                dom._answer_content.removeClass('linking');
                dom._answer_content.empty();
                if ($('.bank').length) {
                    $('.bank').remove()
                }

                if (_mode === "multiple") {
                    _active_activity = $(this).index();
                    currentActivity = $(this).index() + 1;
                } else {
                    _active_activity = 0;
                    currentActivity = 1;
                }
                if (_mode === "single") {
                    _data_activity = _data_total_activities;
                } else {
                    _data_activity = _data_total_activities.activities[_active_activity];
                }


                manageActivities(_data_activity);
                if (_modePlayer === "correction") {
                    showMyAnswer();
                }


                if (Number(_active_activity) === 0) {
                    dom._prev.css({
                        'visibility': 'hidden'
                    });
                }

                if (_modePlayer != "noCorrection" && !$(this).hasClass('activity-dot-bilan')) {

                    if ($(this).hasClass('activity-mi')) {
                        $("#cor").css({ "visibility": "hidden" });
                        dom._myAnswer.css({ 'visibility': 'hidden' });
                    }
                    else if ($(this).hasClass('activity-error')) {
                        $("#cor").css({ "visibility": "visible" });
                        dom._myAnswer.css({ 'visibility': 'hidden' });
                    } if ($(this).hasClass('activity-good')) {
                        $("#cor").css({ "visibility": "hidden" });
                        dom._myAnswer.css({ 'visibility': 'hidden' });
                    } else {
                        $("#cor").css({ "visibility": "visible" });
                        dom._myAnswer.css({ 'visibility': 'hidden' });
                    }

                    dom._attempt.css({
                        'visibility': 'hidden'
                    });
                    dom._validation.css({
                        'visibility': 'hidden'
                    });
                } else {
                    dom._attempt.css({
                        'visibility': 'visible'
                    });
                    dom._validation.css({
                        'visibility': 'visible'
                    });
                }



            }

        })
    }

    function showMyAnswer() {



        if (getAnswserOfStudent()) {
            var val2 = getAnswserOfStudent().activity_typo;

            if (val2 === "Ordonner_MOT" || val2 === "Ordonner_PHRASE") {
                for (var j = 0; j < getAnswserOfStudent().activity_answer.length; j++) {
                    if (getAnswserOfStudent().activity_answer[j]) {
                        $(".letter_box").removeClass('green red');
                        $(".letter_box").each(function (i) {
                            $(this).html(getAnswserOfStudent().activity_answer[i])
                            $("#list-1").sortable('disable')


                        });
                    }
                }
            }
            if (val2.split("_")[0] === "Classer") {
                $('.draggable').css({ "visibility": "visible" });
                for (var t = 0; t < $(".column__container").length; t++) {
                    $('.column__container').eq(t).find('.drop-target').empty()

                    if (getAnswserOfStudent().activity_answer["col" + Number(t + 1)].length) {
                        for (var u = 0; u < getAnswserOfStudent().activity_answer["col" + Number(t + 1)].length; u++) {
                            $('.column__container').eq(t).find('.drop-target').append('<div class="column__item">' + getAnswserOfStudent().activity_answer["col" + Number(t + 1)][u] + '</div>')

                            $('.draggable').find('.normal').each(function () {

                                if ($(this).html() === getAnswserOfStudent().activity_answer["col" + Number(t + 1)][u]) {
                                    $(this).parent().parent().parent().parent().parent().css({ "visibility": "hidden" });
                                }
                            })



                        }
                    }



                }
            }

            if (val2 === "Compléter_LABEL") {
                var _temp = []



                for (var t = 0; t < $("#clozeArea_content").find(".subAnswer").length; t++) {
                    $("#clozeArea_content").find(".subAnswer").eq(t).removeClass("correct").removeClass('wrong')
                    if (getAnswserOfStudent().activity_answer[t]) {
                        $('#temp').html(getAnswserOfStudent().activity_answer[t]);
                        _temp.push($('#temp').find('.normal').html())
                        
                        $("#clozeArea_content").find(".subAnswer").eq(t).find(".textViewer").html(getAnswserOfStudent().activity_answer[t]);
                    }
                }



            }

            if (val2 === "Compléter_SAISIE") {
                $(".miniTextEditor input").each(function (i) {
                    $(this).val("");

                    $(this).parent().parent().parent().parent().removeClass('correct').removeClass('wrong');
                    if (getAnswserOfStudent().activity_answer[i]) {
                        $(this).val(getAnswserOfStudent().activity_answer[i]);
                    }
                });

                $('input[type="text"]').attr('size', $('input[type="text"]').val().length + 1.5);
            }

            if (val2.split("_")[0] === "Relier") {


                $(".link_anchor").removeClass('wrong').removeClass('correct').removeClass('selected')
                _layer.removeChildren();

                var _linesp = getAnswserOfStudent().activity_answer["lines"]

                if (_linesp.length) {
                    var _line;
                    for (var i = 0; i < _linesp.length; i++) {
                        _line = new Kinetic.Line({
                            points: [_linesp[i].attrs.points[0], _linesp[i].attrs.points[1], _linesp[i].attrs.points[2], _linesp[i].attrs.points[3]],
                            strokeWidth: 3,
                            stroke: "#808080",
                            lineCap: 'round',
                            lineJoin: 'round'
                        });
                        _layer.add(_line);
                        _layer.draw();

                    }

                   
                }
                _layer.drawScene();
            }
            if (val2.split("_")[0] === "Légender") {
                var _temp = []

                for (var t = 0; t < $("#clozeArea_content").find(".subAnswer").length; t++) {

                    if (getAnswserOfStudent().activity_answer[t]) {
                        $('#temp').html(getAnswserOfStudent().activity_answer[t]);
                        _temp.push($('#temp').find('.normal').html())

                        if ($("#clozeArea_content").find(".subAnswer").eq(t).find(".textViewer").html() === _temp[t]) {

                        } else {
                            $("#clozeArea_content").find(".subAnswer").eq(t).removeClass("correct").addClass('wrong')
                        }
                        $("#clozeArea_content").find(".subAnswer").eq(t).find(".textViewer").html(getAnswserOfStudent().activity_answer[t]);
                    }
                }



            }
            if (val2.split("_")[0] === "QCM" || val2.split("_")[0] === "QCU" || val2.split("_")[0] === "Cliquer") {

                if ($(".click").length) {
                    $(".option").each(function (i) {

                        $(this).removeClass("red green selected");
                        for (var j = 0; j < getAnswserOfStudent().activity_answer.length; j++) {
                            $(".option").eq(getAnswserOfStudent().activity_answer[j]).addClass("blue");
                        }

                    })
                } else {
                    $(".option").removeClass('selected');
                    $(".option").find('.icon-check_box_01').show();
                    $(".option").find('.icon-check_box_03').hide();
                    $(".option").find('.icon-check_box_04').hide();
                    $(".option").find('.icon-check_box_02').hide();

                    for (var j = 0; j < getAnswserOfStudent().activity_answer.length; j++) {
                        $(".option").eq(getAnswserOfStudent().activity_answer[j]).find('.icon-check_box_01').hide();
                        $(".option").eq(getAnswserOfStudent().activity_answer[j]).addClass('selected');
                        $(".option").eq(getAnswserOfStudent().activity_answer[j]).find('.icon-check_box_02').css({
                            'display': 'inline-block'
                        })


                    }
                }




            }
        } else {

            if ($('.ccs').length) {
                $(".miniTextEditor input").each(function (i) {


                    $(this).parent().parent().parent().parent().removeClass('correct').removeClass('wrong');

                });


            }




            else if ($(".click").length) {
                $(".option").each(function (i) {
                    $(this).removeClass("red green selected");
                })
            } else if ($('.qc').length) {
                $(".option").removeClass('selected');
                $(".option").find('.icon-check_box_01').show();
                $(".option").find('.icon-check_box_03').hide();
                $(".option").find('.icon-check_box_04').hide();
                $(".option").find('.icon-check_box_02').hide();

            } else if ($('.linking').length) {
                $(".link_anchor").removeClass('wrong').removeClass('correct').removeClass('selected')
                _layer.removeChildren();
                _layer.drawScene();
            } else if ($('.ccs').length) {
                $(".miniTextEditor input").each(function (i) {
                    $(this).val("")

                });

            } else if ($('.ccl').length || $('.lnp').length || $('.lp').length) {
                for (var t = 0; t < $("#clozeArea_content").find(".subAnswer").length; t++) {
                    $("#clozeArea_content").find(".subAnswer").eq(t).removeClass("correct").removeClass('wrong')
                    $("#clozeArea_content").find(".subAnswer").eq(t).find(".textViewer").html('')
                }

            } else if ($('.order').length) {
                $(".letter_box").removeClass('green red')

            } else if ($('.classer').length) {
                $('.draggable').css({ "visibility": "visible" });
                for (var t = 0; t < $(".column__container").length; t++) {
                    $('.column__container').eq(t).find('.drop-target').empty()
                }

            }


        }

    }
    function parseDatasSerie(datas) {
        dom_bilan._title_serie_bilan.html(exercice.Utils.doReplace(datas.serie_title));
        dom_bilan._message_bilan.html(exercice.Utils.doReplace(datas.serie_bilan_txt));

        if (datas.serie_bilan_img != "") {
            dom_bilan._mascote_bilan.empty().html('<img id="mascote_bilan" src="' + datas.serie_bilan_img + '" alt="">')
        }

    }
    function checkDevice() {
        if (exercice.Utils.isTablet()) {
            $('body').addClass("tablet");
            var screenOrientation = ($(window).width() > $(window).height()) ? 90 : 0;
            if (screenOrientation === 90) {
                createScreenChangeOrientation("landscape");
            } else {
                createScreenChangeOrientation("portrait");
            }

            $(window).bind("resize", function () {
                screenOrientation = ($(window).width() > $(window).height()) ? 90 : 0;
                if (screenOrientation === 90) {
                    createScreenChangeOrientation("landscape");
                } else {
                    createScreenChangeOrientation("portrait");
                }
            });

        } else {
            $('body').addClass("desktop");
        }
    }
    function setData(datas) {
        yourDatas = datas
    }
    function getData() {
        return yourDatas
    }
    function init(data_activity, desc, data_serie) {
        deleteContentArray();
        mediaManager = new MediaManager();
        if (window.yourDatas) {
            setData(window.yourDatas)

        }
        initVar();

        if (getData()) {
            _data_serie = JSON.parse(getData()).data_serie;
            _data_total_activities = JSON.parse(getData()).data_activities;
            totalActivities = _data_total_activities.activities.length;
            _data_activity = _data_total_activities.activities[_active_activity];
            if (totalActivities) {
                _mode = "multiple";
            } else {
                _mode = "single";
            }
            $('body').addClass('export');
        }

        else if (desc === "multi") {
            _mode = "multiple";
            _data_serie = data_serie;
            _show_bilan = Number(data_serie.serie_bilan);
            _data_total_activities = data_activity;
            totalActivities = _data_total_activities.activities.length;
            _data_activity = _data_total_activities.activities[_active_activity];
        } else {
            _mode = "single";
            _show_bilan = Number(data_serie.serie_bilan);
            _data_total_activities = data_activity;
            totalActivities = 1;
            _data_activity = data_activity;
            _data_serie = data_serie;
        }
        if ($('#temp').length) $('#temp').remove()
        $('body').append('<div id="temp" style="display:none;"></div>');
        _data_serie.serie_css === "Primaire" ? $("body").addClass('primaire') : $("body").removeClass('primaire');
        _image_position_bilan = _data_serie.serie_bilan_img_position;
        _btn = !exercice.Utils.isTablet() ? ["VALIDER", "RÉESSAYER", "SUIVANT", "RETOUR", "CORRIGER", "MA RÉPONSE"] : ["VALIDER", "RÉESSAYER", '>', "<", "CORRIGER", "MA RÉPONSE"];


        createWindow();
        createContent();
        createProgression();
        createFeedBack();
        createAttemp();
        parseDatasSerie(_data_serie);
        manageActivities(_data_activity);
        createEventForToolbar();
        createNavigationForStudent(totalActivities);
        updateAttempt(_try);

        if (_data_serie.serie_css != "Primaire") {
            $("#student-nav").css({ 'visibility': 'hidden' });
        }


        if ($("body").hasClass('primaire')) {
            $("#container-progress-bar").hide();
        }
        var scrollingDiv = document.getElementById('content-exo');
        scrollingDiv.addEventListener('touchmove', function (event) {
            event.stopPropagation();
        });
        checkDevice();
        _modePlayer = "noCorrection";
        if (Number(_data_serie.serie_try) === 0) {
            dom._attempt.hide();
        }


    }
    return {
        init: init,
        yourDatas: yourDatas

    }


})();



