
<style>
    .message {
        padding:10px;
        margin-top: 5px;
        background-color: #{{ colorbodyback }};
        color: #{{ colorbodyfont }};
    }
    .message-toread { 
        font-weight:bold;
    }
    .message-see { 
        display:none;
    }

    .msgavatar {
        height:40px;
    }

    .msgtitle {
        line-height: 12px;
    }
    .msgtitle small{
        zoom: 80%;
    }    
    .msgreplys {
        margin-bottom:10px;
    }
    .messagereply {
        padding:0px;
        border-top: 1px solid #{{ colorbodyfont }};
        font-size:12px;
    }

    .btnreplymessage, .btnreplymessagemail {
        padding: 5px;
        background-color: #{{ colorbodyfont }};
        color : #{{ colorbodyback }};
        border-radius:5px;
        cursor:pointer;
        margin-right:5px;
    }
    .btnreplymessage:hover, .btnreplymessagemail:hover {
        color : #{{ colorbodyback }};
    }
    .replymessage { display:none}
    .replymessage textarea {
        width:100%;
        margin:20px 0px 5px 0px;
        height:150px;
        color:#000000;
    }
    .sendreply { width:100%}

    .bootstrap-switch{
        margin-top:5px;
    }
    .labelswitch {
        line-height: 40px;
        float: right;
        margin-right: 10px;        
    }
    #listtoavatar img {
        margin:0px 5px 5px 0px; 
        cursor:pointer;
    }
    .cke_bottom{ display:none }
</style>

<div>
    {% set colorlabel= colormain %}
    {% if border  %}
        {% set colorlabel = colorbody %}
    {% endif %}
    {% if colorbody==colorbodyfont %}
        {% set colorlabel = colorbodyback %}
    {% endif %}
    
    {% if app.user and ingroup %}
        {{ form_start(form) }}
            <div id="topchat" class='d-flex flex-column'>
                {{ form_widget(form.message) }}

                <div class="d-flex align-items-center">
                    <input id="sendbymail" type="checkbox" style="float:right" class='switch' ></input>            
                    <label class="custom-control-label ps-2" for="sendbymail" style="color:#{{ colorlabel }}">Envoyer par Mail ?</label>
                </div>
                <a id="sendbtn" class="btn btn-success" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
                
                <div id="useronline" style="margin-bottom:10px"></div>
                
                <div class="d-flex align-items-center">
                    <input id="unsee" type="checkbox" style="float:right" class='switch' onChange="switchsee()"></input>
                    <label class="custom-control-label ps-2" for="unsee" style="color:#{{ colorlabel }}">Afficher les messages masqués ?</label>
                </div>
            </div>

            <div class="mychat">
                {% for message in messages %}
                    {% set classread="" %}
                    {% if not message.haveread %}
                        {% set classread="message-toread" %}
                    {% endif %}

                    {% set classsee="" %}
                    {% if message.havesee %}
                        {% set classsee="message-see" %}
                    {% endif %}

                    <div id='message-{{message.id}}' class='message {{classread}} {{classsee}}'>
                        <div class='d-flex flex-column'>
                            <div class="msgheader d-flex align-items-center">
                                <div class='msgavatar'>
                                    <img style='cursor:pointer' onclick='seeUser({{message.user.id}})' id='user_avatar_img' src='{{ asset("uploads/avatar/"~message.user.avatar) }}' class='avatar'><br>
                                </div>

                                <div class='msgtitle px-3 flex-grow-1'>
                                    {{message.user.lastname}} {{message.user.firstname}}<br>
                                    <small>{{message.submitdate|date('d/m/Y H:i')}}</small>
                                </div>                            

                                <div class='msgaction'>
                                    {% if canmanage or message.user == app.user %}
                                        <i class='delmessage fa fa-trash fa-fw' data-id='{{message.id}}' title='Supprimer' style='cursor: pointer;'></i>
                                    {% endif %}
                                    {% if not message.havesee %}
                                        <i id="hidemessage-{{message.id}}" class='hidemessage fa fa-eye-slash fa-fw' title='Ne plus afficher' data-id='{{message.id}}' style='cursor: pointer;'></i>
                                    {% endif %}        
                                </div>                 
                            </div>   

                            <div class='msgdiv mt-2'>
                                <div class='msgtopic'>{{message.topic | raw}}</div>

                                <div id="msgreplys-{{message.id}}" class='msgreplys'>
                                    {% for child in message.childs | reverse %}
                                        {% set classread="" %}
                                        {% if not child.haveread %}
                                            {% set classread="message-toread" %}
                                        {% endif %}

                                        {% set classsee="" %}
                                        {% if child.havesee %}
                                            {% set classsee="message-see" %}
                                        {% endif %}

                                        <div id='message-{{child.id}}' class='message messagereply {{classread}} {{classsee}}'>
                                            {{child.topic | raw | nl2br   }}

                                            <div style='cursor:pointer' onclick='seeUser({{child.user.id}})'><small>{{ child.user.lastname }} {{ child.user.firstname }}</small></div>
                                            <small>{{child.submitdate|date('d/m/Y H:i')}}</small>
                                            {% if canmanage or child.user == app.user %}
                                                <i class='delmessage fa fa-trash fa-fw' data-id='{{child.id}}' title='Supprimer' style='cursor: pointer;'></i>
                                            {% endif %}
                                            {% if not child.havesee %}
                                                <i id="hidemessage-{{child.id}}" class='hidemessage fa fa-eye-slash fa-fw' title='Ne plus afficher' data-id='{{child.id}}' style='cursor: pointer;'></i>
                                            {% endif %}
                                        </div>
                                    {% endfor %}
                                </div>

                                <a class="btnreplymessage" data-id='{{message.id}}'>Répondre</a>
                                <a class="btnreplymessagemail" data-id='{{message.id}}'>Répondre par Mail</a>
                                <div id="replymessage-{{message.id}}" class="replymessage">
                                    <textarea></textarea>
                                    <a id="sendreply" class="btn btn-success sendreply" data-id='{{message.id}}'>Envoyer</a>
                                </div>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </div>

            <div id="mymodal-sendmail" class="modal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">Notifier par Mail</h4>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="form-group ">
                                <label class="control-label required" for="mailsuject">Sujet du Mail<span class="mandatory">*</span></label>
                                <input type="text" id="mailsuject" name="mailsuject" required="required" class="form-control">
                            </div>
                            <div>
                                <label class="control-label required">Destinataires<span class="mandatory">*</span></label>

                                <select id="destinataires" style="width:100%" name="states[]" multiple="multiple">
                                    {% for user in group.users |sort((a, b) => a.user.lastname <=> b.user.lastname) %} %}
                                        {% if(user.user!=app.user) %}
                                            <option value="{{ user.user.email }}" data-image="{{ asset('uploads/avatar/' ~ user.user.avatar) }}">{{ user.user.lastname }} {{ user.user.firstname }}</option>
                                        {% endif %}
                                    {% endfor %}
                                </select>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="" id="checkalldestinataires">
                                    <label class="form-check-label" for="checkalldestinataires">
                                    Tout le monde
                                    </label>
                                </div>                        
                            </div>
                            <div class="form-group" style="margin-top:10px">
                                <label class="control-label required">Corps du Mail<span class="mandatory">*</span></label>
                                {{ form_widget(form.messagemail) }}
                            </div>
                            <a id="sendbtnmail" class="btn btn-success" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
                            <a id="sendbtnmailreply" class="btn btn-success" data-id="" style="margin-top:5px; width:100%; margin-bottom:15px">Envoyer</a>
                        </div>
                    </div>
                </div>
            </div>

        {{ form_end(form) }}
    {% endif %}
</div>

<script>
	$(document).ready(function(){
        $(".switch").bootstrapSwitch();

        if (CKEDITOR.instances["chat_message"]) CKEDITOR.instances["chat_message"].destroy();
        if (CKEDITOR.instances["chat_messagemail"]) CKEDITOR.instances["chat_messagemail"].destroy();

        setTimeout(function(){
            CKEDITOR.replace( 'chat_message', {
                toolbar: [
                    { name: 'custo01',   items: [ 'Bold','Italic','Underline','RemoveFormat' ] },
                    { name: 'custo02',   items: [ 'NumberedList','BulletedList' ] },
                    { name: 'custo03',   items: [ 'Smiley','Link','Unlink' ]}
                ],
                height: 100
            });

            CKEDITOR.replace( 'chat_messagemail', {
                toolbar: [
                    { name: 'custo01',   items: [ 'Bold','Italic','Underline','RemoveFormat' ] },
                    { name: 'custo02',   items: [ 'NumberedList','BulletedList' ] },
                    { name: 'custo03',   items: [ 'Smiley','Link','Unlink' ]}
                ],
                height: 150
            });
        },1000);
        
        $("#mymodal-sendmail").removeAttr("tabindex");

        websocket();
	});

    {% if websocket_activate and app.user %}
        var tosend=false;
        var tosendmail=false;
        var todelete=false;
        var idtodelete;

        var conn;
        function websocket()
        {       
            wssurl="{{wss_url}}";
            if("{{app.request.scheme}}"=="http") wssurl=wssurl.replace("wss:","ws:");
            conn = new WebSocket(wssurl);

            conn.onopen = function(e) {
                console.log("== CONNECT");
                {% set userkey = "" %}
                {% if app.user %}
                    {% set userkey = app.user.apikey %}
                {%endif%}

                subscribe("chat",{{group.id}},"{{userkey}}");
                sendMessage({command: "alive"});

                // Si action en cours
                if(tosend) sendbtn();
                if(tosendmail) sendbtnmail();
                if(todelete) delmessage(idtodelete);                
            };

            conn.onmessage = function(e) {
                console.log("== ON MESSAGE");
                ret=JSON.parse(e.data);
                switch(ret.command) {
                    case "alive" :
                        addOnline(ret.from.id, ret.from.avatar, ret.from.displayname);

                        {% if app.user.visible %}
                            sendMessage({command: "meto"});
                        {% endif %}
                    break;

                    case "adead" :
                        userid= {{ app.user.id }};
                        if(ret.from.id!=userid) $("#online"+ret.from.id).remove();
                        else sendMessage({command: "alive"});
                    break;

                    case "meto" :
                        addOnline(ret.from.id, ret.from.avatar, ret.from.displayname);
                    break;

                    // Desactiver la notification
                    case "unnotify":
                        unnotify(ret.from);
                    break;

                    // Reception d'un nouveau message dans le chat
                    case "addchat":
                        avatar="{{ asset('xxx') }}";
                        avatar=avatar.replace("xxx",ret.from.avatar);
                        html ="<div id='message-"+ret.id+"' class='message message-toread'>";
                            html+="<div class='d-flex flex-column'>";
                                html+="<div class='msgheader d-flex align-items-center'>";
                                    html+="<div class='msgavatar'>";
                                        html+="<img style='cursor:pointer' onclick='seeUser("+ret.from.avatar+")' id='user_avatar_img' src='"+avatar+"' class='avatar'>";
                                    html+="</div>";

                                    html+="<div class='msgtitle px-3 flex-grow-1'>";
                                        html+=ret.from.displayname+"<br>";
                                        html+="<small>"+ret.submitdate+"</small>";
                                    html+="</div>";

                                    html+="<div class='msgaction'>";
                                        if(ret.from.id=={{app.user.id}} || '{{ canmanage }}'=='1') {
                                            html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+ret.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                                        }
                                        html+="<i id='hidemessage-"+ret.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+ret.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                                    html+="</div>";
                                html+="</div>";

                                html+="<div class='msgdiv mt-2'>";
                                    html+="<div class='msgtopic'>"+ret.message+"</div>";
                                    html+="<div id='msgreplys-"+ret.id+"' class='msgreplys'></div>";
                                        html+="<a class='btnreplymessage' data-id='"+ret.id+"'>Répondre</a>";
                                        html+="<a class='btnreplymessagemail' data-id='"+ret.id+"'>Répondre par Mail</a>";
                                    html+="<div id='replymessage-"+ret.id+"' class='replymessage'>";
                                    html+="<textarea></textarea>";
                                    html+="<a id='sendreply' class='btn btn-success sendreply' data-id='"+ret.id+"'>Envoyer</a>";
                                html+="</div>";                        
                            html+="</div>";
                        html+="</div>";
                        $(".mychat").prepend(html);                    
                    break;

                    // Reception d'un reply de message
                    case "replychat":
                        // Si on reçoit une réponse forcement le parent est de nouveau visible
                        $("#message-"+ret.parent).removeClass ("message-see");

                        // On ajout la réponse
                        html ="<div id='message-"+ret.id+"' class='message messagereply message-toread'>";
                        html+=nl2br(ret.message);
                        html+="<div style='cursor:pointer' onclick='seeUser("+ret.from.id+")'><small>"+ret.from.displayname+"</small></div>";
                        html+="<small>"+ret.submitdate+"</small>";
                        if(ret.from.id=={{app.user.id}} || '{{ canmanage }}'=='1') {
                            html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+ret.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                        }
                        html+="<i id='hidemessage-"+ret.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+ret.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                        html+="</div>";            

                        $("#msgreplys-"+ret.parent).prepend(html); 
                    break;

                    // Reception d'un log
                    case "log":
                        console.log("Received message", ret.message);
                    break;

                    // Reception d'une suppression de message
                    case "delchat":
                        $("#message-"+ret.id).remove();
                    break;

                    // Reception d'une suppression d'une alerte
                    case "alert":
                        console.log("Received message", ret.message);
                    break;
                }
            }

            conn.onclose = function(e) {
                console.log("== DISCONNECT");
                setTimeout(function() { websocket(); }, 1000);        
            }; 
        }

        function nl2br (str, is_xhtml) {
            if (typeof str === 'undefined' || str === null) {
                return '';
            }
            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
        }        

        function switchsee() {
            $(".message-see").hide();
            if($("#unsee").bootstrapSwitch('state')) {
                $(".message-see").show();
            }
        }

        $( "#sendbtn" ).click(function() {
            sendbtn();
        });

        function formatState (opt)
        {
            if (!opt.id) {
                return opt.text.toUpperCase();
            } 

            var optimage = $(opt.element).attr('data-image'); 
            console.log(optimage)
            if(!optimage){
            return opt.text.toUpperCase();
            } else {                    
                var $opt = $(
                '<span><img src="' + optimage + '" width="30px" height="30px" style="border-radius:100%"/> ' + opt.text + '</span>'
                );
                return $opt;
            }
        };

        $("#checkalldestinataires").click(function()
        {
            if($("#checkalldestinataires").is(':checked') ){
                $("#destinataires > option").prop("selected","selected");
                $("#destinataires").trigger("change");
            }else{
                $("#destinataires > option").removeAttr("selected");
                $("#destinataires").trigger("change");
            }
        });

        function sendbtn()
        {
            var data = CKEDITOR.instances["chat_message"].getData();
            if($("#sendbymail").bootstrapSwitch('state')) {
                CKEDITOR.instances["chat_messagemail"].setData(data);
                $("#mailsuject").val("{{app.session.get('appname')}} = Notification {{ group.label }}");
                
                $("#sendbtnmail").show();
                $("#sendbtnmailreply").hide();
                $('#mymodal-sendmail').modal('show');
                $("#checkalldestinataires").prop( "checked", false );
                $("#destinataires").val("");
                /*
                $("#destinataires > option").removeAttr("selected");
                $("#destinataires").trigger("change");    
                */
                $('#destinataires').select2();
            }
            else {
                if(data) {
                    try {
                        // Flager que l'envoit c'est fait
                        tosend=false;
                        $("#sendbtn").html("Envoyer");
                        $("#sendbtn").removeClass("btn-danger");
                        $("#sendbtn").css('cursor','auto');

                        // Push envent sur le websocket
                        sendMessage({command: "addchat","message": data});    

                        // Vider l'editeur
                        CKEDITOR.instances["chat_message"].setData('');

                    }
                    catch(error) {
                        // L'envoi ne s'est pas fait
                        console.log("Retry to send");

                        // On flag le fait de retenter l'envoit à la reconnexion
                        tosend=true;

                        // On signal que l'envoi est en cours sur le bouton
                        $("#sendbtn").html("Envoi en cours");
                        $("#sendbtn").addClass("btn-danger");
                        $("#sendbtn").css('cursor','progress');
                    }
                }
            }
        }

        $( "#sendbtnmail" ).click(function()
        {
            sendbtnmail();
        });

        function sendbtnmail()
        {
            var data = CKEDITOR.instances["chat_messagemail"].getData();
            var subject=$("#mailsuject").val();
            var destinataires=$("#destinataires").val();

            if(data&&subject&&!(jQuery.isEmptyObject(destinataires))) {

                try {
                    // Flager que l'envoit c'est fait
                    tosendmail=false;
                    mailto=destinataires.join(';');
                    mailto=";"+mailto;
                    $("#sendbtnmail").html("Envoyer");
                    $("#sendbtnmail").removeClass("btn-danger");
                    $("#sendbtnmail").css('cursor','auto');

                    // Push envent sur le websocket
                    sendMessage({command: "addchat","message": data, mail: "true", to: mailto, subject: subject})

                    // Vider l'editeur
                    CKEDITOR.instances["chat_message"].setData('');

                    // Cacher la popup
                    $("#sendbymail").bootstrapSwitch('state',false);
                    $('#mymodal-sendmail').modal('hide');
                }
                catch(error) {
                    // L'envoi ne s'est pas fait
                    console.log("Retry to send");

                    // On flag le fait de retenter l'envoit à la reconnexion
                    tosendmail=true;

                    // On signal que l'envoi est en cours sur le bouton
                    $("#sendbtnmail").html("Envoi en cours");
                    $("#sendbtnmail").addClass("btn-danger");
                    $("#sendbtnmail").css('cursor','progress');
                }                

            }           
            else alert("Sujet, corps et destinataire(s) obligatoire");
        }

        $( "#sendbtnmailreply" ).click(function()
        {
            sendbtnmailreply();
        });

        function sendbtnmailreply()
        {
            var data = CKEDITOR.instances["chat_messagemail"].getData();
            var subject=$("#mailsuject").val();
            var destinataires=$("#destinataires").val();

            if(data&&subject&&!(jQuery.isEmptyObject(destinataires))) {
                try {
                    // Flager que l'envoit c'est fait
                    tosendmail=false;
                    mailto=destinataires.join(';');
                    mailto=";"+mailto;                    
                    $("#sendbtnmailreply").html("Envoyer");
                    $("#sendbtnmailreply").removeClass("btn-danger");
                    $("#sendbtnmailreply").css('cursor','auto');

                    // Push envent sur le websocket
                    id=$("#sendbtnmailreply").data("id");
                    sendMessage({command: "replychat","message": data, parent: id,  mail: "true", to: mailto, subject: subject})

                    // Vider l'editeur
                    CKEDITOR.instances["chat_message"].setData('');

                    // Cacher la popup
                    $("#sendbymail").bootstrapSwitch('state',false);
                    $('#mymodal-sendmail').modal('hide');
                }
                catch(error) {
                    // L'envoi ne s'est pas fait
                    console.log("Retry to send reply");

                    // On flag le fait de retenter l'envoit à la reconnexion
                    tosendmail=true;

                    // On signal que l'envoi est en cours sur le bouton
                    $("#sendbtnmailreply").html("Envoi en cours");
                    $("#sendbtnmailreply").addClass("btn-danger");
                    $("#sendbtnmailreply").css('cursor','progress');
                }                

            }           
            else alert("Sujet, corps et destinataire(s) obligatoire");
        }

        $(document).on('click', '.delmessage', function()
        {
            delmessage($(this).data("id"));
        });

        function delmessage(id)
        {
            try {
                // Flager que l'envoit c'est fait
                todelete=false;
                idtodelete=null;

                // Push envent sur le websocket
                sendMessage({command: "delchat","id": id});   
            }
            catch(error){
                // Le delete ne s'est pas fait
                console.log("Retry to delete");                

                // On flag le fait de retenter l'envoit à la reconnexion
                todelete=true;
                idtodelete=id;
            }
        }

        $(document).on('click', '.hidemessage', function(){
            hidemessage($(this).data("id"));
        });

        function hidemessage(id)
        {
            $.ajax({
                method: "POST",
                url: "{{ path('app_websocket_message_see') }}",
                data: {
                    id:id
                },
                success: function() {
                    console.log("yo");
                    $("#message-"+id).addClass ("message-see");
                    $("#hidemessage-"+id).remove();

                    if(!$("#unsee").bootstrapSwitch('state')) {
                        $("#message-"+id).hide();
                    }
                    else {
                        $("#message-"+id).show();
                    }
                }            
            }); 
        }

        $(document).on('click', '.btnreplymessage', function(){
            btnreplymessage($(this).data("id"));
        });

        function btnreplymessage(id) {
            $("#replymessage-"+id).toggle();
            $("#replymessage-"+id+" textarea").focus();
        }

        $(document).on('click', '.btnreplymessagemail', function(){
            CKEDITOR.instances["chat_messagemail"].setData("");
            $("#mailsuject").val("{{app.session.get('appname')}} = Notification {{ group.label }}");

            $("#sendbtnmail").hide();
            $("#sendbtnmailreply").show();
            $("#sendbtnmailreply").data("id",$(this).data("id"));
            $('#mymodal-sendmail').modal('show');
            $("#checkalldestinataires").prop( "checked", false );
            $('#destinataires').val("");
            $("#destinataires > option").removeAttr("selected");
            $("#destinataires").trigger("change");                
            $('#destinataires').select2({
                templateResult: formatState,
                templateSelection: formatState,
                sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
            });            
        });


        $(document).on('click', '.sendreply', function(){
            sendreply($(this).data("id"));
        });

        function sendreply(id) {
            try {
                // Flager que l'envoit c'est fait
                tosend=false;
                $("#replymessage-"+id+" a").html("Envoyer");
                $("#replymessage-"+id+" a").removeClass("btn-danger");
                $("#replymessage-"+id+" a").css('cursor','auto');

                // Push envent sur le websocket
                var data = "<p>"+$("#replymessage-"+id+" textarea").val()+"</p>";
                sendMessage({command: "replychat","message": data, parent: id}); 

                // Vider l'editeur
                $("#replymessage-"+id+" textarea").val("");
                $("#replymessage-"+id).hide();
            }
            catch(error) {
                // L'envoi ne s'est pas fait
                console.log("Retry to send");

                // On flag le fait de retenter l'envoit à la reconnexion
                tosend=true;

                // On signal que l'envoi est en cours sur le bouton
                $("#replymessage-"+id+" a").html("Envoi en cours");
                $("#replymessage-"+id+" a").addClass("btn-danger");
                $("#replymessage-"+id+" a").css('cursor','progress');
            }            
            
        }

        function recuplastmsg() {
            console.log("recuplastmsg");

            $.ajax({
                method: "POST",
                url: "{{ path('app_websocket_message_list') }}",
                data: {
                    "id": {{ groupid }},
                },
                success: function(datas) {
                    $.each(datas, function(i,data) {
                        // Le message a-t-il été déposé durant la déconnexion ?
                        if(!$("#message-"+data.id).length) {
                            avatar="{{ asset('uploads/avatar/xxxx') }}";
                            avatar=avatar.replace("xxxx",data.useravatar);
                            html ="<div id='message-"+data.id+"' class='message row message-toread'>";
                            html+="<div class='msgavatar'>";
                            html+="<img style='cursor:pointer' onclick='seeUser("+data.userid+")' id='user_avatar_img' src='"+avatar+"' class='avatar'><br>";
                            if(data.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                                html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+data.id+"' style='cursor: pointer;'></i>";
                            }
                            if (!data.havesee) {
                                html+="<i id='hidemessage-"+data.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+data.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                            }
                            html+="</div>";
                            html+="<div class='msgdiv'>"
                            html+="<div class='msgtitle'>"+data.userlastname+"<br><small>"+new Date(data.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small></div>";
                            html+="<div class='msgtopic'>"+data.message+"</div>";
                            html+="<div id='msgreplys-"+data.id+"' class='msgreplys'>";
                            
                            html+="</div>";
                            html+="<a class='btnreplymessage' data-id='"+data.id+"'>Répondre</a>";
                            html+="<a class='btnreplymessagemail' data-id='"+data.id+"'>Répondre par Mail</a>";
                            html+="<div id='replymessage-"+data.id+"' class='replymessage'>";
                            html+="<textarea></textarea>";
                            html+="<a id='sendreply' class='btn btn-success sendreply' data-id='"+data.id+"'>Envoyer</a>";
                            html+="</div>";
                            html+="</div>";
                            html+="</div>";
                            $(".mychat").prepend(html);                            
                        }

                        $.each(data.childs, function(i,child) {
                            if(!$("#message-"+child.id).length) {
                                html ="<div id='message-"+child.id+"' class='message messagereply message-toread'>";
                                html+=nl2br(child.message);
                                html+="<div style='cursor:pointer' onclick='seeUser("+child.userid+")'><small>"+child.userlastname+"</small></div>";
                                html+="<small>"+new Date(child.submitdate.date).toLocaleDateString("fr-FR", dateoptions)+"</small>";
                                if(child.userid=={{app.user.id}} || '{{ canmanage }}'=='1') {
                                    html+="<i class='delmessage fa fa-trash fa-fw' data-id='"+child.id+"' title='Supprimer' style='cursor: pointer;'></i>";
                                }
                                html+="<i id='hidemessage-"+child.id+"' class='hidemessage fa fa-eye-slash fa-fw' data-id='"+child.id+"' title='Ne plus afficher' style='cursor: pointer;'></i>";
                                html+="</div>";  

                                $("#msgreplys-"+data.id).prepend(html);          
                            }
                        });                        
                    });
                } 
            });            
        }
       
        function addOnline(userid, useravatar, userdisplayname) {
            {% set colorlabel= colormain %}
            {% if border  %}
                {% set colorlabel = colorbody %}
            {% endif %}
            {% if colorbody==colorbodyfont %}
                {% set colorlabel = colorbodyback %}
            {% endif %}


            if(!$("#online"+userid).length) {
                avatar="{{ asset('xxxx') }}";
                avatar=avatar.replace("xxxx",useravatar);

                html = "<span id='online"+userid+"' style='width:70px; display:inline-block; text-align: center; font-size: 10px; color:#{{ colorbodyback }}; text-transform: uppercase; line-height:11px;overflow-wrap: break-word;vertical-align:top;'>";
                html+= "<img style='cursor:pointer; width:40px; height:40px; margin-bottom:5px;' onclick='seeUser("+userid+")' title='"+userdisplayname+"' id='user_avatar_img' src='"+avatar+"' class='avatar'>";
                html+= "<br><span style='color:#{{colorlabel}}'>"+userdisplayname+"</span>";
                html+= "</span>";
                $("#useronline").append(html);
            }
        }
    {% endif %}
</script>

