Subversion Repositories eFlore/Applications.cel

Rev

Blame | Last modification | View Log | RSS feed

/**
 * Constructeur LichensApa par défaut
 */
function LichensApa() {
        this.obsNbre = 0;
        this.nbObsEnCours = 1;
        this.totalObsATransmettre = 0;
        this.nbObsTransmises = 0;
        this.debug = null;
        this.html5 = null;
        this.tagProjet = null;
        this.tagImg = null;
        this.tagObs = null;
        this.separationTagImg = null;
        this.separationTagObs = null;
        this.serviceSaisieUrl = null;
        this.chargementImageIconeUrl = null;
        this.pasDePhotoIconeUrl = null;
        this.nomSciReferentiel = null;
        this.autocompletionElementsNbre = null;
        this.referentielImpose = null;
        this.serviceAutocompletionNomSciUrl = null;
        this.serviceAutocompletionNomSciUrlTpl = null;
        this.obsMaxNbre = null;
        this.dureeMessage = null;
        this.infosUtilisateur = {};
        this.releveDatas = null;
        this.utils = new UtilsApa();
}

LichensApa.prototype.init = function() {
        this.initForm();
        this.initEvts();
};

/**
 * Initialise le formulaire, les validateurs, les listes de complétion...
 */
LichensApa.prototype.initForm = function() {
        const lthis = this;

        $('[type="date"]').prop('max', function(){
                return new Date().toJSON().split('T')[0];
        });

        this.surChangementTaxonListe();
        $( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
        $( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
        if ( this.debug ) {
                console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
        }
        this.configurerFormValidator();
        this.definirReglesFormValidator();
};

/**
 * Initialise les écouteurs d'événements
 */
LichensApa.prototype.initEvts = function() {
        const lthis = this;

        var releveDatas = [];
        this.infosUtilisateur.id     = $( '#id_utilisateur' ).val();
        this.infosUtilisateur.prenom = $( '#prenom' ).val();
        this.infosUtilisateur.nom    = $( '#nom' ).val();

        $( '#bouton-nouveau-releve' ).click( function() {
                $( '#releve-data' ).val( '' );
                if ( lthis.utils.valOk( lthis.infosUtilisateur.id ) ) {
                        lthis.utils.chargerForm( 'arbres', lthis );
                        $( '#bouton-list-releves' ).removeClass( 'hidden' );
                }
                $( '#table-releves' ).addClass( 'hidden' );
        });

        if( this.utils.valOk( this.infosUtilisateur.id ) && this.utils.valOk( $( '#releve-data' ).val() ) ) {
                this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
                if ( this.utils.valOk( this.releveDatas[0].utilisateur, true, this.infosUtilisateur.id ) ) {

                        // Sur téléchargement image
                        $( '#fichier' ).on( 'change', function ( e ) {
                                arreter( e );

                                var options        = {
                                        success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
                                        dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
                                        resetForm: true // reset the form after successful submit
                                };

                                $( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );

                                var imgCheminTmp    = $( '#fichier' ).val(),
                                        formatImgOk     = lthis.verifierFormat( imgCheminTmp ),
                                        imgNonDupliquee = lthis.verifierDuplication( imgCheminTmp );

                                if( formatImgOk && imgNonDupliquee ) {
                                        $( '#form-upload' ).ajaxSubmit( options );
                                } else {
                                        $( '#form-upload' )[0].reset();
                                        if ( !formatImgOk ) {
                                                window.alert( lthis.utils.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
                                        }
                                        if ( !imgNonDupliquee ) {
                                                window.alert( lthis.utils.msgTraduction( 'image-deja-chargee' ) );
                                        }
                                }
                                return false;
                        });
                        $( 'body' ).on( 'click', '.effacer-miniature', function() {
                                $( this ).parent().remove();
                        });

                        $( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
                        $( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
                        // défilement des miniatures dans le résumé obs
                        $( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
                                event.preventDefault();
                                lthis.defilerMiniatures( $( this ) );
                        });
                        $( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
                                event.preventDefault();
                                lthis.defilerMiniatures( $( this ) );
                        });
                        // mécanisme de suppression d'une obs
                        $( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
                                var that = this,
                                suppObs = lthis.supprimerObs.bind( lthis );
                                // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
                                suppObs( that );
                        });

                        $( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );

                        // chargement plantes ou lichens
                        $( '#bouton-saisir-plantes,#bouton-poursuivre' ).on( 'click', function() {
                                var nomSquelette = $( this ).data( 'load' );
                                $( '#charger-form' ).data( 'load', nomSquelette );
                                lthis.utils.chargerForm( nomSquelette, lthis );
                                $( 'html, body' ).stop().animate({
                                        scrollTop: $( '#charger-form' ).offset().top
                                }, 300 );
                        });

                        // Alertes et tooltips
                        $( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
                        $( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
                        // $( '.has-tooltip' ).tooltip( 'enable' );
                }
        }
};

// Préchargement des infos-obs ************************************************/

/**
 * Callback dans le chargement du formulaire dans #charger-form
 */
LichensApa.prototype.chargerSquelette = function( squelette, nomSquelette ) {
        switch( nomSquelette ) {
                case 'plantes' :
                case 'lichens' :
                        this.utils.chargerFormPlantesOuLichens( squelette, nomSquelette );
                        break;
                case 'arbres' :
                default :
                        this.reinitialiserWidget( squelette );
                break;
        }
};

LichensApa.prototype.reinitialiserWidget = function( squelette ) {
        $( '#charger-form' ).html( squelette );
        if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
                this.rechargerFormulaire();
        }
};

// uniquement utilisé si taxon-liste ******************************************/
// Affiche/Cache le champ taxon
LichensApa.prototype.surChangementTaxonListe = function() {
        const utils = new UtilsApa();
        if ( utils.valOk( $( '#taxon-liste' ).val() ) ) {
                if ( 'autre' !== $( '#taxon-liste' ).val() ) {
                        $( '#taxon-input-groupe' )
                                .hide( 200, function () {
                                        $( this ).addClass( 'hidden' ).show();
                                })
                                .find( '#taxon-autre' ).val( '' );
                } else {
                        $( '#taxon-input-groupe' )
                                .hide()
                                .removeClass( 'hidden' )
                                .show(200)
                                .find( '#taxon-autre' )
                                        .focus()
                                        .on( 'change', function() {
                                                if( !utils.valOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
                                                        $( '#taxon' ).val( $( '#taxon-autre' ).val() );
                                                        $( '#taxon' ).removeData( 'value' )
                                                                .removeData( 'numNomSel' )
                                                                .removeData( 'nomRet' )
                                                                .removeData( 'numNomRet' )
                                                                .removeData( 'nt' )
                                                                .removeData( 'famille' );
                                                }
                                                $( '#taxon' ).trigger( 'change' );
                                        });
                }
        }
};

LichensApa.prototype.surChangementValeurTaxon = function() {
        var numNomSel = 0;

        if( this.utils.valOk( $( '#taxon-liste' ).val() ) ) {
                if( 'autre' === $( '#taxon-liste' ).val() ) {
                        this.ajouterAutocompletionNoms();
                } else {
                        var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
                        // $( '#taxon' ).val( $( '#taxon-liste' ).val() );
                        $( '#taxon' ).val( $( '#taxon-liste' ).val() )
                                .data( 'value', $( '#taxon-liste' ).val() )
                                .data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
                                .data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
                                .data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
                                .data( 'nt', optionRetenue.data( 'nt' ) )
                                .data( 'famille', optionRetenue.data( 'famille' ) );
                        $( '#taxon' ).trigger( 'change' );

                        numNomSel = $( '#taxon' ).data( 'numNomSel' );
                        // Si l'espèce est mal déterminée la certitude est "à déterminer"
                        if( !this.utils.valOk( numNomSel ) ) {
                                $( '#certitude' ).find( 'option' ).each( function() {
                                        if ( $( this ).hasClass( 'aDeterminer' ) ) {
                                                $( this ).attr( 'selected', true );
                                        } else {
                                                $( this ).attr( 'selected', false );
                                        }
                                });
                        }
                }
        }
};

// Autocompletion taxons ******************************************************/
/**
 * Initialise l'autocompletion taxons
 */
LichensApa.prototype.ajouterAutocompletionNoms = function() {
        const lthis = this;

        var taxonSelecteur = '#taxon';
        if ( this.utils.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
                taxonSelecteur += '-autre';
        }

        $( taxonSelecteur ).autocomplete({
                source: function( requete, add ) {
                        // la variable de requête doit être vidée car sinon le parametre "term" est ajouté
                        requete = '';
                        if( lthis.utils.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
                                var url = lthis.getUrlAutocompletionNomsSci();
                                $.getJSON( url, requete, function( data ) {
                                        var suggestions = lthis.traiterRetourNomsSci( data );
                                        add( suggestions );
                                })
                                .fail( function() {
                                        $( '#certitude' ).find( 'option' ).each( function() {
                                                if ( $( this ).hasClass( 'aDeterminer' ) ) {
                                                        $( this ).attr( 'selected', true );
                                                } else {
                                                        $( this ).attr( 'selected', false );
                                                }
                                        });
                                });
                        }
                },
                html: true
        });
        $( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
};

LichensApa.prototype.getUrlAutocompletionNomsSci = function() {
        var taxonSelecteur = '#taxon';
        if ( this.utils.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
                taxonSelecteur += '-autre';
        }
        var mots = $( taxonSelecteur ).val();
        var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
        url = url.replace( '{masque}', mots );

        return url;
};

/**
 * Objet taxons pour autocompletion en fonction de la recherche
 */
LichensApa.prototype.traiterRetourNomsSci = function( data ) {
        var taxonSelecteur = '#taxon';
        var suggestions = [];

        if ( this.utils.valOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
                taxonSelecteur += '-autre';
        }
        if ( undefined != data.resultat ) {
                $.each( data.resultat, function( i, val ) {
                        val.nn = i;

                        var nom = {
                                label : '',
                                value : '',
                                nt : 0,
                                nomSel : '',
                                nomSelComplet : '',
                                numNomSel : 0,
                                nomRet : '',
                                numNomRet : 0,
                                famille : '',
                                retenu : false
                        };
                        if ( suggestions.length >= this.autocompletionElementsNbre ) {
                                nom.label = '...';
                                nom.value = $( taxonSelecteur ).val();
                                suggestions.push( nom );
                                return false;
                        } else {
                                nom.label = val.nom_sci_complet;
                                nom.value = val.nom_sci_complet;
                                nom.nt = val.num_taxonomique;
                                nom.nomSel = val.nom_sci;
                                nom.nomSelComplet = val.nom_sci_complet;
                                nom.numNomSel = val.nn;
                                nom.nomRet = val.nom_retenu_complet;
                                nom.numNomRet = val['nom_retenu.id'];
                                nom.famille = val.famille;
                                // Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
                                // en tout cas c'est harmonisé avec le CeL
                                nom.retenu = ( 'true' == val.retenu );
                                suggestions.push( nom );
                        }
                });
        }
        return suggestions;
};

/**
 * charge les données dans #taxon
 */
LichensApa.prototype.surAutocompletionTaxon = function( event, ui ) {
        const utils = new UtilsApa();

        if ( utils.valOk( ui ) ) {
                $( '#taxon' ).val( ui.item.value );
                $( '#taxon' ).data( 'value', ui.item.value )
                        .data( 'numNomSel', ui.item.numNomSel )
                        .data( 'nomRet', ui.item.nomRet )
                        .data( 'numNomRet', ui.item.numNomRet )
                        .data( 'nt', ui.item.nt )
                        .data( 'famille', ui.item.famille );
                if ( ui.item.retenu ) {
                        $( '#taxon' ).addClass( 'ns-retenu' );
                } else {
                        $( '#taxon' ).removeClass( 'ns-retenu' );
                }
                // Si l'espèce est mal déterminée la certitude est "à déterminer"
                if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
                        $( '#certitude' ).find( 'option' ).each( function() {
                                if ( $( this ).hasClass( 'aDeterminer' ) ) {
                                        $( this ).attr( 'selected', true );
                                } else {
                                        $( this ).attr( 'selected', false );
                                }
                        });
                }
        }
        $( '#taxon' ).change();
};

// Fichier Images *************************************************************/
/**
 * Affiche temporairement (formulaire)
 * la miniature d'une image ajoutée à l'obs
 */
LichensApa.prototype.afficherMiniature = function( reponse ) {
        if ( this.debug ) {
                var debogage = $( 'debogage', reponse ).text();
        }

        var message = $( 'message', reponse ).text();

        if ( this.utils.valOk( message ) ) {
                $( '#miniature-msg' ).append( message );
        } else {
                $( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
        }
        $( '#ajouter-obs' ).removeAttr( 'disabled' );
};

/**
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
 */
LichensApa.prototype.creerWidgetMiniature = function( reponse ) {
        var miniatureUrl = $( 'miniature-url', reponse ).text();
        var imgNom = $( 'image-nom', reponse ).text();
        var html =
                '<div class="miniature mb-3 mr-3">'+
                        '<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
                        '<a class="effacer-miniature"><i class="fas fa-times"></i></a>'+
                '</div>';

        return html;
};

/**
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
 */
LichensApa.prototype.verifierFormat = function( cheminTmp ) {
        var parts     = cheminTmp.split( '.' ),
                extension = parts[ parts.length - 1 ];

        return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
};

/**
 * Check les miniatures déjà téléchargées
 * renvoie false si le même nom est rencontré 2 fois
 * renvoie true sinon
 */
LichensApa.prototype.verifierDuplication = function( cheminTmp ) {
        const lthis = this;
        var parts        = cheminTmp.split( '\\' ),
                nomImage     = parts[ parts.length - 1 ],
                thisSrcParts = [],
                thisNomImage = '',
                nonDupliquee = true;

        $( 'img.miniature-img,img.miniature' ).each( function() {
                // vérification avec alt de l'image
                if ( lthis.utils.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
                        nonDupliquee = false;
                        return false;// Pas besoin de poursuivre la boucle
                } else { // sinon vérifie aussi avec l'adresse (src) de l'image
                        thisSrcParts = $( this ).attr( 'src' ).split( '/' );
                        thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
                        if ( lthis.utils.valOk ( thisNomImage, true, nomImage ) ) {
                                nonDupliquee = false;
                                return false;
                        }
                }
        });
        return nonDupliquee;
};

/**
 * Efface une miniature (formulaire)
 */
LichensApa.prototype.supprimerMiniature = function( miniature ) {
        miniature.parents( '.miniature' ).remove();
};

// Ajouter Obs ****************************************************************/

/**
 * Ajoute une observation à la liste des obs à transmettre
 * (résumé obs)
 */
LichensApa.prototype.ajouterObs = function() {
        // Fermeture automatique des dialogue de transmission de données
        // @WARNING TEST
        $( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
        $( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
        $( 'html, body' ).stop().animate({
                scrollTop: $( '#zone-lichens' ).offset().top
        }, 300);

        if ( this.validerLichens() ) {
                this.masquerPanneau( '#dialogue-form-invalide' );
                this.obsNbre  += 1;
                $( '.obs-nbre' ).text( this.obsNbre );
                $( '.obs-nbre' ).triggerHandler( 'changement' );
                //formatage des données
                var obsData   = this.formaterFormObsData();

                // Résumé obs et stockage en data de "#list-obs" pour envoi
                this.afficherObs( obsData );
                this.stockerObsData( obsData );
                this.reinitialiserFormLichens();
                $( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
                $( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
        } else {
                this.afficherPanneau( '#dialogue-form-invalide' );
        }
};

LichensApa.prototype.reinitialiserFormLichens = function() {
        this.supprimerMiniatures();
        $( '#taxon,#taxon-autre,#commentaire' ).val( '' );
        $( '#taxon' ).removeData( 'value' )
                .removeData( 'numNomSel' )
                .removeData( 'nomRet' )
                .removeData( 'numNomRet' )
                .removeData( 'nt' )
                .removeData( 'famille' );
        $( '#taxon-liste,#certitude' ).find( 'option' ).each( function() {
                if ( $( this ).hasClass( 'choisir' ) ) {
                        $( this ).attr( 'selected', true );
                } else {
                        $( this ).attr( 'selected', false );
                }
        });
        $( '#taxon-input-groupe' ).addClass( 'hidden' );
        $( 'input[name=lichens-tronc]:checked' ).each( function() {
                $( this ).prop( 'checked', false );
        });
};

/**
 * Formatage des données du formulaire pour stockage et envoi
 */
LichensApa.prototype.formaterFormObsData = function() {
        var numArbre = $( '#choisir-arbre' ).val(),
                miniatureImg  = [],
                imgB64        = [],
                imgNom        = [],
                numNomSel     = $( '#taxon' ).data( 'numNomSel' ),
                referentiel   = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : this.nomSciReferentiel;

        this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
        imgNom = this.getNomsImgsOriginales();
        imgB64 = this.getB64ImgsOriginales();

        var obsData = {
                obsNum   : this.obsNbre,
                numArbre : numArbre,
                lichen   : {
                        'num_nom_sel'   : numNomSel,
                        'nom_sel'       : $( '#taxon' ).val(),
                        'nom_ret'       : $( '#taxon' ).data( 'nomRet' ),
                        'num_nom_ret'   : $( '#taxon' ).data( 'numNomRet' ),
                        'num_taxon'     : $( '#taxon' ).data( 'nt' ),
                        'famille'       : $( '#taxon' ).data( 'famille' ),
                        'referentiel'   : referentiel,
                        'certitude'     : ( !this.utils.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
                        'date'          : this.utils.fournirDate( $( '#obs-date' ).val() ),
                        'notes'         : $( '#commentaire' ).val(),
                        'pays'          : this.releveDatas[0].pays,
                        'commune_nom'   : this.releveDatas[0]['commune-nom'],
                        'commune_code_insee' : this.releveDatas[0]['commune-insee'],
                        'latitude'      : this.releveDatas[numArbre]['latitude-arbres'],
                        'longitude'     : this.releveDatas[numArbre]['longitude-arbres'],
                        'altitude'      : this.releveDatas[numArbre]['altitude-arbres'],
                        //Ajout des champs images
                        'image_nom'     : imgNom,
                        'image_b64'     : imgB64,
                        // Ajout des champs étendus de l'obs
                        'obs_etendue'   : this.getObsChpLichens( numArbre )
                }
        };
        return obsData;
};

/**
 * Retourne un Array contenant les valeurs des champs
 * dont les données seront transmises dans la table cel-obs-etendues
 */
LichensApa.prototype.getObsChpLichens = function( numArbre ) {
        const lthis = this;

        var retour = [
                { cle : 'num-arbre', valeur : numArbre },
                { cle : 'id_obs_arbre', valeur : this.releveDatas[numArbre]['id_observation'] },
                { cle : 'rue' , valeur : this.releveDatas[0].rue  }
        ];

        var valeursLT  = '';
        const $lichensTronc = $( 'input[name=lichens-tronc]:checked' );
        const LTLenght = $lichensTronc.length;

        $( 'input[name=lichens-tronc]:checked' ).each( function( i, value ) {
                valeursLT += $(value).val();
                if( i < LTLenght ) {
                        valeursLT += ';';
                }
        });
        retour.push({ cle : 'loc-sur-tronc', valeur : valeursLT });

        return retour;
};

/**
 * Résumé obs
 */
LichensApa.prototype.afficherObs = function( datasObs ) {
        var obsNum            = datasObs.obsNum,
                numArbre          = datasObs.numArbre,
                dateObs           = datasObs.lichen.date,
                numNomSel         = datasObs.lichen['num_nom_sel'],
                taxon             = datasObs.lichen['nom_sel'],
                certitude         = datasObs.lichen.certitude,
                miniatures        = this.ajouterImgMiniatureAuTransfert(),
                commentaires      = '';

        if ( this.utils.valOk( datasObs.lichen.notes ) ) {
                commentaires =
                        this.utils.msgTraduction( 'commentaires' ) +
                        ' : <span>'+
                                datasObs.lichen.notes +
                        '</span> ';
        }

        var responsivDiff1 = '',
                responsivDiff2 = '',
                responsivDiff3 = '',
                responsivDiff4 = '',
                responsivDiff5 = '',
                responsivDiff6 = '';

        if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
                /* La largeur minimum de l'affichage est 600 px inclus */
                responsivDiff1 = ' droite';
                responsivDiff2 = '<div></div>';
                responsivDiff3 = '<div class="row">';
                responsivDiff4 = ' col-md-4 col-sm-5';
                responsivDiff5 = ' class="col-md-7 col-sm-6"';
                responsivDiff6 = '</div>';
        }
        $( '#liste-obs' ).prepend(
                '<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
                        '<div '+
                                'class="obs-action" '+
                                'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
                        '>'+
                                '<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
                                '<i class="far fa-trash-alt"></i>'+
                                '</button>'+
                                responsivDiff2 +
                        '</div> '+
                        responsivDiff3 +
                                '<div class="thumbnail' + responsivDiff4 + '">'+
                                        miniatures+
                                '</div>'+
                                '<div' + responsivDiff5 + '>'+
                                        '<ul class="unstyled">'+
                                                '<li>'+
                                                        '<span id="obs-lichen-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
                                                        ' <span class="nom-sci">' + taxon + '</span> '+
                                                        this.ajouterNumNomSel( numNomSel ) +
                                                        ' [certitude : ' + certitude + ']'+
                                                        ' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
                                                        '<span class="date">' + dateObs + '</span>'+
                                                '</li>'+
                                                '<li>'+
                                                        commentaires +
                                                '</li>'+
                                        '</ul>'+
                                '</div>'+
                        responsivDiff6+
                '</div>'
        );
        $( '#zone-liste-obs' ).removeClass( 'hidden' );
};

/**
 * Ajoute une boîte de miniatures avec défilement des images,
 * pour une obs de la liste des obs à transmettre
 */
LichensApa.prototype.ajouterImgMiniatureAuTransfert = function() {
        var html        =
                        '<div class="defilement-miniatures">'+
                                '<figure class="centre">'+
                                        '<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
                                '</figure>'+
                        '</div>',
                miniatures   = '',
                premiere     = true,
                centre       = '';
                defilVisible = '';

        if ( this.utils.valOk( $( '#miniatures img' ) ) ) {
                $( '#miniatures img' ).each( function() {
                        var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
                        premiere = false;

                        var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
                                src        = $( this ).attr( 'src' ),
                                alt        = $( this ).attr( 'alt' ),
                                miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';

                        miniatures += miniature;
                });
                if ( 1 === $( '#miniatures img' ).length ) {
                        centre       = 'centre';
                        defilVisible = ' defilement-miniatures-cache';
                }
                html             =
                        '<div class="defilement-miniatures">'+
                                '<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
                                '<figure class="' + centre + '">'+
                                        miniatures+
                                '</figure>'+
                                '<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
                        '</div>';
        }
        return html;
};

/**
 * Construit le html à afficher pour le numNom
 */
LichensApa.prototype.ajouterNumNomSel = function( numNomSel ) {
        var nn = '<span class="nn">[nn' + numNomSel + ']</span>';

        if ( !this.utils.valOk( numNomSel ) ) {
                nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
        }

        return nn;
};

/**
 * Stocke des données d'obs à envoyer à la bdd
 */
LichensApa.prototype.stockerObsData = function( datasObs ) {
        // Stockage en data des données d'obs à transmettre
        $( '#liste-obs' ).data( 'obsId' + datasObs.obsNum, datasObs.lichen );
};

LichensApa.prototype.getNomsImgsOriginales = function() {
        var noms = new Array();

        $( '.miniature-img' ).each( function() {
                noms.push( $( this ).attr( 'alt' ) );
        });

        return noms;
};

LichensApa.prototype.getB64ImgsOriginales = function() {
        var b64 = new Array();

        $( '.miniature-img' ).each( function() {
                if ( $( this ).hasClass( 'b64' ) ) {
                        b64.push( $( this ).attr( 'src' ) );
                } else if ( $( this ).hasClass( 'b64-canvas' ) ) {
                        b64.push( $( this ).data( 'b64' ) );
                }
        });

        return b64;
};

/**
 * Efface toutes les miniatures (formulaire)
 */
LichensApa.prototype.supprimerMiniatures = function() {
        $( '#miniatures' ).empty();
        $( '#miniature-msg' ).empty();
};

LichensApa.prototype.surChangementNbreObs = function() {
        if ( 0 === this.obsNbre ) {
                $( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
        } else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
                $( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
        } else if ( this.obsNbre >= this.obsMaxNbre ) {
                $( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
                this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
        }
};

LichensApa.prototype.defilerMiniatures = function( element ) {
        var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );

        miniatureSelectionne.removeClass( 'miniature-selectionnee' );
        miniatureSelectionne.addClass( 'miniature-cachee' );

        var miniatureAffichee     = miniatureSelectionne;

        if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
                if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
                        miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
                } else {
                        miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
                }
        } else {
                if( 0 !== miniatureSelectionne.next('.miniature').length ) {
                        miniatureAffichee = miniatureSelectionne.next( '.miniature' );
                } else {
                        miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
                }
        }
        miniatureAffichee.addClass( 'miniature-selectionnee' );
        miniatureAffichee.removeClass( 'miniature-cachee' );
};

LichensApa.prototype.supprimerObs = function( selector ) {
        var obsId = $( selector ).val();

        // Problème avec IE 6 et 7
        if ( 'Supprimer' === obsId ) {
                obsId = $( selector ).attr( 'title' );
        }
        this.supprimerObsParId( obsId );
};

/**
 * Supprime l'obs et les data de l'obs
 * et remonte les suivantes d'un cran
 */
LichensApa.prototype.supprimerObsParId = function( obsId ) {
        this.obsNbre  -= 1;
        $( '.obs-nbre' ).text( this.obsNbre );
        $( '.obs-nbre' ).triggerHandler( 'changement' );
        $( '.obs' + obsId ).remove();

        obsId = parseInt(obsId);
        var listObsData = $( '#liste-obs' ).data(),
                exId        = 0,
                indexObs    = '',
                exIndexObs  = '';

        for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
                exId       = parseInt(id) + 1;
                indexObs   = 'obsId' + id;
                exIndexObs = 'obsId' + exId;
                $( '#liste-obs' ).removeData( indexObs );
                if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
                        $( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
                }
                $( '#obs' + exId )
                        .attr( 'id', 'obs' + id )
                        .removeClass( 'obs' + exId )
                        .addClass( 'obs' + id )
                        .find( '.supprimer-obs' )
                                .attr( 'title', 'Observation n°' + id )
                                .val( id );
                if ( parseInt( id ) !== this.obsNbre ) {
                        id = parseInt( id );
                }
        }
};

LichensApa.prototype.transmettreObs = function() {
        const lthis = this;
        var observations = $( '#liste-obs' ).data();

        if ( this.debug ) {
                console.log( observations );
        }
        if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
                this.afficherPanneau( '#dialogue-zero-obs' );
        } else {
                $( window ).on( 'beforeunload', function( event ) {
                        return lthis.utils.msgTraduction( 'rechargement-page' );
                });
                this.nbObsEnCours         = 1;
                this.nbObsTransmises      = 0;
                this.totalObsATransmettre = $.map( observations, function( n, i ) {
                        return i;
                }).length;
                this.depilerObsPourEnvoi();
        }

        return false;
};

LichensApa.prototype.depilerObsPourEnvoi = function() {
        var observations = $( '#liste-obs' ).data();

        // la boucle est factice car on utilise un tableau
        // dont on a besoin de n'extraire que le premier élément
        // or javascript n'a pas de méthode cross browsers pour extraire les clés
        // TODO: utiliser var.keys quand ça sera plus répandu
        // ou bien utiliser un vrai tableau et pas un objet
        for ( var obsNum in observations ) {
                var obsATransmettre = {
                        'projet'  : this.tagProjet,
                        'tag-obs' : this.tagObs,
                        'tag-img' : this.tagImg
                };
                var utilisateur = {
                        id_utilisateur : this.infosUtilisateur.id,
                        prenom         : this.infosUtilisateur.prenom,
                        nom            : this.infosUtilisateur.nom,
                        courriel       : $( '#courriel' ).val()
                };

                obsATransmettre['utilisateur'] = utilisateur;
                obsATransmettre[obsNum]        = observations[obsNum];

                var idObsNumerique = obsNum.replace( 'obsId', '' );

                if( '' !== idObsNumerique ) {
                        this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
                }
                break;
        }
};

LichensApa.prototype.envoyerObsAuCel = function( idObs, observation ) {
        const lthis     = this;
        var erreurMsg = '';

        $.ajax({
                url        : lthis.serviceSaisieUrl,
                type       : 'POST',
                data       : observation,
                dataType   : 'json',
                beforeSend : function() {
                        $( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
                        $( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
                        $( '.alert-txt' ).empty();
                        $( '.alert-txt .msg-erreur' ).remove();
                        $( '.alert-txt .msg-debug' ).remove();
                        $( '#chargement' ).removeClass( 'hidden' );
                },
                success    : function( data, textStatus, jqXHR ) {
                        // mise à jour du nombre d'obs à transmettre
                        // et suppression de l'obs
                        lthis.supprimerObsParId( idObs );
                        lthis.nbObsEnCours++;
                        // mise à jour du statut
                        lthis.mettreAJourProgression();
                        if( 0 < lthis.obsNbre ) {
                                // dépilement de la suivante
                                lthis.depilerObsPourEnvoi();
                        }
                },
                statusCode  : {
                        500 : function( jqXHR, textStatus, errorThrown ) {
                                erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
                                }
                },
                error        : function( jqXHR, textStatus, errorThrown ) {
                        erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
                        try {
                                reponse = jQuery.parseJSON( jqXHR.responseText );
                                if ( null !== reponse ) {
                                        $.each( reponse, function( cle, valeur ) {
                                                erreurMsg += valeur + '\n';
                                        });
                                }
                        } catch( e ) {
                                erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
                        }
                },
                complete      : function( jqXHR, textStatus ) {
                        var debugMsg = extraireEnteteDebug( jqXHR );

                        if ( '' !== erreurMsg ) {
                                if ( lthis.debug ) {
                                        $( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
                                        $( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
                                }
                                var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
                                        'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
                                        '&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;

                                // mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
                                $( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
                                // window.location.hash = 'obs' + idObs;

                                $( '#dialogue-obs-transaction-ko .alert-txt' ).append(
                                        $( '#tpl-transmission-ko' ).clone()
                                                .find( '.courriel-erreur' )
                                                .attr( 'href', hrefCourriel )
                                                .end()
                                                .html()
                                );
                                $( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
                                $( '#chargement' ).addClass( 'hidden' );
                                lthis.initialiserBarreProgression;
                        } else {
                                if ( lthis.debug ) {
                                        $( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
                                }
                                if( 0 === lthis.obsNbre ) {
                                        setTimeout( function() {
                                                $( '#chargement,#bloc-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
                                                $( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
                                                $( '#dialogue-obs-transaction-ok,#bouton-poursuivre' ).removeClass( 'hidden' );
                                        }, 1500 );
                                }
                        }
                }
        });
};

LichensApa.prototype.mettreAJourProgression = function() {
        this.nbObsTransmises++;

        var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;

        $( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
        $( '#barre-progression-upload' ).css( 'width', pct + '%' );
        $( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
        if( 0 === this.obsNbre ) {
                $( '.progress' ).removeClass( 'active' );
                $( '.progress' ).removeClass( 'progress-bar-striped' );
        }
};

LichensApa.prototype.initialiserBarreProgression = function() {
        $( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
        $( '#barre-progression-upload' ).css( 'width', '0%' );
        $( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
        $( '.progress' ).addClass( 'active' );
        $( '.progress' ).addClass( 'progress-bar-striped' );
};

// Form Validator *************************************************************/
LichensApa.prototype.configurerFormValidator = function() {
        const lthis = this;

        $.validator.addMethod(
                'dateCel',
                function ( value, element ) {
                        return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
                },
                lthis.utils.msgTraduction( 'date-incomplete' )
        );

        $.validator.addMethod(
                'userEmailOk',
                function ( value, element ) {
                        return ( lthis.utils.valOk( value ) );
                },
                ''
        );

        $.extend( $.validator.defaults, {
                errorElement: 'span',
                errorPlacement: function( error, element ) {
                        element.after( error );
                },
                onfocusout: function( element ) {
                        if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
                                if ( $( element ).valid() ) {
                                        $( element ).closest( '.control-group' ).removeClass( 'error' );
                                } else {
                                        $( element ).closest( '.control-group' ).addClass( 'error' );
                                }
                        }
                },
                onkeyup : function( element ) {
                        if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
                                if ( $( element ).valid() ) {
                                        $( element ).closest( '.control-group' ).removeClass( 'error' );
                                } else {
                                        $( element ).closest( '.control-group' ).addClass( 'error' );
                                }
                        }
                },
                unhighlight: function( element ) {
                        if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
                                $( element ).closest( '.control-group' ).removeClass( 'error' );
                        }
                },
                highlight: function( element ) {
                        $( element ).closest( '.control-group' ).addClass( 'error' );
                }
        });
};

LichensApa.prototype.definirReglesFormValidator = function() {
        const lthis = this;

        $( 'input[type=date]' ).on( 'input', function() {
                $( this ).valid();
        });
        // Validation Taxon si pas de miniature
        $( '#taxon' ).on( 'change', function() {
                var images = lthis.utils.valOk( $( '#miniatures .miniature' ) );
                lthis.validerTaxonImage( lthis.utils.valOk( $( this ).val() ), images );
        });

        // // Validation miniatures avec MutationObserver
        // this.surPresenceAbsenceMiniature();

        $( '#form-lichens' ).validate({
                rules : {
                        'choisir-arbre' : {
                                required : true,
                                minlength : 1
                        },
                        'obs-date' : {
                                required : true,
                                'dateCel' : true
                        },
                        certitude : {
                                required : true,
                                minlength : 1
                        }
                }
        });
        $( '#form-observateur' ).validate({
                rules : {
                        courriel : {
                                required : true,
                                minlength : 1,
                                email : true,
                                'userEmailOk' : true
                        },
                        mdp : {
                                required : true,
                                minlength : 1
                        }
                }
        });
        $( '#connexion,#inscription,#oublie' ).click( function() {
                $( '#tb-observateur .control-group' ).removeClass( 'error' );
        });
};

LichensApa.prototype.validerTaxonImage = function( taxon = false, images = false ) {
        var taxonOuImage = ( images || taxon );
        if ( images || taxon ) {
                this.masquerPanneau( '#dialogue-taxon-or-image' );
                $( '#bloc-taxon' ).removeClass( 'error' )
                        .find( 'span.error' ).hide();
                $( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
                $( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
                // faire passer la certitude à 'à déterminer' si on a une image et pas de taxon
                if( !taxon ) {
                        $( '#certitude' ).find( 'option' ).each( function() {
                                if ( $( this ).hasClass( 'aDeterminer' ) ) {
                                        $( this ).attr( 'selected', true );
                                } else {
                                        $( this ).attr( 'selected', false );
                                }
                        });
                }
        } else {
                this.afficherPanneau( '#dialogue-taxon-or-image' );
                $( '#bloc-taxon' ).addClass( 'error' )
                        .find( 'span.error' ).show();
                $( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
                $( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
        }
        return ( images || taxon );
};

/**
 * Valide le formulaire au click sur un bouton "suivant"
 */
LichensApa.prototype.validerLichens = function() {
        const images       = this.utils.valOk( $( '#miniatures .miniature' ) );
        const taxon        = this.utils.valOk( $( '#taxon' ).val() );
        const taxonOuImage = this.validerTaxonImage( taxon, images );
        const observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
        const obs          = $( '#form-lichens' ).valid();

        // panneau observateur
        if ( observateur ) {
                this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
                $( '#tb-observateur .control-group' ).removeClass( 'error' );
        } else {
                this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
                $( '#tb-observateur .control-group' ).addClass( 'error' );
        }

        return ( observateur && obs && taxonOuImage );
};

// Controle des panneaux d'infos **********************************************/

LichensApa.prototype.afficherPanneau = function( selecteur ) {
        $( selecteur )
                .removeClass( 'hidden' )
                .hide()
                .show( 600 )
                .delay( this.dureeMessage )
                .hide( 600 );
        $( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
};

LichensApa.prototype.masquerPanneau = function( selecteur ) {
        $( selecteur ).addClass( 'hidden' );
};

LichensApa.prototype.fermerPanneauAlert = function() {
        $( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
};

// lib hors objet --

/**
* Stope l'évènement courant quand on clique sur un lien.
* Utile pour Chrome, Safari...
*/
function arreter( event ) {
        if ( event.stopPropagation ) {
                event.stopPropagation();
        }
        if ( event.preventDefault ) {
                event.preventDefault();
        }

        return false;
}

/**
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
 * @param jqXHR
 * @returns {String}
 */
function extraireEnteteDebug( jqXHR ) {
        var msgDebug = '';

        if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
                var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
                if ( null !== debugInfos ) {
                        $.each( debugInfos, function( cle, valeur ) {
                                msgDebug += valeur + '\n';
                        });
                }
        }

        return msgDebug;
}

/*
 * jQuery UI Autocomplete HTML Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 *
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
 */
( function( $ ) {
        var proto      = $.ui.autocomplete.prototype,
                initSource = proto._initSource;

        LichensApa.prototype.filter = function( array, term ) {
                var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );

                return $.grep( array, function( value ) {

                        return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
                });
        }
        $.extend( proto, {
                _initSource: function() {
                        if ( this.options.html && $.isArray( this.options.source ) ) {
                                this.source = function( request, response ) {
                                        response( filter( this.options.source, request.term ) );
                                };
                        } else {
                                initSource.call( this );
                        }
                },
                _renderItem: function( ul, item) {
                        if ( item.retenu ) {
                                item.label = '<strong>' + item.label + '</strong>';
                        }

                        return $( '<li></li>' )
                                .data( 'item.autocomplete', item )
                                .append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
                                .appendTo( ul );
                }
        });
})( jQuery );