Subversion Repositories eFlore/Applications.cel

Rev

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