/**
 * Created by laurent-heneman on 29/01/16.
 */
/* STRUCTURE */
/* class modal */
/* id dialogTitle */
/* id dialogContent */
/* class wrap-progress-bar */
/* id content */
/* class title_serie_bilan road */
/* id wrapper-content-exo */
/* class question */
/* class textViewer */ //not used
/* class imageViewer */
/* answer (lnp,) */
/* class answer-content (lnp) */
/* id dialogControls */

/* Process */
// all empty
// create exercice => create "consigne" + create "question" + add image (top or right)
// if top => bloc image width : 100% & bloc question width : 100%
// Question => text + image (width : 2 x 50 %)
// bloc image on top (600x300) && bloc image on right (600x300) on desktop

/* v4.5 => CHANGE DISPLAY */
/* v5 => CHANGE DISPLAY FOR TABLET */

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 _show_bilan = false;
    var currentActivity = 0;
    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 = ["VALIDER", "RÉESSAYER", "SUIVANT", "RETOUR", "CORRIGER"];
    var _balloonTxt = ["Mauvaise réponse","Bonne réponse","Presque bon"]
    var _solutions_qc = [];
    var listOfWords = [];
    var _anchors = [];
    var _listOfWordsCorrects = [];
    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 _linkingMode = "oneToMany";
    var targetActive;
    var _tempRepForLines = [];
    var bankOffsetTop =0;
    var bankOffsetLeft = 0;

    /* 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) {
            $('#player').remove();
        });
    }
    function createContent() {
        var template = '<div id="content"><div class="title_serie_bilan road">Titre de la série</div><div id="wrapper-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 class="bilan"><div class="bilan-content"></div></div><div id="toolbar_container"><div id="toolbar_content"></div></div></div>';
        // <div class="textViewer"><div class="textViewer-content"></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');
        dom.bilan.hide();

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

        // TextViewer
        //dom._textViewer = $('.textViewer');
        //dom._textViewer_content = $('.textViewer-content');

        // ImageViewer
        dom._imageViewer = $('.imageViewer');
        dom._imageViewer_content = $('.imageViewer-content');

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

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

        createButton();

        // Button Toolbar
        dom._correction = $('#cor');
        dom._validation = $('#validate');
        dom._tryAgain = $('#tryAgain');
        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_prev = '<div id="prev"><div class="prev-content"><div class="txt-content"><span class="button">' + _btn[3] + '</span></div></div></div>';
        dom._toolbar_content.append(template_button_prev);

        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_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);


    }
    function createEventForToolbar() {

        dom._validation.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            validateActivity()
        });
        dom._tryAgain.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            tryAgainActivity();
        });
        dom._next.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            nextActivity()
        });
        dom._prev.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            prevActivity()
        });
        dom._correction.on(exercice.Utils.appEvents().globalEvents.mousedown, function () {
            showCorrection()
        });
        dom._correction.css({
            'visibility': 'hidden'
        });
        dom._prev.css({
            'visibility': 'hidden'
        });
        dom._attempt.css({'visibility': 'visible'});
        dom._tryAgain.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) {
        //touches: A list of information for every finger currently touching the screen
        //changedTouches: A list of information for every finger involved in the event
        //When I lift a finger, it will be removed from touches, targetTouches and will appear in changedTouches since it’s what caused the event
        //Removing my last finger will leave touches and targetTouches empty, and changedTouches will contain information for the last finger
        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 createTransition() {
        var template = '<div id="transition" class="transition"></div>';

    }

    function createAnimationTransition() {
        $('#wrapper-content-exo').removeClass('fadeOutOut').addClass('fadeInIn');
        setTimeout(function () {
            //$('.transition').removeClass('fadeOutOut').addClass('fadeInIn');
            //$('#wrapper-content-exo').css({'opaciy':1});
            $('#wrapper-content-exo').removeClass('fadeInIn').addClass('fadeOutOut');
        }, 500);
    }

    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;
            target.hide();
            img.on('load', function () {
                var maxWidth = 120;
                var maxHeight = 120;
                var width = $(this).width();
                var height = $(this).height();
                var ratioW = maxWidth / width;  // Width ratio
                var ratioH = maxHeight / height;  // Height ratio

                // If height ratio is bigger then we need to scale height
                if (ratioH > ratioW) {
                    $(this).css("width", maxWidth);
                    $(this).css("height", height * ratioW);  // Scale height according to width ratio
                }
                else { // otherwise we scale width
                    $(this).css("height", maxHeight);
                    $(this).css("width", width * ratioH);  // according to height ratio
                }
                $(this).show();
            });
        }
    }

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

        // must adjust blocs before image loaded
        dom._imageViewer_content.empty();
        if(data.activity_image != ""){
            dom._imageViewer.show();
            dom._imageViewer.css({'visibility': 'hidden'});
            if (_position === "top") {

                //max-height: 100%;
                //width: auto;
                // update class
                dom._imageViewer.removeClass("position-right").addClass("position-top");
                // add image
                //<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="loading"></div>
                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) {
                        $(this).addClass("responsive-width");
                        exercice.Utils.setHeight(dom._imageBox,'auto');
                    }else if(srcwidth<srcheight) {
                        $(this).addClass("responsive-height")

                    }else {
                        $(this).addClass("responsive-height")
                    }

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

                        $('.container_kinetics').css({
                            left :  ($('.list').eq(0).offset().left+$('.list').eq(1).width()-40)+"px"
                        })

                    }

                })

            }else if (_position === "right") {
                //<div id="gen_id_' + exercice.Utils.generateUUID() + '" class="loading"></div>
                dom._imageViewer.removeClass("position-top").addClass("position-right");
                dom._imageViewer_content.html('<div id="img_box" style=" width: ' + _w/1.5 + '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).addClass("responsive-height")
                    }
                    updatePositionBlock(_typo, data);
                    dom._imageViewer.css({'visibility': 'visible'});
                    if($('.container_kinetics').length){
                        $('.container_kinetics').css({
                            left :  ($('.list').eq(0).offset().left+$('.list').eq(1).width()-40)+"px"
                        })

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

                })
            }
        }
        else {
            dom._imageViewer.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;
        }

        // scale to the target width
        var scaleX1 = targetwidth;
        var scaleY1 = (srcheight * targetwidth) / srcwidth;

        // scale to the target height
        var scaleX2 = (srcwidth * targetheight) / srcheight;
        var scaleY2 = targetheight;

        // now figure out which one we should use
        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 = [];
        _listOfWordsInputs = [];
        _goodAnswers = [];
        listOfWords = [];
        _anchors = [];
        _lines = [];
    }

    /* COMPARE ARRAY */
    function isSameSet(arr1, arr2) {
        //console.log("isSameSet :", arr1, arr2);
        if(arr1.length&&arr2.length) {

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

            return true;
        }


    }

    /* FEEDBACKS */
    function createFeedBack() {
        var tpl = '<div id="gen_id_1" class="balloon_popup correct" style="opacity: 1; width: auto;">' +
            '<div id="gen_id_1_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="gen_id_1_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="gen_id_1_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;
        dom.bilan.css({'height': _h - 100});
        dom._balloon_popup.css({
            'top': _h-_h_toolbar-60,
            'left': _left + dom._validation.width()+80

        });

        if($('.container_kinetics').length){
            //buildCanvas();
            //drawLines();
            $('.container_kinetics').css({
                left :  ($('.list').eq(0).offset().left+$('.list').eq(1).width()-40)+"px",
            })
            /*$('.list').eq(1).offset({
             left :  (positionLeftOfList-$('.list').eq(1).offset().left)+"px",

             })*/
        }
    }



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

    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');
            dom._balloon_popup.find('.feedback').html(exercice.Utils.doReplace(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');
            dom._balloon_popup.find('.feedback').html(exercice.Utils.doReplace(_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');
            dom._balloon_popup.find('.feedback').html(exercice.Utils.doReplace(_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;

        /**
         * Having loaded the control bar we can now utilize and show it
         * wherever a media interaction occurs, play, pause
         */
        this.attachControl = function () {
            //$(Mustache.to_html(this.controlType, this.mediaConfig)).appendTo( "#" + this.currentItem.id );
            //$(this.control).bind('onclick', this.togglePlay);
        },

            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.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;
                }

                //todo decide on volume range (0,1) or (0,100) and coordinate with dtp
                //right now we support both this code need to be deleted when decision is made
                while (volume > 1) {
                    volume = volume / 100;
                }

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

            },

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

    }

    /* PROGRESSION */
    function createProgression() {
        var view_template = '<span class="wrap-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></span>'
        $('#dialogContent').append(view_template);
        dom._dialogContent = $('#dialogContent');
        dom._progressBar = $('#progress_bar');
        dom._progress = $('.ui-progress');
        dom._progressLabel = $('.progression-label');
        updateProgression(1)
    }

    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>')


    }

    /* BILAN */
    function addSvgBilan() {

        var _svg_icone = '<svg id="svg_icone" 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>'
        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;
    }

    /* SCORE */
    function setScore(_id, _point, _try, _time) {
        _score[_id]={activity_score: _point, activity_try: _try, activity_time: _time}
        ////console.log("_score",_score);
        getTotalPoints()
    }
    function getScore() {
        return _score
    }
    function getTotalPoints(){
        _totalPoints=0;
        _.each(getScore(), function(num,key){
           // //console.log("er",key,num.activity_score)
            _totalPoints+=num.activity_score;
        });
        ////console.log('t',_totalPoints)
    }
    function updateScore(id){
        _.each(getScore(), function(num,key){
           // //console.log("id",id)
           // //console.log("key",key)
            if(key>id) {
                _score[key].activity_score=0;
            }
        });
        getTotalPoints();
       // //console.log("update_score",_score);
    }

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

    /* APPLY EQUAL HEIGHT */
    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='" + 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>";

        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]));

        }


    }
    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">' + 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 (data) {
            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);
            }

        }


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


        dom._answer_content.append(TEMPLATE_LISTS);
        dom._answer_content.addClass('noselect');
        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();
        //updatePositionOfLink();



    }


    function imgBasE64(){

        $("img[src*='base64']").each(function(){
            $(this).css ({
               'vertical-align' : 'middle',
                'margin-bottom': '4px',
                'margin-left': '-20px'
           })
        });
    }

    function newPosition(){


        // get number of items
        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;


    for(t;t<nbr_items_A;t++) {
        if (nbr_items_B === nbr_items_A) {
            _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;
            console.log("Avant ajustement", _listA.children().children().eq(t).height(), _listB.children().children().eq(t).height(), _refA, _refB)
            //console.log(_listA.children().children().eq(t).height(), _listB.children().children().eq(t).height());
            if (_refA > 0 && _refB < 0) {
                _listB.children().children().eq(t).css({'height': _listA.children().children().eq(t).height()})
                _listB.children().children().eq(t).children().children().first().css({"top": _refA + "px"})
                _listB.children().children().eq(t).children().first().css({"top": _refA + "px"})
               // _listB.children().children().eq(t).children().children().children().first().css({"position":"relative","top": "50%","margin-top":"-"+_listB.children().children().eq(t).children().children().children().first().height()+'px'})
            } 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().children().first().css({"top": _refB + "px"})
                _listA.children().children().eq(t).children().first().css({"top": _refB + "px"})
               // _listA.children().children().eq(t).children().children().children().first().css({"position":"relative","top": "50%","margin-top":"-"+_listA.children().children().eq(t).children().children().children().first().height()+'px'})

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

                _listA.children().children().eq(t).css({'height': '55px'})
                // _listA.children().children().eq(t).children().children().children().css({"top" :"30px"})

                _listB.children().children().eq(t).css({'height': '55px'})
                // _listB.children().children().eq(t).children().children().children().css({"top" :"30px"})

            }

        }

    }







    }
    function createTemplateLink(data,_typo) {
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(txt);
        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"
        }

        // audio or texte or image
        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) {
            ////console.log("anchor.right ", anchor.right);
            if (anchor.right > maxRight) {
                maxRight = anchor.right;
            }
            ////console.log("anchor.left ", anchor.left);
            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
        });
        ////// update ///////
        var _lists = $('.lists');


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

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

            })
        }
        /////////////////////
        

        
    }

    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: 130,
            //canvasWidth,
            height: _hC,
            //$(".answer").height(),
            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));
        // $(this).mouseleave(onMouseUp.bind(this)); // bind mouseup event to mouseleave as well
        $('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')) {
                    //check that this target is not from the same list
                    if (anchor) {

                        do_drawLine = !(anchor.list_id == over_anchor.list_id);
                    }
                } else { //anchor is selected - allow drawing line from definition list only

                    if (_linkingMode === "oneToMany") {
                        if (over_anchor.isDefinitionAnchor()) {
                            do_drawLine = true;
                        }
                    }
                }
                // add an update for multiple

                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) {
                //has feedback - disabled anchor
                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 (_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');
        }

        //find lines to destroy
        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) {
        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;
            // update new line points
            var newPoints = _line.getPoints();
            newPoints[2] = xPos;
            newPoints[3] = yPos;
            _line.setPoints(newPoints);
            _moving = true;
            _layer.drawScene();

        } else {
            evt.preventDefault = null;
        }
    }
    function onMouseDown(e) {
        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;
            //check if drawing line from anchor is valid
            if (_linkingMode === "oneToMany") {
                //allow drawing more than one line from definition list and only one from the options list
                if ($(elTarget).parent().hasClass('selected')) {
                    if (over_anchor.isDefinitionAnchor()) {
                        isValidLineStart = true;
                    }
                } else {
                    isValidLineStart = true;
                }
            } //else = not one to many linking mode
            else if (!$(elTarget).parent().hasClass('selected')) {
                isValidLineStart = true;

            } else {
                //has feedback - disabled anchor


                if ($(elTarget).parent().hasClass('correct') || $(elTarget).parent().hasClass('incorrect') || $(elTarget).parent().hasClass('_correctconnected')) {
                    return true;
                }
                // mouse down for removing the line
                $(elTarget).parent().removeClass('selected');
                $(elTarget).parent().find('.link_anchor').removeClass('selected');
                //find line and destroy it

                // why return ??

                var tmp = _.where(_lines, {target_1: elTarget.id});
                ////console.log("find line and destroy it _lines =>", tmp);
                if (!tmp.length) {
                    tmp = _.where(_lines, {target_2: elTarget.id});
                }

                if (tmp.length) {
                    tmp[0].destroy();

                    // _layer.drawScene();
                    $('#' + 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]);
                    ////console.log("_lines =>", _lines)

                }


            }
            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() {
        _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);

        //start point and end point are the same
        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;

        //get over anchor
        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(txt);
        dom._imageViewer_content.html('');


        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());
        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(parsedData);
        } catch (e) {
            dom._clozeArea_content_textViewerParagraph.append(t);
        }
        ;
        dom._clozeArea_content_textViewerParagraph.find("span").each(function () {
            if ($(this).attr('class') === "editor_delete_word") {
                $(this).remove();
            }

            if ($(this).attr('class') === "editor_word") {
                _goodAnswers.push($(this).text().split('⊗')[0].trim());
                _listOfWordsCorrects.push($(this).text().split('⊗')[0].trim());
                _solutions_qc = shuffleArray(_listOfWordsCorrects);
                $(this).before(createBoxTarget());
                $(this).remove();
            }
        });
        createBoxForDragElement();
        createEventsForCompleteDD();
        //dom._bank = $('.bank');
        /*if (data.activity_image === "") {
         dom._clozeArea.css({
         'width': dom._answer.width() - dom._bank.width() - 40,
         'height': dom._bank.height()
         });
         dom._answer_content.css({'text-align': 'left'});
         }*/

    }

    function createBoxTarget() {
        var tpl = '<div class="subAnswer 0 custom-alignment drop-target " id="gen_id_' + exercice.Utils.generateUUID() + '" style="width: 128px; height: 35px;">			' +
            '<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: 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 createEventsForCompleteDD() {
        dom._draggable = $("#content").find(".draggable");
        dom._target = $(".drop-target");
        dom._draggable.bind("mousedown touchstart", startDragging);
        dom._target.bind("mousedown touchstart", targetDown);
        bankOffsetTop = $(".bank").offset().top;
        bankOffsetLeft = $(".bank").offset().left;
    }

    // add when validate add autorisation if (enbalbe)
    function targetDown(){
        if($(this).find(".textViewer").text().trim()!=""){
            var target =$(this);
            var t =target.attr('data-id')
            dom._draggable.each(function () {
                ////console.log(t, $(this).attr('id'))
                if (t === $(this).parent().parent().attr('id')) {
                    target.attr('data-id', 'l');
                    target.removeClass('full').removeClass('occuped');
                    target.find('.textViewer').text("");
                    $(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();
            // and save them in a container for later access
            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');
                $(this).find('.textViewer').text("");
            }
            var lefttop = $(this).offset();
            idDrop.push($(this).attr('id'));
            // and save them in a container for later access
            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;

            // Change the position of the draggable

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

            // Bind the events for dragging and stopping
            $(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) {
            targetActive.parent().parent().addClass('textviewer full');
            targetActive.find('.textViewer').css({'display': 'block'});
            targetActive.find('.textViewer').addClass('occuped');
            targetActive.find('.textViewer').text(dragged.find('.textViewer').text());
            targetActive.removeClass('somethingover');
            targetActive.parent().parent().addClass('occuped');
            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 {

            }
            // add data-id in drop target
            targetActive.parent().parent().attr('data-id', dragged.parent().parent().attr('id'));



            //var t = $('#container_plots').append(dragged.clone())

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

            });
            dragged.css({
                "opacity": 0,
                "visibility" : "hidden"

            });
            dragged.addClass('pop')




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

            });
        }


    }

    function continueDragging(e) {
        e.preventDefault();
        e.stopPropagation();
        $(".subAnswer").each(function () {
            if ($(this).attr('data-id') === dragged.parent().parent().attr('id')) {
                $(this).find('.textViewer').text("");
                $(this).attr('data-id', 'l');
                $(this).removeClass('occuped')
            }
        });
        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
            .offset({
                top: top,
                left: left
            });

        // Check if we hit any boxes
        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').text("")
            }

            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];
                    coordinates[i].dom.find('.subAnswer_content_wrap').find('.subAnswer_content').addClass("somethingover");

                }
            } else {

                coordinates[i].dom.find('.subAnswer_content_wrap').find('.subAnswer_content').removeClass("somethingover");
            }
        }

        // Keep the last positions of the mouse coord.s
        mousex = pageX;
        mousey = pageY;

    }

    function getDropBoxes() {

        _listOfWordsInputs = [];
        dom._clozeArea_content.find('.subAnswer').find('.textViewer').each(function (i) {
            _listOfWordsInputs.push($(this).text().trim())
        });


        // Return the array if it is non-empty, or null
        return _listOfWordsInputs.length > 0 ? _listOfWordsInputs : null;


    }

    function getCheckedBoxes(chkboxName) {
        var checkboxes = document.getElementsByClassName(chkboxName);
        var checkboxesChecked = [];
        // loop over them all
        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(){
        ////console.log($(".bank").offset().top,bankOffsetTop)
        if($(".bank").offset().top>bankOffsetTop){

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

                   // //console.log(lefttop,$(".bank").offset().top,bankOffsetTop)
                    $(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()

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

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



    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// COMPLETE SAISIE SYSTEM /////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function createTemplateComplete(data,_typo) {

        _listOfWordsCorrects = [];
        // consigne
        var txt = data.activity_consigne ? data.activity_consigne : "Aucune consigne pour cette activité.";
        dom._questionViewer_content.html(txt);
        // 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%'});
        }
        var u = data.activity_data;
        try {
            parsedData = JSON.parse(u);
            $('#clozeArea_content .textViewerParagraph').append(parsedData);
        } catch (e) {
            $('#clozeArea_content .textViewerParagraph').append(u);
        }

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

                if ($(this).attr('class') === "editor_word") {
                    _listOfWordsCorrects.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]));

        }

    }

    function createBoxForExoComplete() {
        var Tpl = "<div class='miniTextEditor' id='" + exercice.Utils.generateUUID() + "'><input id='" + exercice.Utils.generateUUID() + "_te' type='text' value='' size='30' 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) {
            _listOfWordsInputs.push($(this).find('input').val())
        });
        return _listOfWordsInputs.length > 0 ? _listOfWordsInputs : null;


    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// 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(txt);
        // image
        dom._imageViewer_content.html('');
        addImage(data, 600, 300, data.activity_image_position,typo);


    }

    function createExoQC(data) {
        createContainerBox();
        var str;
        if (typeof(data.activity_data) === 'object') {
            str = data.activity_data;
        } else {
            str = JSON.parse(data.activity_data)
        }

        str = shuffleArray(str);
        for (var t = 0; t < str.length; t++) {
            createBox(str[t].answer);
            _solutions_qc.push(str[t].checked);

        }

    }

    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;
        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'))) {
                       // //console.log("currentPlayed", currentPlayed)

                    } 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');
                        exercice.Utils.setStyle([_target_off],{'display':'block'});
                        exercice.Utils.setStyle([_target_on],{'display':'none'});

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


                    }


                    mediaManager.togglePlay();

                    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_on],{'display':'none'});
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }


                //if (e.target.className === "image" || e.target.className === "option_body" || e.target.className === "textViewer") {
                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');
                        exercice.Utils.setStyle([_target_off],{'display':'block'});
                        exercice.Utils.setStyle([_target_on],{'display':'none'});

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


                    }


                    mediaManager.togglePlay();

                    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_on],{'display':'none'});
                        mediaplayer.removeClass('playing');
                    });
                    return;

                }


                if (!enabledValid) {
                    return
                }
                if (_data_activity.activity_typo === "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'})

                } else {
                    $(this).parent().removeClass('selected');
                    $(this).find('.icon-check_box_02').css({'display': 'none'})
                }


            });
        }

    }

    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) {
            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">' + data + '</div>';
        return template_txt
    }

    function createBoxImage(data) {

        var 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(txt);
        // 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;
            }
            ////console.log(newW+':'+newH,(400-newH)/2);
            if(newH<395) {
                // update V6
                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]-2, pts[1]-2, pts[2]-2, 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;
                ////console.log('_line.target_1', _line.target_1);
                ////console.log('_line.target_2', _line.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 - 23,
                        posY: data.markers[i].posY - 200 - 100 - 23 + data.delta
                    };
                    $('#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: 128px; height: 35px;">			' +
            '<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: 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

    }


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

    function deleteActivity() {
        emptyContent();
        manageActivities(_data_activity);

    }

    function manageActivities(data) {
        deleteContentArray();
        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 = "";

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


        } 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;

        }
        dom._answer_content.removeClass('ccs').removeClass('ccl').removeClass('qc').removeClass('linking').removeClass('lnp').removeClass('lp');
        dom._answer.removeClass('ccs').removeClass('ccl').removeClass('qc').removeClass('linking').removeClass('lnp').removeClass('lp');

        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_content.addClass('qc');
                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 "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
        }


        imgBasE64();

    }

    function tryAgainActivity() {
        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': 'visible'});
            $(".road").css({'visibility': 'visible'});
            dom._next.css({
                'visibility': 'visible'
            });
            emptyContent();
            currentActivity = 0;
            enabledValid = 1;
            _active_activity = 0;
            _end = 0;
            _points = 0;

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

            }
            updateProgression(1);
            updateAttempt(1);
            manageActivities(_data_activity);
            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();
                    //$(this).find('#correct').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')) {
                                var t = $(this).text().trim();
                                dom._draggable.each(function (i) {

                                    if ($(this).text().trim() === t && _id=== $(this).parent().parent().attr('id')) {
                                        $(this).css({
                                            /*"left": 3000,
                                             "top": 3000,*/
                                            "visibility": "hidden"

                                        });

                                    }

                                });

                            } else if ($(this).parent().parent().parent().hasAnyClass(' wrong')) {
                                var t = $(this).text().trim();
                                var _id=$(this).parent().parent().parent().attr('data-id');

                                //$(this).attr('data-id') === dragged.parent().parent().attr('id')
                                $(this).parent().parent().parent().removeClass('full wrong');
                                dom._draggable.each(function (i) {

                                    if ($(this).text().trim() === t && _id=== $(this).parent().parent().attr('id')|| t === " ") {
                                       // //console.log("wrong=>",$(this).text().trim() , t,_id, $(this).parent().parent().attr('id') )
                                        $(this).css({
                                            "left": 0,
                                            "top": 0,
                                            "opacity": 1,
                                            "visibility": "visible"

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

                            }
                        });
                    }
                }


                // 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 {
                            $(this).find('input').attr('disabled', true);
                        }
                    })

                }

                // qcm/qcu
                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() {

        dom._prev.css({
            'visibility': 'visible'
        });
        dom._balloon_popup.css({
            'visibility': 'hidden'
        });
        if (Number(_data_serie.serie_bilan) && _active_activity === totalActivities - 1) {

            if (_totalPoints > 1) {
                $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercices sur " + totalActivities);
            } else {
                $('.result_bilan').html("Tu as réussi " + _totalPoints + " exercice sur " + totalActivities);
            }
            _end = 0;
            _totalPoints =0;
            _score={};
            dom.bilan.show();
            dom._correction.css({'visibility': 'hidden'});
            dom._attempt.css({'visibility': 'hidden'});
            $(".road").css({'visibility': 'hidden'});
            dom._tryAgain.css({'visibility': 'visible'});
            dom._validation.css({
                'visibility': 'hidden'
            });
            dom._next.css({
                'visibility': 'hidden'
            });
            dom._prev.css({
                'visibility': 'hidden'
            });
            return
        } else {
            if (_active_activity === totalActivities - 1) {
                _end = 1;
                dom._next.css({
                    'visibility': 'hidden'
                });
                return
            }
        }


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


    }

    function prevActivity() {
        updateProgression(0);

        enabledValid = 1;
        _try = 1;
        changeActivity(0);
        dom._next.css({
            'visibility': 'visible'
        });
        dom._balloon_popup.css({
            'visibility': 'hidden'
        });
        dom.bilan.hide();
        dom._attempt.css({'visibility': 'visible'});
    }

    function changeActivity(dir) {
        dom._answer_content.removeClass('linking');
        dom._answer_content.empty();
        deleteContentArray();
        updateAttempt(_try = 1);
        if (dir) {
            _active_activity++;
            _data_activity = _data_total_activities.activities[_active_activity];
            manageActivities(_data_activity);
            // prev
        } else {

            ////console.log("_active_activity =>",_active_activity);
            ////console.log("_points =>",_points);
            _active_activity--;
            updateScore(_active_activity)
            _data_activity = _data_total_activities.activities[_active_activity];
            manageActivities(_data_activity);
        }




        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 = "";

        //console.log("********************updatePositionBlock****************",type)
        // Qcm-qcu
        // left : answer + answer_content
        // right imageviewer
        // top imageviewer
        // case with image
        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;
            //console.log("qcu => updatePositionBlock => with image",dom._imageViewer.find('img').length);

            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;
                //console.log("qcu => updatePositionBlock => _option_content_wrap", $(this).width());
            });

            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";
                    //_display = "inline-block";
                }

                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";
                    // _display = "inline-block";
                }

                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"});
                    ////console.log("1-margin-top",Math.floor((bloc_1_content.height() - bloc_2.height()) / 2))
                } 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"});
                    ////console.log("2-margin-top",Math.floor(Math.floor((bloc_2.height() - bloc_1_content.height()) / 2)))
                }
                if(!dom._imageViewer.find('img').length){
                    exercice.Utils.setStyle([bloc_1], {'width': '100%', 'float': 'left'});
                }else {
                    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%'});
                    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
        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))
            });

            //exercice.Utils.setStyle(_array_subAnswer_content_wrap, {'width': '170px', 'height': '29px'});

            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);

                // update here
                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%'});
                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"});

                } else {
                    //exercice.Utils.setStyle([bloc_1], {'padding-top': Math.floor((bloc_2.height() - bloc_1_content.height()) / 2) + "px"});

                }

            }

        }

        // drag and drop
        // left : clozearea + clozearea_content
        // right : bank + bank_content
        // top : imageViewer
        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'
            });
            //exercice.Utils.setStyle([bloc_4], {'width': '390px', 'float': 'right'});
            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
        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'});


        }

        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'
            });

        }


    }

    function doOnOrientationChange()
    {
        if (screen.height > screen.width) {
            ////console.log('portrait');

        } else {
            ////console.log('landscape');
        }
    }

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

    function validateActivity() {

        _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] === "QCM" || val2.split("_")[0] === "QCU") {

            if (isSameSet(_solutions_qc, getCheckedBoxes("option"))) {
                _try = 0;
                _points++;
                dom._attempt.css({'visibility': 'hidden'});
                if (Number(_data_serie.serie_feedbacks_audio)) {
                    var audio = new Audio('audio/good.mp3');
                    audio.play();
                }

                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("good");
                    dom._balloon_popup.css({'visibility': 'visible'})
                }
                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'});
                    //dom._validation.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'});
                }

                if (Number(_data_serie.serie_feedbacks_audio)) {
                    var audio = new Audio('audio/bad.mp3');
                    audio.play();
                }

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


            }

            if (Number(_data_serie.serie_feedbacks_img)) {
                $(".option").each(function (i) {
                    if (!_solutions_qc[i] && $(this).hasClass('selected')) {
                        $(this).find('#select').hide();
                        $(this).find('#selectWrong').css({'display': 'inline-block'});
                    } else if (_solutions_qc[i] && $(this).hasClass('selected')) {
                        $(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++;
                _try = 0;
                dom._attempt.css({'visibility': 'hidden'});
                if (Number(_data_serie.serie_feedbacks_audio)) {

                    var audio = new Audio('audio/good.mp3');
                    audio.play();

                }
                if (Number(_data_serie.serie_try) === 0) {
                    dom._validation.css({'visibility': 'visible'});
                }

                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("good");
                    dom._balloon_popup.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_feedbacks_audio)) {
                    var audio = new Audio('audio/bad.mp3');
                    audio.play();
                }
                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("wrong");
                    dom._balloon_popup.css({'visibility': 'visible'})
                }
                if (Number(_data_serie.serie_try) === 0) {
                    dom._correction.css({'visibility': 'visible'});
                    dom._attempt.css({'visibility': 'hidden'});
                }

            }

            if (Number(_data_serie.serie_feedbacks_img)) {
                $(".clozeArea .subAnswer .textViewer").each(function (i) {

                    if ($(this).text().trim() === _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())) {
                _try = 0;
                _points++;
                dom._attempt.css({'visibility': 'hidden'});
                if (Number(_data_serie.serie_feedbacks_audio)) {

                    var audio = new Audio('audio/good.mp3');
                    audio.play();

                }
                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("good");
                    dom._balloon_popup.css({'visibility': 'visible'})
                }
                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'});
                }
                if (Number(_data_serie.serie_feedbacks_audio)) {
                    var audio = new Audio('audio/bad.mp3');
                    audio.play();
                }

                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("wrong")
                    dom._balloon_popup.css({'visibility': 'visible'})
                }

            }
            if (Number(_data_serie.serie_feedbacks_img)) {
                $(".answer input").each(function (i) {
                    if ($(this).val() === _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") {
            if (!_lines.length) {
                $(".link_anchor").each(function (i) {
                    $(this).addClass('wrong');
                    $(this).find('#incorrect').show();
                    $(this).find('#correct').hide();

                });
                dom._tryAgain.css({'visibility': 'visible'});
                if (Number(_data_serie.serie_feedbacks_audio)) {
                    var audio = new Audio('audio/bad.mp3');
                    audio.play();

                }
                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("wrong");
                    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._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;
                ////console.log($('#' + lineTarget1).data().color, " / ", $('#' + lineTarget2).data().color);

                // On valide toutes les bonnes réponses

                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 searchAnswer = false;
            _lines.forEach(function (line, index) {
                if (line.feedback === 'incorrect') {
                    searchAnswer = true
                }
            });


            if (!searchAnswer) {
                _try = 0;
                _points++;
                dom._attempt.css({'visibility': 'hidden'});
                if (Number(_data_serie.serie_feedbacks_audio)) {

                    var audio = new Audio('audio/good.mp3');
                    audio.play();

                }
                if (Number(_data_serie.serie_feedbacks_txt)) {
                    switchBalloon("good");
                    dom._balloon_popup.css({'visibility': 'visible'})
                }
                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'});
                }
                if (Number(_data_serie.serie_feedbacks_audio)) {
                    var audio = new Audio('audio/bad.mp3');
                    audio.play();
                }

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


        }

        setScore(currentActivity,_points,_try,null);
        //console.log("points =>", _points);
        //console.log("activity=>", currentActivity);
        //console.log("try =>", _try);
        getScore();

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// 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] === "QCM" || val2.split("_")[0] === "QCU") {
            $(".option").each(function (i) {
                $(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(_listOfWordsCorrects[i])

            });
        }
        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).text(_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") {
            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") {

                        deleteLines();
                        _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');
                        ////console.log("showCorrection =>", idOfAnchor1);
                        ////console.log("showCorrection =>", idOfAnchor2);
                        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);
                        ////console.log("showCorrection =>", points);

                        var _line = new Kinetic.Line({
                            points: points,
                            strokeWidth: 3,
                            stroke: "#808080",
                            lineCap: 'round',
                            lineJoin: 'round'
                        });
                        _layer.add(_line);
                        _layer.drawScene();

                    }

                })


            })


        }


    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////// INIT AND PARSE /////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    function parseDatasSerie(datas) {
        dom_bilan._title_serie_bilan.html(datas.serie_title);
        dom_bilan._message_bilan.html(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 init(data_activity, desc, data_serie) {
        if (exercice.Utils.isTablet()) {
            $('body').addClass("tablet")
        }
        deleteContentArray();
        mediaManager = new MediaManager();
        if (window.yourDatas) {
            yourDatas = window.yourDatas;
        }
        _try = 1;
        _end = 0;
        _score={};
        currentActivity = 0;
        enabledValid = 1;
        _active_activity = 0;
        _totalPoints=0;
        _points = 0;
        if (yourDatas) {

            _data_serie = JSON.parse(yourDatas).data_serie;
            _data_total_activities = JSON.parse(yourDatas).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") {
            ////console.log('MODE => 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 {
            ////console.log('MODE => SINGLE');
            _mode = "single";
            _show_bilan = Number(data_serie.serie_bilan);
            _data_total_activities = data_activity;
            totalActivities = 1;
            _data_activity = data_activity;
            _data_serie = data_serie;
        }

        createWindow();
        createProgression();
        createContent();
        createFeedBack();
        createAttemp();

        if (Number(_data_serie.serie_try) === 0) {
            dom._attempt.hide();
        }

        parseDatasSerie(_data_serie);
        manageActivities(_data_activity);
        createEventForToolbar();
        updateAttempt(_try);
        window.addEventListener('orientationchange', doOnOrientationChange);


    }

    return {
        init: init,
        yourDatas: yourDatas

    }


})();