Subversion Repositories eFlore/Applications.cel

Rev

Rev 3333 | Details | Compare with Previous | Last modification | View Log | RSS feed

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