
{% extends '@CadolesCore/base.html.twig' %}

{% block localstyle %}
    body{overflow-y:hidden}
{% endblock %}

{% block appmenu %}
    <ul class="nav navbar-top-links navbar-left">
        {% for page in pagesadmin %} 
            {% set forcereload=true %}
            {% if page.pagecategory.id==1 %}
                {% set forcereload=page.toreload %}
            {% endif %}

            {% set usage="portal" %}
            {% if loop.first %} {% set usage="accueil" %} {%endif %}

            {% if entity.id is defined and page.id==entity.id %}
                <li id="menupage-{{page.id}}" class="active" style="cursor:pointer">
                    <a onClick="showPage({{ page.id }},{{ page.pagecategory.id }},'{{ page.canupdate }}','{{usage}}','{{forcereload}}',null,'{{page.name}}')">
                        {% if page.fonticon %}
                            <i class="{{ page.fonticon }} fa-faw"></i>&nbsp;
                        {% endif %}                    
                        {{ page.name }}
                    </a>
                </li>
            {% else %}
                <li id="menupage-{{page.id}}">
                    <a style="cursor:pointer" onClick="showPage({{ page.id }},{{ page.pagecategory.id }},'{{ page.canupdate }}','portal','{{forcereload}}',null,'{{page.name}}')">
                        {% if page.fonticon %}
                            <i class="{{ page.fonticon }} fa-faw"></i>&nbsp;
                        {% endif %}                       
                        {{ page.name }}
                    </a>
                </li>
            {% endif %}
        {% endfor %}
    </ul>

    <ul id="pagesuser" class="nav navbar-top-links navbar-left">
        {% for page in pagesuser %}
            {% set forcereload=true %}
            {% if page.pagecategory.id==1 %}
                {% set forcereload=page.toreload %}
            {% endif %}
            

            {% if entity.id is defined and page.id==entity.id %}
                <li id="menupage-{{page.id}}" class="active" style="cursor:pointer">
                    <a onClick="showPage({{ page.id }},{{ page.pagecategory.id }},'{{ page.canupdate }}','user','{{forcereload}}',null,'{{page.name}}')">
                        {% if page.fonticon %}
                            <i class="{{ page.fonticon }} fa-faw"></i>
                        {% else %}
                            <i class="fa fa-user fa-fw"></i>
                        {% endif %}
                        &nbsp;{{ page.name }}
                    </a>
                </li>
            {% else %}
                <li id="menupage-{{page.id}}">
                    <a style="cursor:pointer" onClick="showPage({{ page.id }},{{ page.pagecategory.id }},'{{ page.canupdate }}','user','{{forcereload}}',null,'{{page.name}}')">
                        {% if page.fonticon %}
                            <i class="{{ page.fonticon }} fa-faw"></i>
                        {% else %}
                            <i class="fa fa-user fa-fw"></i>
                        {% endif %}
                        &nbsp;{{ page.name }}
                    </a>
                </li>
            {% endif %}
        {% endfor %}
    </ul>

    <ul id="pagesgroup" class="nav navbar-top-links navbar-left">

    <!-- On regroupe l'ensemble des pages si plus de x groupes -->
    {% set nbgroupregrouped=5 %}
    {% if groupsshared|length > nbgroupregrouped %} 
        <ul id="pagesshared" class="nav navbar-top-links navbar-left">
            <li>
                <a id="menugrouppages" style='cursor:pointer' data-toggle='modal' data-target='#selgrouppages'>
                    <i class="fa fa-users fa-fw"></i>&nbsp;Mes Groupes
                    <span class="caret"></span>
                </a>    
            </li>
        </ul>
    {%else%}
        {% set inmenu=true %}
        {{ include('@CadolesPortal/Page/menugroupe.html.twig') }}
    {% endif %}

    </ul>


    <div id="menupageaction">
        <a id="menuname" style="cursor:pointer;font-size:80%" href=""></a>

        {% if canadd %}
            <a id="menusubmit" style="cursor:pointer" onclick="submitPage()" title='Ajouter une page'><i class='fa fa-plus fa-fw'></i></a>
        {% endif %}
        <a id="menuupdate" style="cursor:pointer;display:none" onclick="updatePage()" title='Modifier une page'><i class='fa fa-file fa-fw'></i></a>
        <a id="menushare" style="cursor:pointer;display:none" onclick="sharePage()" title='Partager une page'><i class='fa fa-share-alt fa-fw'></i></a>
        <a id="menudelete" style="cursor:pointer;display:none" onclick="deletePage()" title='Supprimer une page'><i class='fa fa-trash fa-fw'></i></a>
        <a id="menubookmark" style="cursor:pointer;display:none" onclick="bookmarkPage()" title="Faire de cette page votre page d'accueil"><i class='fa fa-heart fa-fw'></i></a>
        <a id="menuwidgetuser" style='cursor:pointer;display:none' data-toggle='modal' data-target='#selwidgetuser' title='Ajouter un widget'><i class='fa fa-cubes fa-fw'></i></a>
        <a id="menuwidgetgroup" style='cursor:pointer;display:none' data-toggle='modal' data-target='#selwidgetgroup' title='Ajouter un widget'><i class='fa fa-cubes fa-fw'></i></a>
    </div>






  
{% endblock %}

{% block pagewrapper %}
    <div id="pagecontainer" style="margin: 0px -30px;"></div>

    
    {% if activate_widonlyoffice %}
        <iframe src="{{ widonlyoffice_url }}/sso/login" style="display:none"></iframe>
    {% endif %}

    {% set nbgroupregrouped=5 %}
    {% if groupsshared|length > nbgroupregrouped %} 
        <div id="selgrouppages" class="modal fade bs-item-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">MES GROUPES</h4>
                    </div>

                    <div class="modal-body">
                        <a onclick="$('#selgrouppages').modal('hide');" class="btn btn-default" style="margin-bottom:15px">
                            Annuler
                        </a>

                        {% set inmenu=false %}
                        {{ include('@CadolesPortal/Page/menugroupe.html.twig') }}
                    </div>
                </div>
            </div>
        </div>    
    {%endif%}

    <div id="selwidgetuser" class="modal fade bs-item-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">SELECTIONNER UN WIDGET</h4>
                </div>

                <div class="modal-body">
                    <div class="form-group row clearfix">
                        <div class="col-md-12" style="margin-bottom:15px">
                            <a onclick="$('#selwidgetuser').modal('hide');" class="btn btn-default">
                                Annuler
                            </a>
                        </div>  

                        <div class="dataTable_wrapper col-md-12">
                        <table id="dataTables" class="table table-bordered table-striped table-hover">  
                            <thead>
                            <tr>
                                <th width="100px">#</th>
                                <th>Nom</th>
                                <th class="no-sort">Description</th>
                            </tr>
                            </thead>

                            <tbody>
                                {% for widget in widgetsuser %}
                                    <tr>
                                        <td>
                                            <a onClick="selWidget({{ widget.id }})" style="cursor:pointer;">
                                                <img id="widgettype-{{ widget.id }}" class="grid-item-img" height="40" src="/{{ alias }}/{{ widget.icon.label }}" style="padding:2px">
                                            </a>
                                        </td>
                                        <td>{{ widget.name }}</td>
                                        <td>{{ widget.description }}</td>
                                    </tr>
                                {% endfor %}  
                            </tbody>
                        </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>   

    <div id="selwidgetgroup" class="modal fade bs-item-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">SELECTIONNER UN WIDGET</h4>
                </div>

                <div class="modal-body">
                    <div class="form-group row clearfix">
                        <div class="col-md-12" style="margin-bottom:15px">
                            <a onclick="$('#selwidgetgroup').modal('hide');" class="btn btn-default">
                                Annuler
                            </a>
                        </div>  

                        <div class="dataTable_wrapper col-md-12">
                        <table id="dataTables" class="table table-bordered table-striped table-hover">  
                            <thead>
                            <tr>
                                <th width="100px">#</th>
                                <th>Nom</th>
                                <th class="no-sort">Description</th>
                            </tr>
                            </thead>

                            <tbody>
                                {% for widget in widgetsgroup %}
                                    <tr>
                                        <td>
                                            <a onClick="selWidget({{ widget.id }})" style="cursor:pointer;">
                                                <img id="widgettype-{{ widget.id }}" class="grid-item-img" height="40" src="/{{ alias }}/{{ widget.icon.label }}" style="padding:2px">
                                            </a>
                                        </td>
                                        <td>{{ widget.name }}</td>
                                        <td>{{ widget.description }}</td>
                                    </tr>
                                {% endfor %}  
                            </tbody>
                        </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>  

    {%if app.user %}
        <a id="refreshcounter" data-event=""></a>
    {% endif %}

{% endblock %}

{% block localexternalscript %}
    {% if app.user %}
        <script src="/{{alias}}/bundles/goswebsocket/js/vendor/autobahn.min.js"></script>
        <script src="/{{alias}}/bundles/goswebsocket/js/gos_web_socket_client.js"></script>
    {% endif %}
{% endblock %}

{% block localjavascript %}
    var idpage;
    pagebookmark="{{app.session.get("pagebookmark")}}";

    $('document').ready(function(){
        {% if gotoroute is empty %}
            {% for page in pagesadmin %} 
                {% if page.id==entity.id %}
                    {% set usage="portal" %}
                    {% if loop.first %} {% set usage="accueil" %} {%endif %}                
                    showPage({{ page.id }}, {{ page.pagecategory.id }},'{{ page.canupdate }}','{{usage}}',false,null,'{{page.name}}');
                {% endif %}
            {% endfor %}
            
            {% for page in pagesuser %} 
                {% if page.id==entity.id %}
                    showPage({{ page.id }}, {{ page.pagecategory.id }},'{{ page.canupdate }}','user',false,null,'{{page.name}}');
                {% endif %}
            {% endfor %}      
            
            {% for groupshared in groupsshared %}
                {% for page in groupshared.pagesshared %}
                    {% if page.id==entity.id %}
                        showPage({{ page.id }}, {{ page.pagecategory.id }},'{{ page.canupdate }}','group',true,{{groupshared.id}},'{{page.name}}');
                    {% endif %}
                {% endfor %}       
            {% endfor %}
        {% else %}
            var url="{{ path(gotoroute,{id:gotoid}) }}";
            showGoto(url);   
        {% endif %}

        // Rendre les pages user déplacable
        $("#pagesuser").sortable({
            axis: "x",
            forcePlaceholderSize: true,
            placeholder: "placeholder",
            update:  function( event, ui ) {
                $('#pagesuser li').each(function(order) {
                    var idpage=$(this).attr('id').replace("menupage-","");
                    $.ajax({
                        method: "POST",
                        url: "{{ path('cadoles_portal_'~access~'_page_order') }}",
                        data: {
                            id:idpage,
                            order:order
                        }
                    });
                });     
            }
        }); 

        // Initialisation du tableau des widgets selectionnable à la création
        $('.table').DataTable({
            columnDefs: [ { "targets": 'no-sort', "orderable": false }, { "targets": 0, "className": "text-center" } ],
            responsive: true,
            iDisplayLength: 10,
            order: [[ 1, "asc" ]],
        }); 

        {% if app.user and app.session.get("timerefreshnotif") > 0%}
        setInterval(function(){
            loadmsgCounter()
        }, {{(app.session.get("timerefreshnotif")*1000)}});
        {% endif %}
    });

    $(window).resize(function() {
        resizeFrame();
    });
    
    function resizeFrame() {
        var iFrame = document.getElementById('frameContent');

        var heightbody = $('html').height();

        if($('.header').length)
            var heightheader = $('.header').height();
        else
            var heightheader = $('.navbarsmall').height();

        if($('#appmenu').css("display")=="none")
            var heightmenu  = 0;
        else
            var heightmenu  = $('#appmenu').height();
        
        var heightframe = heightbody-heightheader-heightmenu;
        
        $(".pageframe").each(function( index ) {
            $(this).height(heightframe);
        });
    }    

       
    // Affichage des frames associés aux items de bureau
    function showFrameitem(id,url,forcereload) {
        $(".pageframereload").remove();
        $(".pageframe").hide();

        // Si force le rechargement et frame existante on la détruit
        if(forcereload&&$("#frameitem-"+id).length)
            $("#frameitem-"+id).remove();

        // Si la frame en cours existe déjà on l'affiche
        if($("#frameitem-"+id).length)
            $("#frameitem-"+id).show();         
        // Sinon on la génère
        else {
            var myclass="";
            if(forcereload) myclass="pageframereload";
            $("#pagecontainer").append("<iframe onload='this.contentWindow.focus()' id='frameitem-"+id+"' class='pageframe "+myclass+"' src='"+url+"' style='border:none; width:100%'></iframe>");
        }
        
        resizeFrame();
    }

    // Affichages des pages
    function showPage(id,catid,canupdate,usage,forcereload,groupid,pagename) {
        // Sauvegarder la page en cours
        idpage=id;   

        // Cacher toutes les pages
        $(".pageframereload").remove();
        $(".pageframe").hide();

        // Rendre actif le page en cours dans le menu
        $(".navbar-top-links li").removeClass("active");
        $(".dropdown-toggle").removeClass("dropdownactive");

        $("#menupage-"+id).addClass("active");
        $('a[data-group="'+groupid+'"][data-toggle="dropdown"]').addClass("dropdownactive");;
        
        var url="{{ path('cadoles_portal_user_page_view',{id:'xx',usage:'yy','group':'zz'}) }}";
        url=url.replace('xx',id);
        url=url.replace('yy',usage);
        url=url.replace('zz',groupid);

        passurl="{{ path('cadoles_core_home',{id:'xx'}) }}";
        passurl=passurl.replace('xx',id);
        history.pushState('data to be passed', 'Title of the page', passurl);

        // Si force le rechargement et frame existante on la détruit
        if(forcereload&&$("#page-"+id).length)
            $("#page-"+id).remove();

        // Si la frame en cours existe déjà on l'affiche
        if($("#page-"+id).length)
            $("#page-"+id).show();
        // Sinon on la génère
        else {
            var myclass="";
            if(forcereload) myclass="pageframereload";
            $("#pagecontainer").append("<iframe onload='this.contentWindow.focus()' id='page-"+id+"' data-category='"+catid+"' class='pageframe "+myclass+"' src='"+url+"' style='border:none; width:100%'></iframe>");    
        }

        // Détruire le badge associé car normalement de fait on a lu les notif
        if(usage=="group") {
            $("#badge-"+groupid).remove()
        }

        // Nom de la page
        console.log(pagename);
        $("#menuname").html(pagename);

        // Cacher les actions possibles sur la page
        $("#menuupdate").hide();
        $("#menushare").hide();
        $("#menudelete").hide();
        $("#menubookmark").hide();
        $("#menuwidgetuser").hide();
        $("#menuwidgetgroup").hide();

        if(canupdate) {
            $("#menuupdate").show();
            $("#menushare").show();
            $("#menudelete").show();
        }

        {% if app.user %}
            
            if(id==pagebookmark) {
                $("#menubookmark").css("color","red");
                $("#menubookmark").attr("title","Ne plus faire de cette page votre page d'accueil")
            }
            else {
                $("#menubookmark").css("color","");
                $("#menubookmark").attr("title","Faire de cette page votre page d'accueil")
            }

            $("#menubookmark").show();
        {% endif %}

        // Si page de type widget on affiche la selection des widgets à insérer
        if($("#page-"+id).data('category')==2&&canupdate) {
            if(usage=="user") $("#menuwidgetuser").show();    
            if(usage=="group") $("#menuwidgetgroup").show();    

        }

        // On resize les frame
        resizeFrame();

        // Mettre le focus dans la frame
        //$("#page-"+id).contentWindow.focus();
    }

    // Affichages des pages
    function showGoto(url) {
        $("#pagecontainer").append("<iframe onload='this.contentWindow.focus()' id='goto' class='pageframe pageframereload' src='"+url+"' style='border:none; width:100%'></iframe>");    

        // On resize les frame
        resizeFrame();
    }


    function submitPage() {
        var url="{{ path('cadoles_portal_'~access~'_page_submit') }}";
        $(location).attr('href',url);
    }  

    function updatePage() {
        if($("#page-"+idpage).length) {
            var url="{{ path('cadoles_portal_'~access~'_page_update',{id:'xx'}) }}";
            url=url.replace('xx',idpage);

            $(location).attr('href',url);
        }
    }    

    function sharePage() {
        if($("#page-"+idpage).length) {
            var url="{{ path('cadoles_portal_'~access~'_page_share',{id:'xx'}) }}";
            url=url.replace('xx',idpage);

            $(location).attr('href',url);
        }
    } 

    function deletePage() {
        if($("#page-"+idpage).length) {
            if (confirm('Êtes-vous sûr de vouloir supprimer ?')) {
                var url="{{ path('cadoles_portal_'~access~'_page_delete',{id:'xx'}) }}";
                url=url.replace('xx',idpage);

                $(location).attr('href',url);
            }
        }
    }  

    function bookmarkPage() {
        {% if app.user %}
            if($("#page-"+idpage).length) {
                if(pagebookmark==idpage)
                    confirmtext="Votre page d'accueil redevient l'accueil général de {{ app.session.get("appname") }}.";
                else
                    confirmtext="Cette page sera votre page d'acueil à l'ouverture de {{ app.session.get("appname") }}, vous pourrez à tout moment changer de page d'accueil.";

               if (confirm(confirmtext)) {
                    $.ajax({
                        method: "POST",
                        url: "{{ path('cadoles_core_user_preference') }}",
                        data: {
                            id:0,
                            key:'pagebookmark',
                            value: idpage
                        },
                        success: function() {
                            if(pagebookmark==idpage) {
                                pagebookmark="";
                                $("#menubookmark").css("color","");
                                $("#menubookmark").attr("title","Faire de cette page votre page d'accueil")
                            }
                            else {
                                pagebookmark=idpage;
                                $("#menubookmark").css("color","red");
                                $("#menubookmark").attr("title","Ne plus faire de cette page votre page d'accueil")
                            }
                        }            
                    });
                }
            }
        {% endif %}   
    }  

    // Création d'un widget selectionné
    function selWidget(idwidgettype) {
        var url="{{ path('cadoles_portal_user_pagewidget_widget_sumbit',{idpage:'yy',idwidgettype:'xx'})}}";
        url=url.replace('xx',idwidgettype);
        url=url.replace('yy',idpage);

        $(location).attr('href', url);
    };      

	function loadmsgCounter() {      

        $.ajax({
            method: "POST",
            url: "{{ path('cadoles_portal_user_page_ajax_msgcounter') }}",
            success: function(data) {
                $.each(data, function(group, counter) {
                    menu=$("a[data-group='"+group+"']");
                    if(menu.length) {
                        if(menu.children(".badge").length) {
                            if(counter==0) 
                                menu.remove();
                            else
                                menu.children(".badge").html(counter);
                        }
                        else if(counter>0)
                            menu.append("<span id='badge-"+group+"' class='badge'>"+counter+"</span");
                    }                    
                });  
            } 
        });
	}
{% endblock %}
