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

{% block localstyle %}
    {% if look=="list" %}
    #R1C1:first-child {
        margin-top: 30px;
    }

    .widget-mini .logo {
        background-color: #{{color["main"]}};
        padding: 3px;
        border-radius: 100%;        
    }
    {% endif %}
{% endblock %}
{% block pagewrapper %}
    {% if access=="config" %}
        <div class="pagemenu">
            {% set template="" %}
            {% if mode=="viewtemplate" %}
                {% set template="template" %}
            {% endif %}

            <a href="{{ path('cadoles_portal_config_page'~template~'_view', {id:entity.id})}}">{{ entity.name }}</a>

            <a href='{{ path('cadoles_portal_config_page'~template~'_update', {id:entity.id}) }}' title='Modifier le panel'><i class='fa fa-cog fa-fw'></i></a>
            <a href='{{ path('cadoles_portal_config_page'~template~'_delete', { id: entity.id }) }}' data-method='delete' data-confirm='Êtes-vous sûr de vouloir supprimer ?' title='Supprimer le panel'><i class='fa fa-trash fa-fw'></i></a>
            <a href='' style='cursor:pointer' data-toggle='modal' data-target='#selwidget' title='Ajouter un widget'><i class='fa fa-cubes fa-fw'></i></a>
        </div>
    {% endif %}

    <div id="loader"><img src="/{{alias}}/bundles/cadolescore/images/loading.gif" width="50px"></div>

    <div id="gridtemplate" style="{% if entity.maxwidth>0%} max-width:{{ entity.maxwidth }}px; margin:auto; {% endif %} margin-bottom:30px">

    </div>  

    <div id="tolocalize" style="display:none">
        {% for pagewidget in entity.pagewidgets %}
            <a href="{{ url(pagewidget.widget.routeview|replace({'_config_':'_'~access~'_'}),{id:pagewidget.id,by:mode,usage:usage,group:group,look:look,selwidget:selwidget}) }}"></a>
            {{ render(url(pagewidget.widget.routeview|replace({'_config_':'_'~access~'_'}),{id:pagewidget.id,by:mode,usage:usage,group:group,look:look,selwidget:selwidget})) }}
        {% endfor %}
    </div>

    {% if access=="config" %}
        <div id="selwidget" 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="$('#selwidget').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 widgets %}
                                        <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>
    {% endif %}
{% endblock %}

{% block localjavascript %}
    var optiongrid={columnWidth: '.grid-sizer',itemSelector: '.grid-item', gutter: '.grid-gutter-sizer'};

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

        // Création de la grille des widgets
        {% if look == "list" %}
            var template = '{"rows":[{"id":0,"cols":[{"id":0,"size": 1,"rows":[]},{"id":1,"size": 11,"rows":[]}]}]}';
        {% else %}
            var template = '{{ entity.template | raw }}';
        {% endif %}

        // Template de base
        if(template=="") {
            myrow ="<div class='row'>";
            myrow+="<div class='colcontainer'>";
            myrow+="<div id='R1C1' class='col col-md-4'></div>"
            myrow+="<div id='R1C2' class='col col-md-4'></div>"
            myrow+="<div id='R1C3' class='col col-md-4'></div>"
            myrow+="</div>"

            $("#gridtemplate").append(myrow);
        }
        // Interprétation du template sauvegardé
        else {
            var json = jQuery.parseJSON(template);
            var mygrid="";
            var row01=0;

            $.each(json.rows, function( index, rownv01 ) {
                row01++;
                col01=0;
                mygrid+="<div class='row'>";
                mygrid+="<div class='colcontainer'>";

                $.each(rownv01.cols, function( index, colnv01 ) {
                    col01++;
                    var row02=0;

                    mygrid+="<div id='R"+row01+"C"+col01+"' class='col col-md-"+colnv01.size+"'>";
                    mygrid+="<div class='rowcontainer'>";

                    $.each(colnv01.rows, function( index, rownv02 ) {
                        row02++;
                        col02=0;

                        mygrid+="<div class='row'>";
                        mygrid+="<div class='colcontainer'>";   
                        $.each(rownv02.cols, function( index, colnv02 ) { 
                            col02++;
                            mygrid+="<div id='R"+row01+"C"+col01+"R"+row02+"C"+col02+"' class='col col-md-"+colnv02.size+"'></div>";
                        });
                        mygrid+="</div>";
                        mygrid+="</div>";                          
                    });

                    mygrid+="</div>";    
                    mygrid+="</div>";      
                });

                mygrid+="</div>";
                mygrid+="</div>";
            });

            $("#gridtemplate").append(mygrid);
        }

        // On déplace les widgets à leur emplacement
        $("#tolocalize").children(".widget").each(function( element ) {
            {% if look=="list" %}
                if($(this).data("id")=="{{selwidget}}") {
                    $(this).appendTo('#R1C2');
                }
                else
                    $(this).appendTo('#R1C1');
                
            {% else %}
                if($('#'+$(this).attr("loc")).length)
                    $(this).appendTo('#'+$(this).attr("loc"));
                else
                    $(this).appendTo('#R1C1');
            {% endif %}
        });

        // On ajoute un widget vide à chaque colonne
        $("#gridtemplate .col").each(function(element) {
            $("<div class='widgetempty'>&nbsp;</div>").appendTo($(this));
        });

        {% if canupdate and look!="list" %}
            // Mettre une taille mini de colonne sinon on ne pourra pas déplacer le widget dans la colonne
            $(".colcontainer .col").css("min-height","80px");

            // Cursor move sur les widgets header
            $(".widgetheader").css("cursor","move");

            // Rendre les widgets déplacable
            $("#gridtemplate .col").sortable({
                connectWith: "#gridtemplate .col",
                handle: '.widgetheader',
                placeholder: "widget widgetplacehorder",
                tolerance: "pointer",
                cursor: "move",
                opacity: 0.6,      
                start: function( event, ui ) {
                    ui.placeholder.css("height",ui.item.height());
                    $(".widgetbody").hide();
                    $(".colcontainer .col").css("border","1px solid #cdcdcd");
                    $(".colcontainer .col").css("padding-bottom","15px");
                },
                stop: function( event, ui ) {
                    $(".widgetbody").show();
                    $(".colcontainer .col").css("border","none");   
                    $(".colcontainer .col").css("padding-bottom","");

                    // Création des grilles d'items
                    var grid = $('.grid').masonry(optiongrid);        
                },
                update: updateLocalisation
            });
        {% endif %}

        
        // Création des grilles d'items
        $('body').imagesLoaded(function() {
            var grid = $('.grid').masonry(optiongrid);        
        });

        // Preview item de bureau
        $( ".grid .item-preview" ).click(function() {
            if($(this).parent().children(".grid-item-body").css('display') == 'none') {
                $(this).html('<i style="color: #FFF" class="fa fa-minus" title="Informations sur ce service"></i>');
                heightbody=$(this).parent().children(".grid-item-body").height()+30;
                heightitem=$(this).parent().parent().height();


                $(this).parent().children(".grid-item-body").show();
                $(this).parent().parent().css("width","100%");

                $(this).parent().parent().css("height",heightitem+heightbody);
                $(this).parent().children(".grid-item-content").css("height",heightitem+heightbody);
                $(this).parent().children(".item-preview").css("height",heightitem+heightbody);

                var grid = $('.grid').masonry(optiongrid);        
            }
            else {
                $(this).html('<i style="color: #FFF" class="fa fa-info" title="Informations sur ce service"></i>');

                $(this).parent().children(".grid-item-body").hide();
                $(this).parent().parent().css("width","");
                $(this).parent().parent().css("height","");
                $(this).parent().children(".grid-item-content").css("height","");
                $(this).parent().children(".item-preview").css("height","");

                var grid = $('.grid').masonry(optiongrid);
            }
        });

        // badgeurl item
        $(".itembadgeurl").each(function() {
            mybadge=$(this);
            $.ajax({
                method: "GET",
                url: $(this).data("url"),
                success: function(data) {
                    mybadge.append(data);
                }            
            });
        });

        // Création des slick
        slick();

        // Sur le click des titres de widgets ouvrir / fermer le widget
        $( ".widgetheader .title" ).click(function() {
            showhideWidget(this);
        });        
        $( ".widgetheader .logo" ).click(function() {
            showhideWidget(this);
        });  

        // Sur click item à sonder
        {% if activate_widsonde %}
        $( ".linktosonde" ).click(function() {
            title=$(this).attr("data-sondetitle");
            service=$(this).attr("data-sondeservice");
            EnvoleClickSondes($(this),title,service);
        });        
        {% endif %}

        // balise h des widget editor
        $(".widget-editor .widgetbody :header").css("color",$(".widgetbody").css("color"));

        // cacher le loader
        $("#loader").hide();
    });

    // function slick
    function slick() {
        $('.slick').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            autoplay: true,
            //autoplaySpeed: ($(this).data("interval")*1000),
            dots: false,
            touchMove: false,
            pauseOnHover: false,
            fade: true,
            cssEase: 'linear',
            prevArrow: '<button type="button" class="slick-prev"></button>',
            nextArrow: '<button type="button" class="slick-next"></button>',
        });
    }    

    function showhideWidget(elem) {
        widget=$(elem).parent().parent();
        idwidget= widget.data("id");
        if(widget.children(".widgetbody").css("display")=='block')
            value=false;
        else
            value=true;
        
        {% if app.user %}
            {% if entity.fgpreference %}
                $.ajax({
                    method: "POST",
                    url: "{{ path('cadoles_core_user_preference') }}",
                    data: {
                        id:idwidget,
                        key:'widgetshowhide',
                        value:value
                    }          
                });
            {% endif %}

            // on récupère le parent widget conteneur
            widget=$(elem).parent().parent();
            //console.log(widget.children(".widgetbody").css("display"));
            widget.children(".widgetbody" ).toggle();

            // On recalcule les grilles
            var grid = $('.grid').masonry(optiongrid);  
        {% endif %}
    }

    // Modification de la localisation d'un widget
    function updateLocalisation() {
		$('.colcontainer .col').each(function(index) {
            var idloc=$(this).attr('id');
            $(this).children(".widget").each(function(order){
                var idwidget=$(this).data('id');
                $.ajax({
                    method: "POST",
                    url: "{{ path('cadoles_portal_'~access~'_pagewidget_order') }}",
                    data: {
                        idwidget:idwidget,
                        order:order,
                        idloc:idloc
                    }
                });
            });
        });
    }

    // Création d'un widget selectionné
    function selWidget(idwidgettype) {
        var url="{{ path('cadoles_portal_'~access~'_pagewidget_widget_sumbit',{idpage:entity.id,idwidgettype:'xx','by':mode})}}";
        url=url.replace('xx',idwidgettype);

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

    // Modifciation d'un widget
    function modWidget(idwidget) {

        var url="{{ path('cadoles_portal_'~access~'_pagewidget_widget_update',{idpage:entity.id,idwidget:'xx',group:group,usage:usage,by:mode})}}";
        url=url.replace('xx',idwidget);
        url=url.replace(/&amp;/g,"&");

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

    // Suppression d'un widget
    function delWidget(idwidget) {
        var txt;
        var r = confirm("ATTENTION\nConfirmez-vous la suppression de ce widget ?\n\nL'ensemble du contenu sera définitivement perdu !!");
        if (r == true) {
            $.ajax({
                method: "POST",
                url: "{{ path('cadoles_portal_'~access~'_pagewidget_delete') }}",
                data: {
                    idwidget:idwidget
                }
            });

            $(".widget[data-id="+idwidget+"]").remove();
        }
    }  

    // Changer widget
    function changeWidget(idwidget,key,value) {
        {% if app.user %}
        if(key=="modedesktop") {
            value=value+1;
            console.log(value);
            if(value==4) value=0;
            console.log(value);
        }

        $.ajax({
            method: "POST",
            url: "{{ path('cadoles_core_user_preference') }}",
            data: {
                id:idwidget,
                key:key,
                value:value
            },
            success: function() {
                location.reload();
            }            
        });
        {% endif %}
    }  

    // Aggrandir widget
    function bigWidget(idwidget) {
        var url="{{ path('cadoles_portal_'~access~'_page_view',{id:entity.id,group:group,usage:usage,by:mode,look:'list',selwidget:'xx'})}}";
        
        url=url.replace('xx',idwidget);
        url=url.replace(/&amp;/g,"&");

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

    // Réduire widget
    function smallWidget(idwidget) {
        var url="{{ path('cadoles_portal_'~access~'_page_view',{id:entity.id,group:group,usage:usage,by:mode,look:'view',selwidget:'xx'})}}";
        
        url=url.replace('xx',idwidget);
        url=url.replace(/&amp;/g,"&");

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

    // Ajout d'un bookmark
    function addBookmark(idwidget,touser) {
        var url="{{ path('cadoles_portal_'~access~'_bookmark_submit',{idpage:entity.id,idwidget:'xx',touser:'yy',group:group,usage:usage,by:mode})}}";
        url=url.replace('xx',idwidget);
        url=url.replace('yy',touser);
        url=url.replace(/&amp;/g,"&");

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

    // Modifciation d'un bookmark
    function modBookmark(idbookmark) {
        var url="{{ path('cadoles_portal_'~access~'_bookmark_update',{idpage:entity.id,id:'xx',group:group,usage:usage,by:mode})}}";

        url=url.replace('xx',idbookmark);
        url=url.replace(/&amp;/g,"&");

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

    // Ajouter un item aux bookmark
    function heartBookmark(iditem) {
        var idbookmark;

        $.ajax({
            method: "POST",
            url: "{{ path('cadoles_portal_user_bookmark_heart') }}",
            data: {
                iditem:iditem
            },
            success: function(idbookmark) {
                 location.reload();
            }            
        });

    }

    // Supprimer un bookmark
    function delBookmark(idbookmark) {
        if (confirm('Êtes-vous sûr de vouloir supprimer cet item ?')) {
            var url="{{ path('cadoles_portal_'~access~'_bookmark_delete',{idpage:entity.id,id:'xx',group:group,usage:usage,by:mode})}}";

            url=url.replace('xx',idbookmark);
            url=url.replace(/&amp;/g,"&");

            $.ajax({
                method: "POST",
                url: url,
                success: function(idbookmark) {
                    location.reload();
                }            
            });
        }
    }

    // Supprimer un fichier 
    function delFile(directory,filename) {
        var r = confirm("Confirmez-vous la suppression de ce fichier ?");
        if (r == true) {        
            $.ajax({
                method: "POST",
                url: "{{ path('cadoles_core_'~access~'_file_delete') }}",
                data: {
                    directory:directory,
                    filename:filename
                },
                success: function() {
                    location.reload();
                }            
            });        
        }
    }

    // Liste des slides
    function listSlide(idwidget) {
        var url="{{ path('cadoles_portal_'~access~'_slide_list',{idpage:entity.id,idwidget:'xx',group:group,usage:usage,by:mode})}}";
        
        url=url.replace('xx',idwidget);
        url=url.replace(/&amp;/g,"&");
        
        $(location).attr('href', url);
    }    

    // Ajustement des frames
	function AjustFrame() {
		$('.frameajust').iframeAutoHeight({
			minHeight: 500, // Sets the iframe height to this value if the calculated value is less
			heightOffset: 0, // Optionally add some buffer to the bottom
			callback: function(callbackObject) { $(this).parent().css("height",callbackObject.newFrameHeight) ;}
		});

        if($(".frameitem").length>0) {
            var heightbody = $('html').height();
            var heightheader = $('.header').height();
            if($('.pagemenu').css("display")=="none")
                var heightmenu  = 0;
            else
                var heightmenu  = $('.pagemenu').height();

            var heightframe = heightbody-heightheader-heightmenu;

            $(".frameitem").height(heightframe);
        }
        
	}    

    // Affichage des frames associés aux items de bureau
    function showFrameitem(id,url,forcereload) {
        {% if access=="user" %}
            window.parent.showFrameitem(id,url,forcereload);
        {% else %}
            $("#gridtemplate").hide();
            $("body").css("overflow-y","hidden");

            if($("#frameitem-"+id).length) {
                if(forcereload) {
                    $("#frameitem-"+id).attr("src",url);
                }
                $("#frameitem-"+id).show();
            }
            else {
                $("#gridtemplate").before("<iframe id='frameitem-"+id+"' class='frameitem' src='"+url+"'></iframe>");
            }
        {% endif %}
    }

    // Affichage d'un Flux 
    function showFlux(idwidget, id) {
        if(id=="all")
            $(".widget[data-id="+idwidget+"]").find(".feed").show();
        else {
            $(".widget[data-id="+idwidget+"]").find(".feed").hide();
            $(".widget[data-id="+idwidget+"]").find(".flux-"+id).show();
        }

        var grid = $('.grid').masonry(optiongrid);         
    }

    // Affichage des items d'une catégorie
    function showItemCat(idwidget, id) {
        $(".widget[data-id="+idwidget+"]").find(".grid-sizer").show();

        $(".widget[data-id="+idwidget+"]").find("#searchitems").val("");
        if(id=="all") {
            $(".widget[data-id="+idwidget+"]").find(".grid-item").show();
            $(".widget[data-id="+idwidget+"]").find(".bookmark-container").show();
            $(".widget[data-id="+idwidget+"]").find(".itemcategory-container").show();
        }
        else if(id=="fav") {
            $(".widget[data-id="+idwidget+"]").find(".grid-item").show();
            $(".widget[data-id="+idwidget+"]").find(".bookmark-container").show();
            $(".widget[data-id="+idwidget+"]").find(".itemcategory-container").hide();
        }
        else {
            $(".widget[data-id="+idwidget+"]").find(".grid-item").show();
            $(".widget[data-id="+idwidget+"]").find(".bookmark-container").hide();
            $(".widget[data-id="+idwidget+"]").find(".itemcategory-container").hide();
            $(".widget[data-id="+idwidget+"]").find("[data-idcategory="+id+"]").show();

            
            
            /* Recherche
            $(".widget[data-id="+idwidget+"]").find(".bookmark-container").show();
            $(".widget[data-id="+idwidget+"]").find(".itemcategory-container").show();
            $(".widget[data-id="+idwidget+"]").find(".grid-item").hide();
            $(".widget[data-id="+idwidget+"]").find(".grid-item[data-title*='Eportfolio']").show();
            */
        }
        

        var grid = $('.grid').masonry(optiongrid);      
    }

    // Affichage des items d'une catégorie
    function searchItem(idwidget, label) {
        $(".widget[data-id="+idwidget+"]").find(".bookmark-container").show();
        $(".widget[data-id="+idwidget+"]").find(".itemcategory-container").show();
        if(label=="") {
            $(".widget[data-id="+idwidget+"]").find(".grid-item").show();
            $(".widget[data-id="+idwidget+"]").find(".grid-title").show();
            $(".widget[data-id="+idwidget+"]").find(".grid-sizer").show();
        }
        else {
            $(".widget[data-id="+idwidget+"]").find(".grid-title").hide();
            $(".widget[data-id="+idwidget+"]").find(".grid-item").hide();
            $(".widget[data-id="+idwidget+"]").find(".grid-sizer").hide();

            items=$(".widget[data-id="+idwidget+"]").find(".grid-item[data-title*='"+label.toLowerCase()+"']");
            if(items.length) {
                items.show();
                items.each(function() {
                    category=$(this).data("idcategory");
                    $(".widget[data-id="+idwidget+"]").find("h3[data-idcategory="+category+"]").show();
                    $(".widget[data-id="+idwidget+"]").find(".grid-sizer[data-idcategory="+category+"]").show();
                });
                //
                
            }
        }
        

        var grid = $('.grid').masonry(optiongrid);      
    }      

    // Place un message en lu
    function hideMessage(id) {
        $.ajax({
            method: "POST",
            url: "{{ path('cadoles_websocket_message_see') }}",
            data: {
                id:id
            },
            success: function() {
                $(".msg-"+id).remove();
                var ele = $(".msg-hidden").first();
                ele.show();
                ele.removeClass("msg-hidden");

                var grid = $('.grid').masonry(optiongrid);  

            }            
        }); 
    }

    // Place un message en lu
    function hideAlert(id) {
        $.ajax({
            method: "POST",
            url: "{{ path('cadoles_portal_user_alert_read') }}",
            data: {
                id:id
            },
            success: function() {
                $("#alert-"+id).remove();
                var grid = $('.grid').masonry(optiongrid);  
            }            
        }); 
    }

{% endblock %}
