<inserisci-percorso>
    <div class="page-header header-percorsi">
        <div class="row">
            <div class="col-md-6">
                <h1 if="{ opts.tipo == ISTITUZIONALE }">{ percorso ? "SCHEDA PERCORSO ISTITUZIONALE" : 'INSERISCI PERCORSO ISTITUZIONALE' }</h1>
                <h1 if="{ opts.tipo == VISTADACASA }">{ percorso ? "SCHEDA PERCORSO DA CASA" : 'INSERISCI PERCORSO DA CASA' }</h1>
                <h1 if="{ opts.tipo == POP }">{ percorso ? "SCHEDA PERCORSO POP" : 'INSERISCI PERCORSO POP' }</h1>
                <h1 if="{ opts.tipo == FUORICARRARA }">{ percorso ? "SCHEDA ITINERARIO FUORI CARRARA" : 'INSERISCI ITINERARIO FUORI CARRARA' }</h1>
                <h1 if="{ opts.tipo == TEMPORANEA }">{ percorso ? "SCHEDA MOSTRA TERMPORANEA" : 'INSERISCI MOSTRA TEMPORANEA' }</h1>
            </div>
            <div class="col-md-6">
                <p if="{ opts.tipo == ISTITUZIONALE }" class="breadcrump">Home > Percorsi > <a href="/visualizza-percorsi?tipo={ ISTITUZIONALE }">Visualizza percorsi istutuzionali ></a> { percorso ? "Scheda percorso istutuzionale" : "Nuova percorso istutuzionale"}</p>
                <p if="{ opts.tipo == VISTADACASA }" class="breadcrump">Home > Percorsi > <a href="/visualizza-percorsi?tipo={ VISTADACASA }">Visualizza percorsi da casa ></a> { percorso ? "Scheda percorso da casa" : "Nuova percorso da casa"}</p>
                <p if="{ opts.tipo == POP }" class="breadcrump">Home > Percorsi > <a href="/visualizza-percorsi?tipo={ POP }">Visualizza percorsi pop ></a> { percorso ? "Scheda percorso POP" : "Nuova percorso POP"}</p>
                <p if="{ opts.tipo == FUORICARRARA }" class="breadcrump">Home > Percorsi > <a href="/visualizza-percorsi?tipo={ FUORICARRARA }">Visualizza Itinerari fuori Carrara ></a> { percorso ? "Scheda itinerario fuori Carrara" : "Nuovo itinerario fuori Carrara"}</p>
                <p if="{ opts.tipo == TEMPORANEA }" class="breadcrump">Home > Percorsi > <a href="/visualizza-percorsi?tipo={ TEMPORANEA }">Visualizza mostre temporanee ></a> { percorso ? "Scheda mostra temporanea" : "Nuova mostra temporanea"}</p>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="box scheda" data-widget="box-widget">
            <div class="box-header">
                <h3 if="{ opts.tipo == ISTITUZIONALE }" class="box-title">DATI DEL PERCORSO ISTITUZIONALE</h3>
                <h3 if="{ opts.tipo == VISTADACASA }" class="box-title">DATI DEL PERCORSO DA CASA</h3>
                <h3 if="{ opts.tipo == POP }" class="box-title">DATI DEL PERCORSO POP</h3>
                <h3 if="{ opts.tipo == FUORICARRARA }" class="box-title">DATI DELL'ITINERARIO FUORI CARRARA</h3>
                <h3 if="{ opts.tipo == TEMPORANEA }" class="box-title">DATI DELLA MOSTRA TEMPORANEA</h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                </div>
            </div>
            <div class="box-body">
                <form role="form" id="form-percorso">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <p>Titolo IT</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="text" placeholder="" name="title_it" value="{ percorso ? percorso.get('title_it') : '' }">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <p>Titolo EN</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="text" placeholder="" name="title_en" value="{ percorso ? percorso.get('title_en') : '' }">
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == ISTITUZIONALE || opts.tipo == POP }" class="row">
                                    <div class="col-md-4">
                                        <p>Tempo stimato</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <select name="timing" class="form-control select2" value="{ percorso ? percorso.get('timing') : '' }">
                                                <option value="30">30 minuti</option>
                                                <option value="60">60 minuti</option>
                                                <option value="120">2 ore</option>
                                                <option value="180">Pi&ugrave; di 2 ore</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == POP }" class="row">
                                    <div class="col-md-4">
                                        <p>Colore</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="text" placeholder="Codice esadecimale del colore (senza '#')" name="color" value="{ percorso ? percorso.get('color') : '' }">
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == TEMPORANEA }" class="row">
                                    <div class="col-md-4">
                                        <p>Date di inizio e fine</p>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <div class="input-group date">
                                                <div class="input-group-addon">
                                                    <i class="far fa-calendar-alt" title="Data inizio"></i>
                                                </div>
                                                <input type="text" class="form-control input-sm pull-right datepicker" name="start_date" value="{ percorso ? formatDate(percorso.get('start_date')) : '' }">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <div class="input-group date">
                                                <div class="input-group-addon">
                                                    <i class="far fa-calendar-alt" title="Data fine"></i>
                                                </div>
                                                <input type="text" class="form-control input-sm pull-right datepicker" name="end_date" value="{ percorso ? formatDate(percorso.get('end_date')) : '' }">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == TEMPORANEA }" class="row">
                                    <div class="col-md-4">
                                        <p>Ticket link IT</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="url" placeholder="Link al sistema di ticket IT" name="ticket_link_it" value="{ percorso ? percorso.get('ticket_link_it') : '' }">
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == TEMPORANEA }" class="row">
                                    <div class="col-md-4">
                                        <p>Ticket link EN</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="url" placeholder="Link al sistema di ticket EN" name="ticket_link_en" value="{ percorso ? percorso.get('ticket_link_en') : '' }">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <p>Descrizione IT</p>
                                        <p class="subtitle">(max 250 catatteri)</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <div id="description_it"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <p>Descrizione EN</p>
                                        <p class="subtitle">(max 250 catatteri)</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <div id="description_en"></div>
                                        </div>
                                    </div>
                                </div>
                                <div if="{ opts.tipo == VISTADACASA || opts.tipo == FUORICARRARA }" class="row">
                                    <div class="col-md-4">
                                        <p>Ordinamento</p>
                                    </div>
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <input class="form-control" type="number" placeholder="Posizione" name="position" value="{ percorso ? percorso.get('position') : '' }">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <div class="img-container">
                                        <img id="image" class="medium" src="{ percorso && percorso.get('data') ? percorso.get('data').medium.url : '/assets/img/img-plus.png' }"  title="Clicca sull'immagine per cambiare l'immagine">
                                        <div class="upload-btn-wrapper custom-file-upload">
                                            <button type="button" class="btn btn-sm btn-info btn-flat">Modifica l'immagine
                                                <input type="file" name="image" /></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <input type="hidden" name="id" value="{ percorso ? percorso.id : '' }">
                    <input type="hidden" name="source" value="{ opts.tipo }">
                </form>
            </div>
            <div class="box-footer">
                <button type="button" class="btn btn-sm btn-primary btn-flat pull-right" id="salva" onclick="{
                            save
                        }"
                        data-saving-text="<i class='fa fa-spinner fa-spin'></i> Salvataggio in corso"
                        data-error-text="<i class='fa fa-ban'></i> Errore nel salvataggio"
                        data-saved-text="<i class='fa fa-check'></i> Salvato">SALVA MODIFICHE</button>
            </div>
        </div>
        <!-- /.box -->

        <div if="{ percorso && opts.tipo == TEMPORANEA }" class="box scheda" data-widget="box-widget">
            <div class="box-header">
                <h3 class="box-title">MULTIMEDIA AGGIUNTIVI</h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                </div>
            </div>
            <div class="box-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="media-type">
                            <p>VIDEO</p>
                        </div>
                        <form role="form" id="form-video">
                            <div class="row">
                                <div class="col-md-4">
                                    <p>Link video Youtube</p>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <input class="form-control" type="url" placeholder="https://www.youtube.com/watch?v=..." name="youtube" value="{ video ? video.get('data').youtube.url : '' }">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <input type="hidden" name="id" value="{ video ? video.id : '' }">
                                    <input type="hidden" name="type_class" value="video">
                                    <input type="hidden" name="percorso_id" value="{ opts.id_percorso }">
                                    <button type="button" class="btn btn-sm btn-primary btn-flat" onclick="{
                                                savevideo
                                            }"><i class="far fa-save"></i></button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="col-md-6">
                        <form role="form" id="form-gallery">
                            <div class="media-type">
                                <p>GALLERY</p>
                                <div id="gallery-container" class="clearfix">
                                    <div class="gallery-item" data-id="new">
                                        <label for="uploadgallery">
                                            <i class="fas fa-plus"></i>
                                        </label>
                                        <input id="uploadgallery" class='hidden' type="file" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div if="{ percorso }" class="box scheda" data-widget="box-widget">
            <div class="box-header">
                <h3 if="{ opts.tipo == ISTITUZIONALE }" class="box-title">LE TAPPE DEL PERCORSO ISTITUZIONALE</h3>
                <h3 if="{ opts.tipo == VISTADACASA }" class="box-title">LE TAPPE DEL PERCORSO DA CASA</h3>
                <h3 if="{ opts.tipo == POP }" class="box-title">LE TAPPE DEL PERCORSO POP</h3>
                <h3 if="{ opts.tipo == FUORICARRARA }" class="box-title">LE TAPPE DELL'ITINERARIO FUORI CARRARA</h3>
                <h3 if="{ opts.tipo == TEMPORANEA }" class="box-title">LE TAPPE DELLA MOSTRA</h3>
                <!--<div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                </div>-->
            </div>
            <div class="box-body">
                <ul id="lista-tappe">
                    <li each="{ tappe }" class="draggable-element">
                        <input type="hidden" value="{ id }" name="tappa_id"/>
                        <div class="box scheda">
                            <div class="box-header">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <h3 class="box-title">TAPPA { position < 10 ? ("0" + position) : position }</h3>
                                    </div>
                                    <div class="col-lg-3">
                                        <img class="thumb" src="{ file }">
                                    </div>
                                    <div class="col-lg-5 col-md-4">
                                        <p class="box-title-opera">{ opera_title_it }</p>
                                    </div>
                                    <div class="col-lg-2 col-md-2 text-right">
                                        <button type="button" class="btn minus-icon" data-toggle="collapse" data-target="{ id }">
                                            <i class="fas fa-plus"></i></button>
                                        <button type="button" class="btn trash-icon" onclick="{
                                                    deleteTappa
                                                }"><i class="fa fa-trash "></i></button>
                                    </div>
                                </div>
                            </div>
                            <div id="{ id }" data-tappaid="{ id }" class="box-body collapse out">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="text-center add-contenuto">
                                            <button type="button" id="addContenuto" onclick="{
                                                        addContenuto
                                                    }" class="btn btn-flat pull-center">AGGIUNGI CONTENUTO</button>
                                            <input type="hidden" value="{ id }" name="add_to_tappa_id"/>
                                        </div>
                                    </div>
                                </div>
                                <table class="table display dataTable no-footer dtr-inline " style="width: 100%; display: table;" role="grid" aria-describedby="tbl_contenuti_info">
                                    <thead>
                                        <tr role="row">
                                            <th class="dt-body-center" tabindex="0" aria-controls="tbl_contenuti" style="width: 10%;" aria-label="Argomento: attiva per ordinare la colonna in ordine crescente">
                                                ARGOMENTO
                                            </th>
                                            <th class="dt-body-center" tabindex="0" aria-controls="tbl_contenuti" style="width: 20%;" aria-label="Tipologia: attiva per ordinare la colonna in ordine crescente">
                                                TIPOLOGIA
                                            </th>
                                            <th class="dt-body-left" tabindex="0" aria-controls="tbl_contenuti" style="width: 25%;" aria-label="Titolo del contenuto: attiva per ordinare la colonna in ordine crescente">
                                                TITOLO
                                            </th>
                                            <th class="text-right" tabindex="0" aria-controls="tbl_contenuti" style="width: 45%;" >
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr each="{ contenuto in collegamenti }" id="{ contenuto.id }" data-tappacollegamentoid="{ contenuto.enabled }" data-contenutoid="{ contenuto.id }" data-tappaid="{ id }" role="row" class="{ contenuto.enabled && (index % 2 == 0) ? 'stripe3 stripe4' : (contenuto.enabled && (index % 2 != 0) ?  'stripe2 stripe4' : ( (index % 2 == 0) ? 'stripe3' : 'stripe2')) }">
                                            <td class=" dt-body-center" style="">
                                                <i class="icon-{ contenuto.get('action_name') }carrara"></i>
                                            </td>
                                            <td class=" dt-body-center">
                                                { contenuto.get('type_class') == 'image' ? 'Immagine' : (contenuto.get('type_class') == 'gallery' ? 'Galleria' : (contenuto.get('type_class') == 'video' ? 'Video' : (contenuto.get('type_class') == 'audio' ? 'Audio' : (contenuto.get('type_class') == 'text' ? 'Testo' : '')))) }
                                            </td>
                                            <td class=" dt-body-left">
                                                { contenuto.get('title_it') }
                                            </td>
                                            <td class=" text-right">
                                                <div class="btn-group">
                                                    <a title="Modifica" href="/inserisci-contenuto?id_contenuto={ contenuto.id }" data-action="modifica" data-id="{ contenuto.id }" class="btn btn-flat btn-sq-sm btn-primary">
                                                        <i class="fas fa-pen fa-2x"></i>
                                                    </a>
                                                    <button type="button" onclick="{
                                                                toggleContenuto
                                                            }" class="enable-contenuto">{ contenuto.enabled ? 'RIMUOVI DALLA' : 'INCLUDI NELLA' } { opts.tipo == 'percorso' || opts.tipo == 'temporanea' ? 'TAPPA' : opts.tipo == 'playlist' ? 'TRACCIA' : '' }</button>
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </li>
                    <li id="newTappa">
                        <div class="box scheda" data-widget="collapse">
                            <div class="box-header">
                                <div class="row">
                                    <div class="col-lg-2">
                                        <h3 class="box-title" style="margin-top: 52px; font-size: 26px; font-weight: bold;">TAPPA { (tappe.length + 1) < 10 ? ('0' + (tappe.length + 1)) : (tappe.length + 1) }</h3>
                                    </div>
                                    <div class="col-lg-8">
                                        <div class="form-group text-center" id="selectOpera">
                                            <select id="nuova-opera" class="form-control pull-left select2 new-opera"></select>
                                        </div>
                                    </div>
                                    <div class="col-lg-2 col-md-2 text-right">
                                        <input type="hidden" name="id">
                                        <button type="button" class="btn trash-icon" onclick="{
                                                    saveTappa
                                                }"><i class="far fa-save "></i></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </section>

    <div if="{ tappaToDelete }" class="modal modal-danger fade" id="modal" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">ATTENZIONE</h4>
                </div>
                <div class="modal-body">
                    <p>Confermi la rimozione della tappa?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-flat btn-outline pull-left" data-dismiss="modal">CHIUDI</button>
                    <button type="button" class="btn btn-flat btn-outline" data-dismiss="modal" onclick="{
                                confirmedDeleteTappa
                            }">CANCELLA LA TAPPA</button>
                </div>
            </div>
        </div>
    </div>

    <style>
        @media (max-width: 1000px) {
            .enable-contenuto {
                font-size: 11px;
                padding-right: 1px;
                padding-left: 1px;
            }
            .btn-group {
                margin-right: 2px;
            }
            .btn-sq-sm {
                width: 24px !important;
                height: 24px !important;
            }
        }
        .enable-contenuto {
            background-color: transparent;
            border: 2px solid  #F93822;
            color: #F93822;
            padding: 3px 8px 4px 8px;
            margin-right: 16px;
        }
        #lista-tappe li {
            list-style-type: none;
        }
        #lista-tappe li:not(#newTappa) {
            cursor: ns-resize;
        }
        #lista-tappe .box-header {
            min-height: 150px;
        }
        #lista-tappe .box-header .box-title {
            margin-top: 52px; 
            font-size: 26px; 
            font-weight: bold;
        }
        #lista-tappe .box-header .box-title-opera {
            margin-top: 52px; 
            font-size: 18px; 
            font-weight: bold;
            color: #fff;
        }        
        #lista-tappe #selectOpera {
            margin-top: 52px;
        }
        #lista-tappe .thumb {
            height: 130px;
            padding: 0;
            margin: 0 auto;
        }
        #lista-tappe .box-header button {
            border-radius: 0;
            background-color: #fff;
            margin-top: 46px;
            color: #F93822;
            margin-right: 4px;
            width: 40px;
            height: 40px;
            font-size: 20px;
            text-align: center;
            outline: none;
        }
        #lista-tappe .box.scheda {
            padding: 0;
        }
        #lista-tappe .box.scheda > .box-body {
            padding-right: 0;
        }
        #addContenuto {
            border: 1.5px solid #F93822;
            background-color: #fff;
            color: #F93822;
            margin-bottom: 16px;
        }
        #lista-tappe .ui-state-highlight {
            margin-bottom: 20px;
            background-color: #F8EDEC;
        }
        .gallery-item {
            float: left;
            margin-right: 4px;
            margin-bottom: 4px;
            width: 130px;
            height: 130px;
            border: 2px solid #F93822;
            text-align: center;
            color: #F93822;
            position: relative;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
        }
        #gallery-notice{
            margin-top: 20px;
        }
        #gallery-container .gallery-highlight {
            float: left;
            margin-right: 4px;
            border: 2px solid #F93822;
            background-color: #fff;
            width: 130px;
            height: 130px;
        }
        .gallery-item[data-id='new'] label {
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        .gallery-item.thumb {
            cursor: move;
        }
        .gallery-item.thumb > button {
            opacity: 0;
            transition: opacity 0.5s;
            background-color: #fff;
            top: calc(50% - 16px);
            left: calc(50% - 16px);
            cursor: pointer;
            margin: 0;
        }
        .gallery-item.thumb:not(.ui-sortable-handle):hover {
            background-image: none !important;
            background-color: #F8EDEC;
        }
        .gallery-item.thumb:hover button {
            opacity: 1;
        }
        .gallery-item > button,
        .gallery-item > label > i {
            display: block;
            position: absolute;
        }
        .gallery-item > label > i {
            top: calc(50% - 6px);
            left: calc(50% - 6px);
        }
    </style>

    <script>
        var tag = this;
        tag.percorso = null;
        tag.opere = [];
        tag.tappe = [];
        tag.gallery = [];
        tag.video = null;

        tag.on('mount', function () {
            RiotBus.getInstance().on('opere::response', tag.opereResponse);
            RiotBus.getInstance().on('contenuti::created', tag.contenutoCreated);
            RiotBus.getInstance().on('percorsi::found', tag.percorsoFound);
            RiotBus.getInstance().on('percorsi::saved', tag.percorsoSaved);
            RiotBus.getInstance().on('tappe::response', tag.tappeResponse);
            RiotBus.getInstance().on('tappe::created', tag.tappaCreated);
            RiotBus.getInstance().on('tappe::deleted', tag.tappaDeleted);
            RiotBus.getInstance().on('multimediapercorso::response', tag.multimediapercorsoResponse);
            RiotBus.getInstance().on('multimediapercorso::saved', tag.multimediapercorsoSaved);
            RiotBus.getInstance().on('multimediapercorso::deleted', tag.multimediapercorsoDeleted);
            RiotBus.getInstance().on('contenuti::enabledintappa', tag.contenutoEnabled);
            RiotBus.getInstance().on('contenuti::disabledintappa', tag.contenutoDisabled);
            if (opts.id_percorso) {
                RiotBus.getInstance().trigger('percorsi::get', opts.id_percorso);
            }
            const $description_it = $('#description_it');
            if (!$description_it.hasClass(tag.EVENT_BOUND)) {
                $description_it.addClass(tag.EVENT_BOUND);
                $description_it.froalaEditor({
                    placeholderText: "Descrizione IT",
                    height: 150
                });
            }
            const $description_en = $('#description_en');
            if (!$description_en.hasClass(tag.EVENT_BOUND)) {
                $description_en.addClass(tag.EVENT_BOUND);
                $description_en.froalaEditor({
                    placeholderText: "Descrizione EN",
                    height: 150
                });
            }
            const $body = $('body');
            $body.off('focusin change click');
            $body.on('focusin', '.datepicker', function (e) {
                tag.addDatePicker(this);
            });
            $body.on("change", "[name='image']", function (e) {
                readImage("image", e.target.files);
            });
            $body.on("change", "#uploadgallery", function (e) {
                $("#gallery-container").block({message: null});
                let allegato = null;
                if (e.target.files.length > 0) {
                    allegato = e.target.files[0];
                }
                if (allegato) {
                    const position = tag.gallery.length + 1;
                    let data = {
                        allegato: allegato,
                        percorso_id: opts.id_percorso,
                        type_class: "gallery",
                        position: position
                    };
                    RiotBus.getInstance().trigger('multimediapercorso::save', data);
                }
            });
            $body.on("click", ".gallery-item [data-action='delete']", function (e) {
                $("#gallery-container").block({message: null});
                const id = $(e.currentTarget).parent().attr("data-id");
                RiotBus.getInstance().trigger('multimediapercorso::delete', id);
            });
            $('.box').each(function () {
                $(this).boxWidget();
            });
        });

        tag.on('unmount', function () {
            RiotBus.getInstance().off('opere::response', tag.opereResponse);
            RiotBus.getInstance().off('contenuti::created', tag.contenutoCreated);
            RiotBus.getInstance().off('percorsi::found', tag.percorsoFound);
            RiotBus.getInstance().off('percorsi::saved', tag.percorsoSaved);
            RiotBus.getInstance().off('tappe::response', tag.tappeResponse);
            RiotBus.getInstance().off('tappe::created', tag.tappaCreated);
            RiotBus.getInstance().off('tappe::deleted', tag.tappaDeleted);
            RiotBus.getInstance().off('multimediapercorso::response', tag.multimediapercorsoResponse);
            RiotBus.getInstance().off('multimediapercorso::saved', tag.multimediapercorsoSaved);
            RiotBus.getInstance().off('multimediapercorso::deleted', tag.multimediapercorsoDeleted);
            RiotBus.getInstance().off('contenuti::enabledintappa', tag.contenutoEnabled);
            RiotBus.getInstance().off('contenuti::disabledintappa', tag.contenutoDisabled);
        });

        tag.multimediapercorsoResponse = function (multimedia) {
            tag.gallery = [];
            tag.video = null;
            let m = null;
            for (let i = 0; i < multimedia.length; i++) {
                m = multimedia[i];
                switch (m.get("type_class")) {
                    case "gallery":
                        tag.gallery.push(m);
                        break;
                    case "video":
                        tag.video = m;
                        break;
                }
            }
            tag.update();
            const $gallery = $("#gallery-container");
            for (let i = 0; i < tag.gallery.length; i++) {
                let g = tag.gallery[i];
                $gallery.append(getGalleryItem(g));
            }
            $gallery.sortable({
                placeholder: "gallery-highlight",
                items: ".gallery-item.thumb",
                update: function (e, ui) {
                    let $elements = $('#gallery-container > .gallery-item.thumb');
                    const gallerySorted = [];
                    $elements.each(function () {
                        const id = $(this).attr("data-id");
                        gallerySorted.push(id);
                    });
                    RiotBus.getInstance().trigger('multimediapercorso::updateposition', gallerySorted);
                }
            }).disableSelection();
        };

        tag.multimediapercorsoSaved = function (m) {
            switch (m.get("type_class")) {
                case "gallery":
                    const $gallery = $("#gallery-container");
                    tag.gallery.push(m);
                    tag.update();
                    $gallery.append(getGalleryItem(m));
                    $gallery.sortable('refresh');
                    $gallery.unblock();
                    break;
                case "video":
                    tag.video = m;
                    tag.update();
                    break;
            }
        };

        tag.multimediapercorsoDeleted = function (m) {
            switch (m.get("type_class")) {
                case "gallery":
                    let i = 0;
                    for (i = 0; i < tag.gallery.length; i++) {
                        if (tag.gallery[i].id === m.id) {
                            break;
                        }
                    }
                    tag.gallery.splice(i, 1);
                    tag.update();
                    const $gallery = $("#gallery-container");
                    $gallery.unblock();
                    $gallery.children("[data-id='" + m.id + "']").fadeOut();
                    $gallery.sortable('refresh');
                    break;
                case "video":
                    tag.video = null;
                    tag.update();
                    break;
            }
        };

        tag.savevideo = function () {
            const data = {};
            $('#form-video [name]').each(function () {
                data[this.name] = this.value;
            });
            if (data.youtube.trim().length > 0) {
                RiotBus.getInstance().trigger('multimediapercorso::save', data);
            } else if (data.id) {
                RiotBus.getInstance().trigger('multimediapercorso::delete', data.id);
            }
        };

        tag.confirmedDeleteTappa = function () {
            const tappa_id = tag.tappaToDelete.id;
            RiotBus.getInstance().trigger('tappe::delete', tappa_id);
        };

        tag.deleteTappa = function (e) {
            const tappa_id = e.item.id;
            const tappa = tag.tappe.find(function (item) {
                return item.id === tappa_id;
            });
            tag.tappaToDelete = tappa;
            tag.update();
            $("#modal").modal("show");
        };

        tag.tappaDeleted = function () {
            RiotBus.getInstance().trigger('tappe::search', tag.percorso.id);
        };

        tag.tappaCreated = function (tappa) {
            const $select = $('#nuova-opera');
            $select.val("").trigger('change');
            RiotBus.getInstance().trigger('tappe::search', tag.percorso.id);
        };

        tag.opereResponse = function (results) {
            tag.opere = results;
            const $select = $('#nuova-opera');
            $select.select2({
                placeholder: "Indica l'opera.."
            });
            $select.append(new Option('', '', false, false)).trigger('change');
            for (let i = 0; i < results.length; i++) {
                let text = "";
                const data = {
                    id: results[i].id
                };
                if (results[i].get('ac_inventory_number')) {
                    text += results[i].get('ac_inventory_number') + " - ";
                }
                text += results[i].get('title_it') + (results[i].get('creator') ? (' - ' + results[i].get('creator')) : "");
                data.text = text;
                var o = new Option(data.text, data.id, false, false);
                $select.append(o).trigger('change');
            }
        };

        tag.toggleContenuto = function (e) {
            const $tr = $(e.target).closest("tr");
            const contenuto_id = $tr.data("contenutoid");
            const tappa_id = $tr.data("tappaid");
            const tappacollegamento = $tr.attr("data-tappacollegamentoid");
            if (tappacollegamento) {
                RiotBus.getInstance().trigger('contenuti::disableintappa', tappacollegamento, opts.tipo);
            } else {
                RiotBus.getInstance().trigger('contenuti::enableintappa', contenuto_id, tappa_id, opts.tipo);
            }
        };

        tag.contenutoDisabled = function (tc) {
            let tappa_id = tc.get("tappa_id").id;
            const tappacollegamento_id = tc.id;
            for (let i = 0; i < tag.tappe.length; i++) {
                if (tag.tappe[i].id === tappa_id) {
                    for (let j = 0; j < tag.tappe[i].collegamenti.length; j++) {
                        if (tag.tappe[i].collegamenti[j].enabled === tappacollegamento_id) {
                            tag.tappe[i].collegamenti[j].enabled = null;
                            break;
                        }
                    }
                    break;
                }
            }
            tag.update();
        };

        tag.contenutoEnabled = function (tc) {
            let tappa_id = tc.get("tappa_id").id;
            const collegamento_id = tc.get("collegamento_id").id;
            const tappacollegamento_id = tc.id;
            for (let i = 0; i < tag.tappe.length; i++) {
                if (tag.tappe[i].id === tappa_id) {
                    for (let j = 0; j < tag.tappe[i].collegamenti.length; j++) {
                        if (tag.tappe[i].collegamenti[j].id === collegamento_id) {
                            tag.tappe[i].collegamenti[j].enabled = tappacollegamento_id;
                            break;
                        }
                    }
                    break;
                }
            }
            tag.update();
        };

        tag.saveTappa = function () {
            const opera_id = $("#nuova-opera").val();
            const percorso_id = tag.percorso.id;
            const step_number = tag.tappe.length + 1;
            RiotBus.getInstance().trigger('tappe::create', percorso_id, opera_id, step_number);
        };

        tag.percorsoFound = function (percorso) {
            tag.percorso = percorso;
            $("#description_it").froalaEditor('html.set', tag.percorso.get("description_it"));
            $("#description_en").froalaEditor('html.set', tag.percorso.get("description_en"));
            tag.update();
            RiotBus.getInstance().trigger('opere::request', {source: opts.tipo});
            RiotBus.getInstance().trigger('multimediapercorso::request', opts.id_percorso);
            RiotBus.getInstance().trigger('tappe::search', opts.id_percorso);
        };

        tag.percorsoSaved = function (result) {
            $("#salva").button('saved');
            tag.routeTo("/inserisci-percorso?tipo=" + opts.tipo + "&id_percorso=" + result.id);
            tag.update();
        };

        tag.addContenuto = function (e) {
            var tappa_id = e.item.id;
            var opera_id = e.item.opera_id;
            RiotBus.getInstance().trigger('contenuti::create', tappa_id, opera_id);
        };

        tag.contenutoCreated = function (contenuto, tappa_id) {
            tag.routeTo('/inserisci-contenuto?id_contenuto=' + contenuto.id + "&id_tappa=" + tappa_id + "&id_percorso=" + tag.percorso.id);
        };

        tag.save = function () {
            $("#salva").button('saving');
            const data = {};
            $('#form-percorso [name]').each(function () {
                data[this.name] = this.value;
            });
            data["description_it"] = $("#description_it").froalaEditor('html.get');
            data["description_en"] = $("#description_en").froalaEditor('html.get');
            let allegato = null;
            const fileControl = $("[name='image']")[0];
            if (fileControl.files.length > 0) {
                allegato = fileControl.files[0];
            }
            RiotBus.getInstance().trigger('percorsi::save', data, allegato);
        };

        tag.tappeResponse = function (results) {
            tag.tappe = [];
            for (let i = 0; i < results.length; i++) {
                const o = {
                    opera: results[i].t.get("opera_id"),
                    opera_id: results[i].t.get("opera_id").id,
                    file: results[i].t.get("opera_id").get('data') ? results[i].t.get("opera_id").get('data').thumb.url : "",
                    tappa: results[i].t,
                    collegamenti: results[i].contenuti,
                    opera_title_it: results[i].t.get("opera_id").get('title_it'),
                    position: results[i].t.get("step_number"),
                    id: results[i].t.id
                };
                tag.tappe.push(o);
            }
            tag.update();
            $("#lista-tappe").sortable({
                placeholder: "ui-state-highlight",
                start: function (e, ui) {
                    ui.placeholder.height(ui.item.height());
                },
                items: "li:not(#newTappa)",
                update: function (e, ui) {
                    let elements = $('#lista-tappe li');
                    let k = 1;
                    const tappeSorted = [];
                    elements.each(function (e) {
                        let el = elements[e];
                        const $el = $(el);
                        const id = $el.find("[name='tappa_id']").val();
                        tappeSorted.push(id);
                        let num = e + 1;
                        let new_title = 'TAPPA ' + (num < 10 ? ('0' + num) : num);
                        $el.find('.box-title')[0].textContent = new_title;
                        k++;
                    });
                    RiotBus.getInstance().trigger('tappe::updateposition', tappeSorted);
                }
            }).disableSelection();

            $('body').on('click', '.draggable-element .minus-icon', function () {
                const $this = $(this);
                $this.find("i").toggleClass("fa-plus").toggleClass("fa-minus");
                const box_id = $this.data("target");
                if ($('#' + box_id).hasClass('in')) {
                    $("#" + box_id).collapse('hide');
                } else {
                    $("#" + box_id).collapse('show');
                }
            });
        };

        function getGalleryItem(g) {
            return "<div class='gallery-item thumb' data-id='" + g.id + "' data-position='" + g.get('position') + "' style='background-image: url(" + (g.get('data') ? g.get('data').thumb.url : '/assets/img/imgloading.jpeg') + ")'>" +
                    "<button type='button' data-action='delete' class='btn btn-primary btn-sm btn-flat trash-icon'><i class='fa fa-trash'></i></button>" +
                    "</div>";
        }

    </script>
</inserisci-percorso>
