Subversion Repositories eFlore/Applications.cel

Rev

Rev 3811 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * Constructeur WidgetSaisie par défaut
 */
function WidgetSaisie( proprietes ) {
        if  ( valOk(proprietes) ) {
                this.urlWidgets                        = proprietes.urlWidgets;
                this.projet                            = proprietes.projet;
                this.idProjet                          = proprietes.idProjet;
                this.tagsMotsCles                      = proprietes.tagsMotsCles;
                this.mode                              = proprietes.mode;
                this.langue                            = proprietes.langue;
                this.serviceAnnuaireIdUrl              = proprietes.serviceAnnuaireIdUrl;
                this.serviceNomCommuneUrl              = proprietes.serviceNomCommuneUrl;
                this.serviceNomCommuneUrlAlt           = proprietes.serviceNomCommuneUrlAlt;
                this.debug                             = proprietes.debug;
                this.html5                             = proprietes.html5;
                this.serviceSaisieUrl                  = proprietes.serviceSaisieUrl;
                this.serviceObsUrl                     = proprietes.serviceObsUrl;
                this.chargementImageIconeUrl           = proprietes.chargementImageIconeUrl;
                this.pasDePhotoIconeUrl                = proprietes.pasDePhotoIconeUrl;
                this.autocompletionElementsNbre        = proprietes.autocompletionElementsNbre;
                this.serviceAutocompletionNomSciUrl    = proprietes.serviceAutocompletionNomSciUrl;
                this.serviceAutocompletionNomSciUrlTpl = proprietes.serviceAutocompletionNomSciUrlTpl;
                this.dureeMessage                      = proprietes.dureeMessage;
                this.obsMaxNbre                        = proprietes.obsMaxNbre;
                this.tagImg                            = proprietes.tagImg;
                this.tagObs                            = proprietes.tagObs;
                this.obsId                             = proprietes.obsId;
                this.nomSciReferentiel                 = proprietes.nomSciReferentiel;
                this.especeImposee                     = proprietes.especeImposee;
                this.infosEspeceImposee                = proprietes.infosEspeceImposee;
                this.referentielImpose                 = proprietes.referentielImpose;
                this.isTaxonListe                      = proprietes.isTaxonListe;
                this.utils                             = utils;
                this.msgs                              = utils.msgs;
        }
        this.urlRacine            = window.location.origin;
        this.obsNbre              = 0;
        this.nbObsEnCours         = 1;
        this.totalObsATransmettre = 0;
        this.nbObsTransmises      = 0;
        this.observer             = null;
        this.isASL                = false;
}
WidgetSaisie.prototype = new WidgetsSaisiesCommun();

var valOk = WidgetSaisie.prototype.valOk;

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

        this.initFormConnection();
        if ( this.valOk( this.obsId ) ) {
                this.chargerInfoObs();
        }
        if( this.isTaxonListe ) {
                this.initFormTaxonListe();
        } else {
                this.ajouterAutocompletionNoms();
        }
        // au rafraichissement de la page,
        // les input date semblent conserver la valeur entrée précedemment
        // c'est voulu après la création d'une obs mais pas quand la page est actualisée
        // Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
        $( 'input[type=date]' ).each( function () {
                ( lthis.valOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
        });
        this.configurerFormValidator();
        this.definirReglesFormValidator();

        if( this.especeImposee ) {
                $( '#taxon' ).attr( 'disabled', 'disabled' );
                $( '#taxon-input-groupe' ).attr( 'title', '' );
                // Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
                var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
                        nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet,
                        debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
                if ( -1 !== debutAnneRefBiblio ) {
                        nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
                }
                // fin bricolage cracra
                var infosAssociee = {
                        label : infosEspeceImposee.nom_sci_complet,
                        value : infosEspeceImposee.nom_sci_complet,
                        nt : infosEspeceImposee.num_taxonomique,
                        nomSel : infosEspeceImposee.nom_sci,
                        nomSelComplet : infosEspeceImposee.nom_sci_complet,
                        numNomSel : infosEspeceImposee.id,
                        nomRet : nomRetenuComplet,
                        numNomRet : infosEspeceImposee['nom_retenu.id'],
                        famille : infosEspeceImposee.famille,
                        retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
                };
                $( '#taxon' ).data( infosAssociee );
        }
};

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

        // identité
        this.initEvtsConnection();
        // on location, initialisation de la géoloc
        this.initEvtsGeoloc();
        // Sur téléchargement image
        this.initEvtsFichier();

        $( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
        // Création / Suppression / Transmission des obs
        // Défilement des miniatures dans le résumé obs
        this.initEvtsObs();
        // Alertes et aides
        this.initEvtsAlertes();
        // message avant de quitter le formulaire
        this.confirmerSortie();
};

// Identité Observateur par courriel
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
        const lthis = this;

        var courriel = $( '#courriel' ).val();
        var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;

        if ( this.valOk( courriel ) ) {
                $.ajax({
                        url : urlAnnuaire,
                        type : 'GET',
                        success : function( data, textStatus, jqXHR ) {
                                if ( lthis.debug ) {
                                        console.log( 'SUCCESS: ' + textStatus );
                                }
                                if ( lthis.valOk( data ) && lthis.valOk( data[courriel] ) ) {
                                        var infos = data[courriel];
                                        lthis.surSuccesCompletionCourriel( infos, courriel );
                                } else {
                                        lthis.surErreurCompletionCourriel();
                                }
                        },
                        error : function( jqXHR, textStatus, errorThrown ) {
                                if ( lthis.debug ) {
                                        console.log( 'ERREUR: '+ textStatus );
                                }
                                lthis.surErreurCompletionCourriel();
                        },
                        complete : function( jqXHR, textStatus ) {
                                if ( lthis.debug ) {
                                        console.log( 'COMPLETE: '+ textStatus );
                                }
                        }
                });
        }
};

// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
        if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
                if ( !this.valOk( $( '#warning-identite' ) ) ) {
                        $( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
                }
                $( '#inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
                $( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
                $( '.nav.control-group' ).addClass( 'error' );
        }
};

// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
        $( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
        $( '#warning-identite' ).remove();
        $( '.nav.control-group' ).removeClass( 'error' );
        $( '#prenom, #nom, #courriel_confirmation' ).val( '' ).removeAttr( 'disabled' );
};

WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
        if ( this.valOk( event.which, true, 13 ) ) {
                this.requeterIdentiteCourriel();
                event.preventDefault();
                event.stopPropagation();
        }
};

WidgetSaisie.prototype.reduireVoletIdentite = function() {
        if ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ) {
                $( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
                $( '#bienvenue').removeClass( 'hidden' );
                $( '#inscription, #zone-courriel' ).addClass( 'hidden' );
                if ( lthis.valOk( $( '#nom' ).val() ) && lthis.valOk( $( '#prenom' ).val() ) ) {
                        $( '#zone-prenom-nom' ).addClass( 'hidden' );
                        $( '#bienvenue-prenom' ).text( ' ' + $( '#prenom' ).val() );
                        $( '#bienvenue-nom' ).text( ' ' + $( '#nom' ).val() );
                } else {
                        $( '#zone-prenom-nom' ).removeClass( 'hidden' );
                        $( '#bienvenue-prenom,#bienvenue-nom' ).text( '' );
                }
        } else {
                $( '#bouton-connexion, #creation-compte' ).removeClass( 'hidden' );
                $( '#bienvenue').addClass( 'hidden' );
        }
};


WidgetSaisie.prototype.formaterNom = function() {
        $( '#nom' ).val( $( '#nom' ).val().toUpperCase() );
};

WidgetSaisie.prototype.formaterPrenom = function() {
        var prenom     = new Array(),
                mots       = $( '#prenom' ).val().split( ' ' ),
                motsLength = mots.length;

        for ( var i = 0; i < motsLength; i++ ) {
                var mot = mots[i];
                if ( 0 <= mot.indexOf( '-' ) ) {
                        var prenomCompose = new Array(),
                                motsComposes = mot.split( '-' )
                                motsComposesLength = motsComposes.length;
                        for ( var j = 0; j < motsComposesLength; j++ ) {
                                var motSimple    = motsComposes[j],
                                        motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);

                                prenomCompose.push( motMajuscule );
                        }
                        prenom.push( prenomCompose.join( '-' ) );
                } else {
                        var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
                        prenom.push( motMajuscule );
                }
        }
        $( '#prenom' ).val( prenom.join( ' ' ) );
};

WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
        this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
        return false;
};

// Préchargement des infos-obs ************************************************/
WidgetSaisie.prototype.chargerInfoObs = function() {
        const lthis = this;

        var urlObs = this.serviceObsUrl + '/' + this.obsId;

        $.ajax({
                url: urlObs,
                type: 'GET',
                success: function( data, textStatus, jqXHR ) {
                        if ( lthis.valOk( data ) ) {
                                lthis.prechargerForm( data );
                        } else {
                                lthis.surErreurChargementInfosObs.bind( lthis );
                        }
                },
                error: function( jqXHR, textStatus, errorThrown ) {
                        lthis.surErreurChargementInfosObs();
                }
        });
};

// @TODO faire mieux que ça !
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
        this.activerModale( this.msgTraduction( 'erreur-chargement' ) );
};

WidgetSaisie.prototype.prechargerForm = function( data ) {
        $( '#milieu' ).val( data.milieu );
        $( '#commune-nom' ).text( data.zoneGeo );
        if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
          // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
          $( '#commune-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
        }

        if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
                // $cartoRemplacee = $( '#tb-geolocation' ),
                // suffixe = '',
                // layer = 'osm',
                // zoomInit = 18
                var typeLocalisation = $( '#top' ).data( 'type-loc' ),
                        donnesResetCarto = {
                        latitude         : data.latitude,
                        longitude        : data.longitude,
                        typeLocalisation : typeLocalisation
                };
                this.transfererCarto( donnesResetCarto );
        }
};

// Ajouter Obs ****************************************************************/
/**
 * Retourne un Array contenant les valeurs des champs étendus
 */
WidgetSaisie.prototype.getObsChpSpecifiques = function() {
        const lthis = this;

        var champs    = new Array(),
                $thisForm = $( '#form-supp' ),
                elements  =
                        'input[type=text]:not(.collect-other),'+
                        'input[type=checkbox]:checked,'+
                        'input[type=radio]:checked,'+
                        'input[type=email],'+
                        'input[type=number],'+
                        'input[type=range],'+
                        'input[type=date],'+
                        'textarea,'+
                        '.select',
                retour    = new Array();

        $( elements, $thisForm ).each( function() {
                if ( lthis.valOk( $( this ).val() ) && ( lthis.valOk( $( this ).attr( 'name' ) ) || lthis.valOk( $( this ).data( 'name' ) ) ) ) {
                        var valeur = $( this ).val(),
                                cle    = ( lthis.valOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
                        if ( cle in champs ) {
                                champs[cle] += ';' + valeur;
                        } else {
                                champs[cle] = valeur;
                        }
                }
        });
        for ( var key in champs ) {
                retour.push({ 'cle' : key , 'valeur' : champs[key] });
        }
        if ( this.valOk( $( '#coord-lineaire' ).val() ) ) {
                retour.push({ 'cle' : 'coordonnees-rue-ou-lineaire' , 'valeur' : $( '#coord-lineaire' ).val() });
        }
        return retour;
};

WidgetSaisie.prototype.reinitialiserForm = function() {
        this.supprimerMiniatures();
        if( !this.especeImposee ) {
                $( '#taxon' ).val( '' );
                $( '#taxon' ).data( 'numNomSel', '' )
                        .data( 'nomRet','' )
                        .data( 'numNomRet', '' )
                        .data( 'nt', '' )
                        .data( 'famille', '' );
                if( this.isTaxonListe ) {
                        $( '#taxon-liste' ).find( 'option' ).each( function() {
                                if ( $( this ).hasClass( 'choisir' ) ) {
                                        $( this ).attr( 'selected', true );
                                } else {
                                        $( this ).attr( 'selected', false );
                                }
                        });
                        $( '#taxon-input-groupe' ).addClass( 'hidden' );
                        $('#taxon-autre').val('');
                }
        }
        if ( this.valOk( $( '#form-supp' ) ) ) {
                $( '#form-supp' ).validate().resetForm();
        }
};

// Géolocalisation *************************************************************/
/**
 * Fonction handler de l'évenement location du module tb-geoloc
 */
WidgetSaisie.prototype.locationHandler = function( location ) {
        var locDatas = location.originalEvent.detail;

        if ( this.valOk( locDatas ) ) {
                console.log( locDatas );
                var geometry      = JSON.stringify( locDatas.geometry );
                var altitude      = ( this.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
                var pays          = ( this.valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR';
                var latitude      = '';
                var longitude     = '';
                var coordLineaire = '';
                var nomCommune    = '';
                var communeInsee  = '';

                if ( this.valOk( locDatas.geometry.coordinates ) ) {
                        if ( 'Point' === locDatas.geometry.type ) {
                                if ( this.valOk( locDatas.geometry.coordinates[0] ) ) {
                                        longitude = locDatas.geometry.coordinates[0];
                                }
                                if ( this.valOk( locDatas.geometry.coordinates[1] ) ) {
                                        latitude = locDatas.geometry.coordinates[1];
                                }
                        } else if ( 'LineString' === locDatas.geometry.type ) {// on a besoin que d'un point de la rue
                                coordLineaire = JSON.stringify( locDatas.geometry.coordinates );
                                if ( this.valOk( locDatas.geometry.coordinates[0][0] ) ) {
                                        longitude = locDatas.geometry.coordinates[0][0];
                                }
                                if ( this.valOk( locDatas.geometry.coordinates[0][1] ) ){
                                        latitude = locDatas.geometry.coordinates[0][1];
                                }
                        }
                }
                if ( this.valOk( locDatas.inseeData ) ) {
                        nomCommune = locDatas.inseeData.nom;
                        communeInsee = ( this.valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
                } else if ( this.valOk( locDatas.locality ) ) {
                        nomCommune = locDatas.locality;
                } else if ( this.valOk( locDatas.locality ) ) {
                        nomCommune = locDatas.osmCounty;
                }
                $( '#geometry' ).val( geometry );
                $( '#coord-lineaire' ).val( coordLineaire );
                $( '#latitude' ).val( latitude );
                $( '#longitude' ).val( longitude );
                $( '#commune-nom' ).val( nomCommune );
                $( '#commune-insee' ).val( communeInsee );
                $( '#altitude' ).val( altitude );
                $( '#pays' ).val( pays );
                if ( this.valOk( $( '#latitude' ).val() ) && this.valOk( $( '#longitude' ).val() ) ) {
                        $( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
                } else {
                        $( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
                }
        } else {
                console.log( 'Error location' );
        }
}

// Form Validator *************************************************************/
WidgetSaisie.prototype.chpEtendusValidation = function() {
        const lthis = this;

        var $thisForm = $( '#form-supp' ),
                elements  =
                        '.checkbox,'+
                        '.radio,'+
                        '.checkboxes,'+
                        '.select,'+
                        'textarea,'+
                        'input[type=text]:not(.collect-other),'+
                        'input[type=email],'+
                        'input[type=number],'+
                        'input[type=range],'+
                        'input[type=date]',
                speFields = ['checkbox','radio','checkboxes','select'],
                spefieldsCount = speFields.length,
                chpSuppValidation = {
                        rules : {},
                        messages : {},
                        minmax : []
                },
                errors = {},
                namesListFields = [],
                picked = '';

        $( elements, $thisForm ).each( function() {
                for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
                        if ( lthis.valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !lthis.valOk( chpSuppValidation.rules[ dataName ] ) ) {

                                var dataName = $( this ).data( 'name' );

                                namesListFields.push( dataName );
                                chpSuppValidation.rules[ dataName ] = { required : true };
                                if ( lthis.valOk( $( '.other', $( this ) ) ) ) {
                                        picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
                                        chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
                                                required : '#other-' + dataName.replace( '[]', '' ) + picked,
                                                minlength: 1
                                        };
                                        chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
                                }
                                chpSuppValidation.rules[ dataName ]['listFields'] = true;
                                chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
                                errors[dataName] = '.' + speFields[fieldsClass];
                        }
                }
                if ( lthis.valOk( $( this ).attr( 'name' ) ) && lthis.valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
                        chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
                        if(
                                ( lthis.valOk( $( this ).attr( 'type' ), true, 'number' ) || lthis.valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
                                ( lthis.valOk( $( this )[0].min ) || lthis.valOk( $( this )[0].max ) )
                        ) {
                                chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
                                chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
                        }
                }
        });
        if ( this.valOk( chpSuppValidation.rules ) ) {
                $.each( chpSuppValidation.rules, function( key ) {
                        if ( !lthis.valOk( chpSuppValidation.messages[key] ) ) {
                                chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
                        }
                });
                if ( 0 < Object.keys( errors ).length ) {
                        chpSuppValidation['errors'] = errors;
                }
        }
        return chpSuppValidation;
};

WidgetSaisie.prototype.validerMinMax = function( element ) {
        var mMCond      = new Boolean(),
                minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
                maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
                messageMnMx = 'La valeur entrée doit être',
                returnMnMx  = { cond : true , message : '' };

        if(
                ( this.valOk( element.type, true, 'number' ) || this.valOk( element.type, true, 'range' ) ) &&
                ( this.valOk( element.min ) || this.valOk( element.max ) )
        ) {
                if ( element.min && element.max ) {
                        messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
                        mnMxCond     = ( minCond && maxCond );
                } else if ( element.min ) {
                        messageMnMx += ' supérieure à ' + element.min;
                        mnMxCond     = minCond;
                } else {
                        messageMnMx += ' inférieure à ' + element.max;
                        mnMxCond     = maxCond;
                }
                returnMnMx.cond    = mnMxCond;
                returnMnMx.message = messageMnMx;
        }
        return returnMnMx;

};

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

        var formSuppValidation = this.chpEtendusValidation();

        $( '#form-supp' ).validate({
                onclick : function( element ) {
                        if (
                                (
                                        lthis.valOk( element.type, true, 'checkbox' ) ||
                                        lthis.valOk( element.type, true, 'radio' )
                                ) &&
                                (
                                        !lthis.valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
                                        lthis.valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
                                        !lthis.valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
                                        $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
                                        (
                                                $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
                                                $( element ).closest( '.control-group' ).hasClass('error')
                                        )
                                )
                        ) {
                                $( element ).valid();
                                if ( $( element ).valid() ) {
                                        $( element ).closest( '.control-group' ).removeClass( 'error' );
                                        $( element ).next( $( 'span.error' ) ).remove();
                                } else {
                                        $( element ).closest( '.control-group' ).addClass( 'error' );
                                }
                        }
                        return false;
                },
                rules : formSuppValidation.rules,
                messages : formSuppValidation.messages,
                errorPlacement : function( error , element ) {
                        if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
                                var errorsKeys = Object.keys( formSuppValidation.errors ),
                                        thisKey = '',
                                        errorsFlag = true;
                                for ( i = 0 ; i < errorsKeys.length ; i++ ) {
                                        thisKey = errorsKeys[i];
                                        if( $( element ).attr( 'name' ) === thisKey ) {
                                                $( formSuppValidation.errors[thisKey] ).append( error );
                                                errorsFlag = false;
                                        }
                                }
                                if ( errorsFlag ) {
                                        error.insertAfter( element );
                                }
                        } else {
                                error.insertAfter( element );
                        }
                }
        });
        $( '#form-supp .select' ).change( function() {
                $( this ).valid();
        });
        $( 'input[type=date]' ).on( 'input', function() {
                $( this ).valid();
        });
        // Validation Taxon si pas de miniature
        $( '#taxon' ).on( 'change', function() {
                var images = lthis.valOk( $( '#miniatures .miniature' ) );
                lthis.validerTaxonImage( lthis.valOk( $( this ).val() ), images );
        });
        // Validation miniatures avec MutationObserver
        this.surPresenceAbsenceMiniature();
        $( '#form-observation' ).validate({
                rules : {
                        date_releve : {
                                required : true,
                                'dateCel' : true
                        },
                        latitude : {
                                required : true,
                                minlength : 1,
                                range : [-90, 90]
                        },
                        longitude : {
                                required : true,
                                minlength : 1,
                                range : [-180, 180]
                        }
                }
        });
        $( '#form-observateur' ).validate({
                rules : {
                        courriel : {
                                required : true,
                                email : true,
                                'userEmailOk' : true
                        },
                        courriel_confirmation : {
                                required : true,
                                equalTo : '#courriel'
                        }
                }
        });
        $( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
                $( '.nav.control-group' ).removeClass( 'error' );
        });
};

WidgetSaisie.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();
        } 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 );
};

WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
        const lthis = this;

        // voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
        // Selectionne le noeud dont les mutations seront observées
        var targetNode = document.getElementById( 'miniatures' );
        // Fonction callback à éxécuter quand une mutation est observée
        var callback = function( mutationsList ) {
                for( var mutation of mutationsList ) {
                        var taxon = lthis.valOk( $( '#taxon' ).val() );

                        images = ( 0 < mutation.target.childElementCount );
                        lthis.validerTaxonImage( taxon, images );
                }
        };
        // Créé une instance de l'observateur lié à la fonction de callback
        this.observer = new MutationObserver( callback );
        // Commence à observer le noeud cible pour les mutations précédemment configurées
        this.observer.observe( targetNode, { childList: true } );
};

WidgetSaisie.prototype.validerForm = function() {
        const lthis = this;

        var observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() );
        var obs          = $( '#form-observation' ).valid();
        var geoloc       = ( this.valOk( $( '#latitude' ).val() ) && this.valOk( $( '#longitude' ).val() ) ) ;
        var images       = this.valOk( $( '#miniatures .miniature' ) );
        var taxon        = this.valOk( $( '#taxon' ).val() );
        // validation et panneau taxon/images
        var taxonOuImage = this.validerTaxonImage( taxon, images );
        var chpsSupp     = new Boolean();
        if ( this.valOk( $( '#form-supp' ) ) ) {
                chpsSupp = ( function () {
                        var otherFlag = $( '#form-supp' ).valid();
                        if( lthis.valOk( $( '.other', $( '#form-supp' ) ) ) ) {
                                $( '.other', $( '#form-supp' ) ).each( function() {
                                        var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
                                                if ( $( this ).is( picked ) && lthis.valOk( $( this ).val(), true, 'other' ) ) {
                                                        otherFlag = false;
                                                }
                                });
                        }
                        return otherFlag;
                })();
        } else {
                chpsSupp = true;
        }
        // panneau geoloc
        if ( geoloc ) {
                this.masquerPanneau( '#dialogue-geoloc-ko' );
                $( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
        } else{
                this.afficherPanneau( '#dialogue-geoloc-ko' );
                $( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
        }
        // panneau observateur
        if ( observateur ) {
                this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
                $( '.nav.control-group' ).removeClass( 'error' );
        } else {
                this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
                $( '.nav.control-group' ).addClass( 'error' );
        }
        return ( observateur && obs && geoloc && taxonOuImage && chpsSupp );
};

// Referentiel ****************************************************************/
// N'est pas utilisé en cas de taxon-liste
WidgetSaisie.prototype.surChangementReferentiel = function() {
        this.nomSciReferentiel = $( '#referentiel' ).val();
        //réinitialise taxon.val
        $( '#taxon' ).val( '' );
        $( '#taxon' ).data( 'numNomSel', '' );
};