Subversion Repositories eFlore/Applications.cel

Rev

Rev 3334 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3318 idir 1
/**
2
 * Constructeur LichensLg par défaut
3
 */
4
function LichensLg() {
5
	this.obsNbre = 0;
6
	this.nbObsEnCours = 1;
7
	this.totalObsATransmettre = 0;
8
	this.nbObsTransmises = 0;
9
	this.debug = null;
10
	this.html5 = null;
11
	this.tagProjet = null;
12
	this.tagImg = null;
13
	this.tagObs = null;
14
	this.separationTagImg = null;
15
	this.separationTagObs = null;
16
	this.serviceSaisieUrl = null;
17
	this.chargementImageIconeUrl = null;
18
	this.pasDePhotoIconeUrl = null;
19
	this.nomSciReferentiel = null;
20
	this.autocompletionElementsNbre = null;
21
	this.referentielImpose = null;
22
	this.serviceAutocompletionNomSciUrl = null;
23
	this.serviceAutocompletionNomSciUrlTpl = null;
24
	this.obsMaxNbre = null;
25
	this.dureeMessage = null;
26
	this.infosUtilisateur = {};
27
	this.releveDatas = null;
28
	this.utils = new UtilsLg();
29
}
30
 
31
LichensLg.prototype.init = function() {
32
	this.initForm();
33
	this.initEvts();
34
};
35
 
36
/**
37
 * Initialise le formulaire, les validateurs, les listes de complétion...
38
 */
39
LichensLg.prototype.initForm = function() {
40
	const lthis = this;
41
 
42
	this.ajouterAutocompletionNoms();
43
	this.configurerFormValidator();
44
	this.definirReglesFormValidator();
45
};
46
 
47
/**
48
 * Initialise les écouteurs d'événements
49
 */
50
LichensLg.prototype.initEvts = function() {
51
	const lthis = this;
52
 
53
	var releveDatas = [];
54
	this.infosUtilisateur.id     = $( '#id_utilisateur' ).val();
55
	this.infosUtilisateur.prenom = $( '#prenom' ).val();
56
	this.infosUtilisateur.nom    = $( '#nom' ).val();
57
 
58
	$( '#bouton-nouveau-releve' ).click( function() {
59
		$( '#releve-data' ).val( '' );
60
		if ( lthis.utils.valOk( lthis.infosUtilisateur.id ) ) {
61
			lthis.utils.chargerForm( 'arbres', lthis );
62
			$( '#bouton-list-releves' ).removeClass( 'hidden' );
63
		}
64
		$( '#table-releves' ).addClass( 'hidden' );
65
	});
66
 
67
	if( this.utils.valOk( this.infosUtilisateur.id ) && this.utils.valOk( $( '#releve-data' ).val() ) ) {
68
		this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
69
		if ( this.utils.valOk( this.releveDatas[0].utilisateur, true, this.infosUtilisateur.id ) ) {
70
 
71
			// Sur téléchargement image
72
			$( '#fichier' ).on( 'change', function ( e ) {
73
				arreter( e );
74
 
75
				var options        = {
76
					success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
77
					dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
78
					resetForm: true // reset the form after successful submit
79
				};
80
 
81
				$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
82
 
83
				var imgCheminTmp    = $( '#fichier' ).val(),
84
					formatImgOk     = lthis.verifierFormat( imgCheminTmp ),
85
					imgNonDupliquee = lthis.verifierDuplication( imgCheminTmp );
86
 
87
				if( formatImgOk && imgNonDupliquee ) {
88
					$( '#form-upload' ).ajaxSubmit( options );
89
				} else {
90
					$( '#form-upload' )[0].reset();
91
					if ( !formatImgOk ) {
92
						window.alert( lthis.utils.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
93
					}
94
					if ( !imgNonDupliquee ) {
95
						window.alert( lthis.utils.msgTraduction( 'image-deja-chargee' ) );
96
					}
97
				}
98
				return false;
99
			});
100
			$( 'body' ).on( 'click', '.effacer-miniature', function() {
101
				$( this ).parent().remove();
102
			});
103
 
104
			$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
105
			$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
106
			// défilement des miniatures dans le résumé obs
107
			$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
108
				event.preventDefault();
109
				lthis.defilerMiniatures( $( this ) );
110
			});
111
			$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
112
				event.preventDefault();
113
				lthis.defilerMiniatures( $( this ) );
114
			});
115
			// mécanisme de suppression d'une obs
116
			$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
117
				var that = this,
118
				suppObs = lthis.supprimerObs.bind( lthis );
119
				// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
120
				suppObs( that );
121
			});
122
 
123
			$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
124
 
125
			// chargement lichens
126
			$( '#bouton-poursuivre' ).on( 'click', function() {
127
				var nomSquelette = $( this ).data( 'load' );
128
				$( '#charger-form' ).data( 'load', nomSquelette );
129
				lthis.utils.chargerForm( nomSquelette, lthis );
130
				$( 'html, body' ).stop().animate({
131
					scrollTop: $( '#charger-form' ).offset().top
132
				}, 300 );
133
			});
134
 
135
			// Alertes et tooltips
136
			$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
137
			$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
138
			// $( '.has-tooltip' ).tooltip( 'enable' );
139
		}
140
	}
141
};
142
 
143
// Préchargement des infos-obs ************************************************/
144
 
145
/**
146
 * Callback dans le chargement du formulaire dans #charger-form
147
 */
148
LichensLg.prototype.chargerSquelette = function( squelette, nomSquelette ) {
149
	switch( nomSquelette ) {
150
		case 'lichens' :
151
			this.utils.chargerFormLichens( squelette, nomSquelette );
152
			break;
153
		case 'arbres' :
154
		default :
155
			this.reinitialiserWidget( squelette );
156
		break;
157
	}
158
};
159
 
160
LichensLg.prototype.reinitialiserWidget = function( squelette ) {
161
	$( '#charger-form' ).html( squelette );
162
	if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
163
		this.rechargerFormulaire();
164
	}
165
};
166
 
167
// Autocompletion taxons ******************************************************/
168
/**
169
 * Initialise l'autocompletion taxons
170
 */
171
LichensLg.prototype.ajouterAutocompletionNoms = function() {
172
	const lthis = this;
173
 
174
	$( '#taxon' ).autocomplete({
175
		source: function( requete, add ) {
176
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
177
			requete = '';
178
			if( lthis.utils.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
179
				var url = lthis.getUrlAutocompletionNomsSci();
180
				$.getJSON( url, requete, function( data ) {
181
					var suggestions = lthis.traiterRetourNomsSci( data );
182
					add( suggestions );
183
				})
184
				.fail( function() {
185
					$( '#certitude' ).find( 'option' ).each( function() {
186
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
187
							$( this ).attr( 'selected', true );
188
						} else {
189
							$( this ).attr( 'selected', false );
190
						}
191
					});
192
				});
193
			}
194
		},
195
		html: true
196
	});
197
	$( '#taxon' ).on( 'autocompleteselect', this.surAutocompletionTaxon );
198
};
199
 
200
LichensLg.prototype.getUrlAutocompletionNomsSci = function() {
201
	var mots = $( '#taxon' ).val();
202
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
203
	url = url.replace( '{masque}', mots );
204
 
205
	return url;
206
};
207
 
208
/**
209
 * Objet taxons pour autocompletion en fonction de la recherche
210
 */
211
LichensLg.prototype.traiterRetourNomsSci = function( data ) {
212
	var suggestions = [];
213
 
214
	if ( undefined != data.resultat ) {
215
		$.each( data.resultat, function( i, val ) {
216
			val.nn = i;
217
 
218
			var nom = {
219
				label : '',
220
				value : '',
221
				nt : 0,
222
				nomSel : '',
223
				nomSelComplet : '',
224
				numNomSel : 0,
225
				nomRet : '',
226
				numNomRet : 0,
227
				famille : '',
228
				retenu : false
229
			};
230
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
231
				nom.label = '...';
232
				nom.value = $( '#taxon' ).val();
233
				suggestions.push( nom );
234
				return false;
235
			} else {
236
				nom.label = val.nom_sci_complet;
237
				nom.value = val.nom_sci_complet;
238
				nom.nt = val.num_taxonomique;
239
				nom.nomSel = val.nom_sci;
240
				nom.nomSelComplet = val.nom_sci_complet;
241
				nom.numNomSel = val.nn;
242
				nom.nomRet = val.nom_retenu_complet;
243
				nom.numNomRet = val['nom_retenu.id'];
244
				nom.famille = val.famille;
245
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
246
				// en tout cas c'est harmonisé avec le CeL
247
				nom.retenu = ( 'true' == val.retenu );
248
				suggestions.push( nom );
249
			}
250
		});
251
	}
252
	return suggestions;
253
};
254
 
255
/**
256
 * charge les données dans #taxon
257
 */
258
LichensLg.prototype.surAutocompletionTaxon = function( event, ui ) {
259
	const utils = new UtilsLg();
260
 
261
	if ( utils.valOk( ui ) ) {
262
		$( '#taxon' ).val( ui.item.value );
263
		$( '#taxon' ).data( 'value', ui.item.value )
264
			.data( 'numNomSel', ui.item.numNomSel )
265
			.data( 'nomRet', ui.item.nomRet )
266
			.data( 'numNomRet', ui.item.numNomRet )
267
			.data( 'nt', ui.item.nt )
268
			.data( 'famille', ui.item.famille );
269
		if ( ui.item.retenu ) {
270
			$( '#taxon' ).addClass( 'ns-retenu' );
271
		} else {
272
			$( '#taxon' ).removeClass( 'ns-retenu' );
273
		}
274
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
275
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
276
			$( '#certitude' ).find( 'option' ).each( function() {
277
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
278
					$( this ).attr( 'selected', true );
279
				} else {
280
					$( this ).attr( 'selected', false );
281
				}
282
			});
283
		}
284
	}
285
	$( '#taxon' ).change();
286
};
287
 
288
// Fichier Images *************************************************************/
289
/**
290
 * Affiche temporairement (formulaire)
291
 * la miniature d'une image ajoutée à l'obs
292
 */
293
LichensLg.prototype.afficherMiniature = function( reponse ) {
294
	if ( this.debug ) {
295
		var debogage = $( 'debogage', reponse ).text();
296
	}
297
 
298
	var message = $( 'message', reponse ).text();
299
 
300
	if ( this.utils.valOk( message ) ) {
301
		$( '#miniature-msg' ).append( message );
302
	} else {
303
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
304
	}
305
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
306
};
307
 
308
/**
309
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
310
 */
311
LichensLg.prototype.creerWidgetMiniature = function( reponse ) {
312
	var miniatureUrl = $( 'miniature-url', reponse ).text();
313
	var imgNom = $( 'image-nom', reponse ).text();
314
	var html =
315
		'<div class="miniature mb-3 mr-3">'+
316
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
317
			'<a class="effacer-miniature"><i class="fas fa-times"></i></a>'+
318
		'</div>';
319
 
320
	return html;
321
};
322
 
323
/**
324
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
325
 */
326
LichensLg.prototype.verifierFormat = function( cheminTmp ) {
327
	var parts     = cheminTmp.split( '.' ),
328
		extension = parts[ parts.length - 1 ];
329
 
330
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
331
};
332
 
333
/**
334
 * Check les miniatures déjà téléchargées
335
 * renvoie false si le même nom est rencontré 2 fois
336
 * renvoie true sinon
337
 */
338
LichensLg.prototype.verifierDuplication = function( cheminTmp ) {
339
	const lthis = this;
340
	var parts        = cheminTmp.split( '\\' ),
341
		nomImage     = parts[ parts.length - 1 ],
342
		thisSrcParts = [],
343
		thisNomImage = '',
344
		nonDupliquee = true;
345
 
346
	$( 'img.miniature-img,img.miniature' ).each( function() {
347
		// vérification avec alt de l'image
348
		if ( lthis.utils.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
349
			nonDupliquee = false;
350
			return false;// Pas besoin de poursuivre la boucle
351
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
352
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
353
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
354
			if ( lthis.utils.valOk ( thisNomImage, true, nomImage ) ) {
355
				nonDupliquee = false;
356
				return false;
357
			}
358
		}
359
	});
360
	return nonDupliquee;
361
};
362
 
363
/**
364
 * Efface une miniature (formulaire)
365
 */
366
LichensLg.prototype.supprimerMiniature = function( miniature ) {
367
	miniature.parents( '.miniature' ).remove();
368
};
369
 
370
// Ajouter Obs ****************************************************************/
371
 
372
/**
373
 * Ajoute une observation à la liste des obs à transmettre
374
 * (résumé obs)
375
 */
376
LichensLg.prototype.ajouterObs = function() {
377
	// Fermeture automatique des dialogue de transmission de données
378
	// @WARNING TEST
379
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
380
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
381
	$( 'html, body' ).stop().animate({
382
		scrollTop: $( '#zone-lichens' ).offset().top
383
	}, 300);
384
 
385
	if ( this.validerLichens() ) {
386
		this.masquerPanneau( '#dialogue-form-invalide' );
387
		this.obsNbre  += 1;
388
		$( '.obs-nbre' ).text( this.obsNbre );
389
		$( '.obs-nbre' ).triggerHandler( 'changement' );
390
		//formatage des données
391
		var obsData   = this.formaterFormObsData();
392
 
393
		// Résumé obs et stockage en data de "#list-obs" pour envoi
394
		this.afficherObs( obsData );
395
		this.stockerObsData( obsData );
396
		this.supprimerMiniatures();
397
		$( '#taxon' ).val( '' );
398
		$( '#taxon' ).removeData( 'value' )
399
			.removeData( 'numNomSel' )
400
			.removeData( 'nomRet' )
401
			.removeData( 'numNomRet' )
402
			.removeData( 'nt' )
403
			.removeData( 'famille' );
404
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
405
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
406
	} else {
407
		this.afficherPanneau( '#dialogue-form-invalide' );
408
	}
409
};
410
 
411
/**
412
 * Formatage des données du formulaire pour stockage et envoi
413
 */
414
LichensLg.prototype.formaterFormObsData = function() {
415
	var numArbre = $( '#choisir-arbre' ).val(),
416
		miniatureImg  = [],
417
		imgB64        = [],
418
		imgNom        = [],
419
		numNomSel     = $( '#taxon' ).data( 'numNomSel' ),
420
		referentiel   = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx';
421
 
422
	this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
423
	imgNom = this.getNomsImgsOriginales();
424
	imgB64 = this.getB64ImgsOriginales();
425
 
426
	var obsData = {
427
		obsNum   : this.obsNbre,
428
		numArbre : numArbre,
429
		lichen   : {
430
			'num_nom_sel'   : numNomSel,
431
			'nom_sel'       : $( '#taxon' ).val(),
432
			'nom_ret'       : $( '#taxon' ).data( 'nomRet' ),
433
			'num_nom_ret'   : $( '#taxon' ).data( 'numNomRet' ),
434
			'num_taxon'     : $( '#taxon' ).data( 'nt' ),
435
			'famille'       : $( '#taxon' ).data( 'famille' ),
436
			'referentiel'   : referentiel,
437
			'certitude'     : ( !this.utils.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
438
			'date'          : this.utils.fournirDate( $( '#obs-date' ).val() ),
439
			'notes'         : $( '#commentaire' ).val(),
440
			'pays'          : this.releveDatas[0].pays,
441
			'commune_nom'   : this.releveDatas[0]['commune-nom'],
442
			'commune_code_insee' : this.releveDatas[0]['commune-insee'],
443
			'latitude'      : this.releveDatas[numArbre]['latitude-arbres'],
444
			'longitude'     : this.releveDatas[numArbre]['longitude-arbres'],
445
			'altitude'      : this.releveDatas[numArbre]['altitude-arbres'],
446
			//Ajout des champs images
447
			'image_nom'     : imgNom,
448
			'image_b64'     : imgB64,
449
			// Ajout des champs étendus de l'obs
450
			'obs_etendue'   : this.getObsChpLichens( numArbre )
451
		}
452
	};
453
	return obsData;
454
};
455
 
456
/**
457
 * Retourne un Array contenant les valeurs des champs
458
 * dont les données seront transmises dans la table cel-obs-etendues
459
 */
460
LichensLg.prototype.getObsChpLichens = function( numArbre ) {
461
	const lthis = this;
462
 
463
	var retour = [
464
		{ cle : 'num-arbre', valeur : numArbre },
465
		{ cle : 'id_obs_arbre', valeur : this.releveDatas[numArbre]['id_observation'] },
466
		{ cle : 'rue' , valeur : this.releveDatas[0].rue  }
467
	];
468
 
469
	var valeursLT  = '';
470
	const $lichensTronc = $( 'input[name=lichens-tronc]:checked' );
471
	const LTLenght = $lichensTronc.length;
472
 
473
	$( 'input[name=lichens-tronc]:checked' ).each( function( i, value ) {
474
		valeursLT += $(value).val();
475
		if( i < LTLenght ) {
476
			valeursLT += ';';
477
		}
478
	});
479
	retour.push({ cle : 'loc-sur-tronc', valeur : valeursLT });
480
 
481
	return retour;
482
};
483
 
484
/**
485
 * Résumé obs
486
 */
487
LichensLg.prototype.afficherObs = function( datasObs ) {
488
	var obsNum            = datasObs.obsNum,
489
		numArbre          = datasObs.numArbre,
490
		dateObs           = datasObs.lichen.date,
491
		numNomSel         = datasObs.lichen['num_nom_sel'],
492
		taxon             = datasObs.lichen['nom_sel'],
493
		certitude         = datasObs.lichen.certitude,
494
		miniatures        = this.ajouterImgMiniatureAuTransfert(),
495
		commentaires      = '';
496
 
497
	if ( this.utils.valOk( datasObs.lichen.notes ) ) {
498
		commentaires =
499
			this.utils.msgTraduction( 'commentaires' ) +
500
			' : <span>'+
501
				datasObs.arbre.notes +
502
			'</span> ';
503
	}
504
 
505
	var responsivDiff1 = '',
506
		responsivDiff2 = '',
507
		responsivDiff3 = '',
508
		responsivDiff4 = '',
509
		responsivDiff5 = '',
510
		responsivDiff6 = '';
511
 
512
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
513
		/* La largeur minimum de l'affichage est 600 px inclus */
514
		responsivDiff1 = ' droite';
515
		responsivDiff2 = '<div></div>';
516
		responsivDiff3 = '<div class="row">';
517
		responsivDiff4 = ' col-md-4 col-sm-5';
518
		responsivDiff5 = ' class="col-md-7 col-sm-6"';
519
		responsivDiff6 = '</div>';
520
	}
521
	$( '#liste-obs' ).prepend(
522
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
523
			'<div '+
524
				'class="obs-action" '+
525
				'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
526
			'>'+
527
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
528
				'<i class="far fa-trash-alt"></i>'+
529
				'</button>'+
530
				responsivDiff2 +
531
			'</div> '+
532
			responsivDiff3 +
533
				'<div class="thumbnail' + responsivDiff4 + '">'+
534
					miniatures+
535
				'</div>'+
536
				'<div' + responsivDiff5 + '>'+
537
					'<ul class="unstyled">'+
538
						'<li>'+
539
							'<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
540
							' <span class="nom-sci">' + taxon + '</span> '+
541
							this.ajouterNumNomSel( numNomSel ) +
542
							' [certitude : ' + certitude + ']'+
543
							' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
544
							'<span class="date">' + dateObs + '</span>'+
545
						'</li>'+
546
						'<li>'+
547
							commentaires +
548
						'</li>'+
549
					'</ul>'+
550
				'</div>'+
551
			responsivDiff6+
552
		'</div>'
553
	);
554
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
555
};
556
 
557
/**
558
 * Ajoute une boîte de miniatures avec défilement des images,
559
 * pour une obs de la liste des obs à transmettre
560
 */
561
LichensLg.prototype.ajouterImgMiniatureAuTransfert = function() {
562
	var html        =
563
			'<div class="defilement-miniatures">'+
564
				'<figure class="centre">'+
565
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
566
				'</figure>'+
567
			'</div>',
568
		miniatures   = '',
569
		premiere     = true,
570
		centre       = '';
571
		defilVisible = '';
572
 
573
	if ( this.utils.valOk( $( '#miniatures img' ) ) ) {
574
		$( '#miniatures img' ).each( function() {
575
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
576
			premiere = false;
577
 
578
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
579
				src        = $( this ).attr( 'src' ),
580
				alt        = $( this ).attr( 'alt' ),
581
				miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
582
 
583
			miniatures += miniature;
584
		});
585
		if ( 1 === $( '#miniatures img' ).length ) {
586
			centre       = 'centre';
587
			defilVisible = ' defilement-miniatures-cache';
588
		}
589
		html             =
590
			'<div class="defilement-miniatures">'+
591
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
592
				'<figure class="' + centre + '">'+
593
					miniatures+
594
				'</figure>'+
595
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
596
			'</div>';
597
	}
598
	return html;
599
};
600
 
601
/**
602
 * Construit le html à afficher pour le numNom
603
 */
604
LichensLg.prototype.ajouterNumNomSel = function( numNomSel ) {
605
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
606
 
607
	if ( !this.utils.valOk( numNomSel ) ) {
608
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
609
	}
610
 
611
	return nn;
612
};
613
 
614
/**
615
 * Stocke des données d'obs à envoyer à la bdd
616
 */
617
LichensLg.prototype.stockerObsData = function( datasObs ) {
618
	// Stockage en data des données d'obs à transmettre
619
	$( '#liste-obs' ).data( 'obsId' + datasObs.obsNum, datasObs.lichen );
620
};
621
 
622
LichensLg.prototype.getNomsImgsOriginales = function() {
623
	var noms = new Array();
624
 
625
	$( '.miniature-img' ).each( function() {
626
		noms.push( $( this ).attr( 'alt' ) );
627
	});
628
 
629
	return noms;
630
};
631
 
632
LichensLg.prototype.getB64ImgsOriginales = function() {
633
	var b64 = new Array();
634
 
635
	$( '.miniature-img' ).each( function() {
636
		if ( $( this ).hasClass( 'b64' ) ) {
637
			b64.push( $( this ).attr( 'src' ) );
638
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
639
			b64.push( $( this ).data( 'b64' ) );
640
		}
641
	});
642
 
643
	return b64;
644
};
645
 
646
/**
647
 * Efface toutes les miniatures (formulaire)
648
 */
649
LichensLg.prototype.supprimerMiniatures = function() {
650
	$( '#miniatures' ).empty();
651
	$( '#miniature-msg' ).empty();
652
};
653
 
654
LichensLg.prototype.surChangementNbreObs = function() {
655
	if ( 0 === this.obsNbre ) {
656
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
657
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
658
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
659
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
660
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
661
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
662
	}
663
};
664
 
665
LichensLg.prototype.defilerMiniatures = function( element ) {
666
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
667
 
668
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
669
	miniatureSelectionne.addClass( 'miniature-cachee' );
670
 
671
	var miniatureAffichee     = miniatureSelectionne;
672
 
673
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
674
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
675
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
676
		} else {
677
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
678
		}
679
	} else {
680
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
681
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
682
		} else {
683
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
684
		}
685
	}
686
	miniatureAffichee.addClass( 'miniature-selectionnee' );
687
	miniatureAffichee.removeClass( 'miniature-cachee' );
688
};
689
 
690
LichensLg.prototype.supprimerObs = function( selector ) {
691
	var obsId = $( selector ).val();
692
 
693
	// Problème avec IE 6 et 7
694
	if ( 'Supprimer' === obsId ) {
695
		obsId = $( selector ).attr( 'title' );
696
	}
697
	this.supprimerObsParId( obsId );
698
};
699
 
700
/**
701
 * Supprime l'obs et les data de l'obs
702
 * et remonte les suivantes d'un cran
703
 */
704
LichensLg.prototype.supprimerObsParId = function( obsId ) {
705
	this.obsNbre  -= 1;
706
	$( '.obs-nbre' ).text( this.obsNbre );
707
	$( '.obs-nbre' ).triggerHandler( 'changement' );
708
	$( '.obs' + obsId ).remove();
709
 
710
	obsId = parseInt(obsId);
711
	var listObsData = $( '#liste-obs' ).data(),
712
		exId        = 0,
713
		indexObs    = '',
714
		exIndexObs  = '';
715
 
716
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
717
		exId       = parseInt(id) + 1;
718
		indexObs   = 'obsId' + id;
719
		exIndexObs = 'obsId' + exId;
720
		$( '#liste-obs' ).removeData( indexObs );
721
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
722
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
723
		}
724
		$( '#obs' + exId )
725
			.attr( 'id', 'obs' + id )
726
			.removeClass( 'obs' + exId )
727
			.addClass( 'obs' + id )
728
			.find( '.supprimer-obs' )
729
				.attr( 'title', 'Observation n°' + id )
730
				.val( id );
731
		if ( parseInt( id ) !== this.obsNbre ) {
732
			id = parseInt( id );
733
		}
734
	}
735
};
736
 
737
LichensLg.prototype.transmettreObs = function() {
738
	const lthis = this;
739
	var observations = $( '#liste-obs' ).data();
740
 
741
	if ( this.debug ) {
742
		console.log( observations );
743
	}
744
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
745
		this.afficherPanneau( '#dialogue-zero-obs' );
746
	} else {
747
		$( window ).on( 'beforeunload', function( event ) {
748
			return lthis.utils.msgTraduction( 'rechargement-page' );
749
		});
750
		this.nbObsEnCours         = 1;
751
		this.nbObsTransmises      = 0;
752
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
753
			return i;
754
		}).length;
755
		this.depilerObsPourEnvoi();
756
	}
757
 
758
	return false;
759
};
760
 
761
LichensLg.prototype.depilerObsPourEnvoi = function() {
762
	var observations = $( '#liste-obs' ).data();
763
 
764
	// la boucle est factice car on utilise un tableau
765
	// dont on a besoin de n'extraire que le premier élément
766
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
767
	// TODO: utiliser var.keys quand ça sera plus répandu
768
	// ou bien utiliser un vrai tableau et pas un objet
769
	for ( var obsNum in observations ) {
770
		var obsATransmettre = {
771
			'projet'  : this.tagProjet,
772
			'tag-obs' : this.tagObs,
773
			'tag-img' : this.tagImg
774
		};
775
		var utilisateur = {
776
			id_utilisateur : this.infosUtilisateur.id,
777
			prenom         : this.infosUtilisateur.prenom,
778
			nom            : this.infosUtilisateur.nom,
779
			courriel       : $( '#courriel' ).val()
780
		};
781
 
782
		obsATransmettre['utilisateur'] = utilisateur;
783
		obsATransmettre[obsNum]        = observations[obsNum];
784
 
785
		var idObsNumerique = obsNum.replace( 'obsId', '' );
786
 
787
		if( '' !== idObsNumerique ) {
788
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
789
		}
790
		break;
791
	}
792
};
793
 
794
LichensLg.prototype.envoyerObsAuCel = function( idObs, observation ) {
795
	const lthis     = this;
796
	var erreurMsg = '';
797
 
798
	$.ajax({
799
		url        : lthis.serviceSaisieUrl,
800
		type       : 'POST',
801
		data       : observation,
802
		dataType   : 'json',
803
		beforeSend : function() {
804
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
805
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
806
			$( '.alert-txt' ).empty();
807
			$( '.alert-txt .msg-erreur' ).remove();
808
			$( '.alert-txt .msg-debug' ).remove();
809
			$( '#chargement' ).removeClass( 'hidden' );
810
		},
811
		success    : function( data, textStatus, jqXHR ) {
812
			// mise à jour du nombre d'obs à transmettre
813
			// et suppression de l'obs
814
			lthis.supprimerObsParId( idObs );
815
			lthis.nbObsEnCours++;
816
			// mise à jour du statut
817
			lthis.mettreAJourProgression();
818
			if( 0 < lthis.obsNbre ) {
819
				// dépilement de la suivante
820
				lthis.depilerObsPourEnvoi();
821
			}
822
		},
823
		statusCode  : {
824
			500 : function( jqXHR, textStatus, errorThrown ) {
825
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
826
				}
827
		},
828
		error        : function( jqXHR, textStatus, errorThrown ) {
829
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
830
			try {
831
				reponse = jQuery.parseJSON( jqXHR.responseText );
832
				if ( null !== reponse ) {
833
					$.each( reponse, function( cle, valeur ) {
834
						erreurMsg += valeur + '\n';
835
					});
836
				}
837
			} catch( e ) {
838
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
839
			}
840
		},
841
		complete      : function( jqXHR, textStatus ) {
842
			var debugMsg = extraireEnteteDebug( jqXHR );
843
 
844
			if ( '' !== erreurMsg ) {
845
				if ( lthis.debug ) {
846
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
847
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
848
				}
849
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
850
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
851
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
852
 
853
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
854
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
855
				// window.location.hash = 'obs' + idObs;
856
 
857
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
858
					$( '#tpl-transmission-ko' ).clone()
859
						.find( '.courriel-erreur' )
860
						.attr( 'href', hrefCourriel )
861
						.end()
862
						.html()
863
				);
864
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
865
				$( '#chargement' ).addClass( 'hidden' );
866
				lthis.initialiserBarreProgression;
867
			} else {
868
				if ( lthis.debug ) {
869
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
870
				}
871
				if( 0 === lthis.obsNbre ) {
872
					setTimeout( function() {
873
						$( '#chargement,#bloc-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
874
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
875
						$( '#dialogue-obs-transaction-ok,#bouton-poursuivre' ).removeClass( 'hidden' );
876
					}, 1500 );
877
				}
878
			}
879
		}
880
	});
881
};
882
 
883
LichensLg.prototype.mettreAJourProgression = function() {
884
	this.nbObsTransmises++;
885
 
886
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
887
 
888
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
889
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
890
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
891
	if( 0 === this.obsNbre ) {
892
		$( '.progress' ).removeClass( 'active' );
893
		$( '.progress' ).removeClass( 'progress-bar-striped' );
894
	}
895
};
896
 
897
LichensLg.prototype.initialiserBarreProgression = function() {
898
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
899
	$( '#barre-progression-upload' ).css( 'width', '0%' );
900
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
901
	$( '.progress' ).addClass( 'active' );
902
	$( '.progress' ).addClass( 'progress-bar-striped' );
903
};
904
 
905
// Form Validator *************************************************************/
906
LichensLg.prototype.configurerFormValidator = function() {
907
	const lthis = this;
908
 
909
	$.validator.addMethod(
910
		'dateCel',
911
		function ( value, element ) {
912
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
913
		},
914
		lthis.utils.msgTraduction( 'date-incomplete' )
915
	);
916
 
917
	$.validator.addMethod(
918
		'userEmailOk',
919
		function ( value, element ) {
920
			return ( lthis.utils.valOk( value ) );
921
		},
922
		''
923
	);
924
 
925
	$.extend( $.validator.defaults, {
926
		errorElement: 'span',
927
		errorPlacement: function( error, element ) {
928
			element.after( error );
929
		},
930
		onfocusout: function( element ) {
931
			if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
932
				if ( $( element ).valid() ) {
933
					$( element ).closest( '.control-group' ).removeClass( 'error' );
934
				} else {
935
					$( element ).closest( '.control-group' ).addClass( 'error' );
936
				}
937
			}
938
		},
939
		onkeyup : function( element ) {
940
			if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
941
				if ( $( element ).valid() ) {
942
					$( element ).closest( '.control-group' ).removeClass( 'error' );
943
				} else {
944
					$( element ).closest( '.control-group' ).addClass( 'error' );
945
				}
946
			}
947
		},
948
		unhighlight: function( element ) {
949
			if( lthis.utils.valOk( element.id, false, 'taxon' ) ) {
950
				$( element ).closest( '.control-group' ).removeClass( 'error' );
951
			}
952
		},
953
		highlight: function( element ) {
954
			$( element ).closest( '.control-group' ).addClass( 'error' );
955
		}
956
	});
957
};
958
 
959
LichensLg.prototype.definirReglesFormValidator = function() {
960
	const lthis = this;
961
 
962
	$( 'input[type=date]' ).on( 'input', function() {
963
		$( this ).valid();
964
	});
965
	// Validation Taxon si pas de miniature
966
	$( '#taxon' ).on( 'change', function() {
967
		var images = lthis.utils.valOk( $( '#miniatures .miniature' ) );
968
		lthis.validerTaxonImage( lthis.utils.valOk( $( this ).val() ), images );
969
	});
970
 
971
	// // Validation miniatures avec MutationObserver
972
	// this.surPresenceAbsenceMiniature();
973
 
974
	$( '#form-lichens' ).validate({
975
		rules : {
976
			'choisir-arbre' : {
977
				required : true,
978
				minlength : 1
979
			},
980
			'obs-date' : {
981
				required : true,
982
				'dateCel' : true
983
			},
984
			certitude : {
985
				required : true,
986
				minlength : 1
987
			}
988
		}
989
	});
990
	$( '#form-observateur' ).validate({
991
		rules : {
992
			courriel : {
993
				required : true,
994
				minlength : 1,
995
				email : true,
996
				'userEmailOk' : true
997
			},
998
			mdp : {
999
				required : true,
1000
				minlength : 1
1001
			}
1002
		}
1003
	});
1004
	$( '#connexion,#inscription,#oublie' ).click( function() {
1005
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1006
	});
1007
};
1008
 
1009
LichensLg.prototype.validerTaxonImage = function( taxon = false, images = false ) {
1010
	var taxonOuImage = ( images || taxon );
1011
	if ( images || taxon ) {
1012
		this.masquerPanneau( '#dialogue-taxon-or-image' );
1013
		$( '#bloc-taxon' ).removeClass( 'error' )
1014
			.find( 'span.error' ).hide();
1015
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
1016
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
1017
		// faire passer la certitude à 'à déterminer' si on a une image et pas de taxon
1018
		if( !taxon ) {
1019
			$( '#certitude' ).find( 'option' ).each( function() {
1020
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
1021
					$( this ).attr( 'selected', true );
1022
				} else {
1023
					$( this ).attr( 'selected', false );
1024
				}
1025
			});
1026
		}
1027
	} else {
1028
		this.afficherPanneau( '#dialogue-taxon-or-image' );
1029
		$( '#bloc-taxon' ).addClass( 'error' )
1030
			.find( 'span.error' ).show();
1031
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
1032
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
1033
	}
1034
	return ( images || taxon );
1035
};
1036
 
1037
/**
1038
 * Valide le formulaire au click sur un bouton "suivant"
1039
 */
1040
LichensLg.prototype.validerLichens = function() {
1041
	const images       = this.utils.valOk( $( '#miniatures .miniature' ) );
1042
	const taxon        = this.utils.valOk( $( '#taxon' ).val() );
1043
	const taxonOuImage = this.validerTaxonImage( taxon, images );
1044
	const observateur  = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1045
	const obs          = $( '#form-lichens' ).valid();
1046
	console.log('images : ' + images);
1047
	console.log('taxon : ' + taxon);
1048
	console.log('taxonOuImage : ' + taxonOuImage);
1049
	console.log(obs);
1050
 
1051
	// panneau observateur
1052
	if ( observateur ) {
1053
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1054
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1055
	} else {
1056
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1057
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1058
	}
1059
 
1060
	return ( observateur && obs && taxonOuImage );
1061
};
1062
 
1063
// Controle des panneaux d'infos **********************************************/
1064
 
1065
LichensLg.prototype.afficherPanneau = function( selecteur ) {
1066
	$( selecteur )
1067
		.removeClass( 'hidden' )
1068
		.hide()
1069
		.show( 600 )
1070
		.delay( this.dureeMessage )
1071
		.hide( 600 );
1072
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
1073
};
1074
 
1075
LichensLg.prototype.masquerPanneau = function( selecteur ) {
1076
	$( selecteur ).addClass( 'hidden' );
1077
};
1078
 
1079
LichensLg.prototype.fermerPanneauAlert = function() {
1080
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1081
};
1082
 
1083
// lib hors objet --
1084
 
1085
/**
1086
* Stope l'évènement courant quand on clique sur un lien.
1087
* Utile pour Chrome, Safari...
1088
*/
1089
function arreter( event ) {
1090
	if ( event.stopPropagation ) {
1091
		event.stopPropagation();
1092
	}
1093
	if ( event.preventDefault ) {
1094
		event.preventDefault();
1095
	}
1096
 
1097
	return false;
1098
}
1099
 
1100
/**
1101
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1102
 * @param jqXHR
1103
 * @returns {String}
1104
 */
1105
function extraireEnteteDebug( jqXHR ) {
1106
	var msgDebug = '';
1107
 
1108
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1109
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1110
		if ( null !== debugInfos ) {
1111
			$.each( debugInfos, function( cle, valeur ) {
1112
				msgDebug += valeur + '\n';
1113
			});
1114
		}
1115
	}
1116
 
1117
	return msgDebug;
1118
}
1119
 
1120
/*
1121
 * jQuery UI Autocomplete HTML Extension
1122
 *
1123
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1124
 * Dual licensed under the MIT or GPL Version 2 licenses.
1125
 *
1126
 * http://github.com/scottgonzalez/jquery-ui-extensions
1127
 *
1128
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1129
 */
1130
( function( $ ) {
1131
	var proto      = $.ui.autocomplete.prototype,
1132
		initSource = proto._initSource;
1133
 
1134
	LichensLg.prototype.filter = function( array, term ) {
1135
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1136
 
1137
		return $.grep( array, function( value ) {
1138
 
1139
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1140
		});
1141
	}
1142
	$.extend( proto, {
1143
		_initSource: function() {
1144
			if ( this.options.html && $.isArray( this.options.source ) ) {
1145
				this.source = function( request, response ) {
1146
					response( filter( this.options.source, request.term ) );
1147
				};
1148
			} else {
1149
				initSource.call( this );
1150
			}
1151
		},
1152
		_renderItem: function( ul, item) {
1153
			if ( item.retenu ) {
1154
				item.label = '<strong>' + item.label + '</strong>';
1155
			}
1156
 
1157
			return $( '<li></li>' )
1158
				.data( 'item.autocomplete', item )
1159
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1160
				.appendTo( ul );
1161
		}
1162
	});
1163
})( jQuery );