Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3638 delphine 1
const utils = new Utils;
2
 
3
/**
4
 * WidgetsSaisiesCommun
5
 * Methodes communes aux widgets de saisie
6
 */
7
function WidgetsSaisiesCommun(){}
8
 
9
WidgetsSaisiesCommun.prototype.init = function() {
10
	// ASL : APA, sTREETs, Lichen's Go!
11
	// const ASL = ['tb_aupresdemonarbre','tb_streets','tb_lichensgo'];
12
	// this.isASL = ( utils.valOk( this.projet ) && -1 < $.inArray( this.projet , ASL ) );
13
	this.initForm();
14
	this.initEvts();
15
};
16
 
17
WidgetsSaisiesCommun.prototype.initFormConnection = function() {
18
	this.urlBaseAuth = this.urlRacine + '/service:annuaire:auth';
19
	$( '#inscription' ).attr( 'href',  this.urlSiteTb() + 'inscription' );
20
	if ( this.isASL ) {
21
		$( '#mdp' ).val( '' );
22
		$( '#oublie' ).attr( 'href',  this.urlSiteTb() + 'wp-login.php?action=lostpassword' );
23
	}
24
};
25
 
26
WidgetsSaisiesCommun.prototype.initFormTaxonListe = function() {
27
	const lthis = this;
28
 
29
	this.surChangementTaxonListe();
30
	$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
31
	$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
32
	if ( this.debug ) {
33
		console.dir( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
34
	}
35
};
36
 
37
WidgetsSaisiesCommun.prototype.initEvtsConnection = function() {
38
	const lthis = this;
39
 
40
	this.chargerStatutSSO();
41
	$( '#utilisateur-connecte .volet-toggle, #profil-utilisateur a, #deconnexion a' ).on( 'click', function( event ) {
42
		if( $( this ).hasClass( 'volet-toggle' ) ) {
43
			event.preventDefault();
44
		}
45
		$( '#utilisateur-connecte .volet-menu' ).toggleClass( 'hidden' );
46
	});
47
	$( '#deconnexion a' ).on( 'click', function( event ) {
48
		event.preventDefault();
49
		lthis.deconnecterUtilisateur();
50
	});
51
	if ( !this.isASL ) {
52
		$( '#bouton-anonyme' ).on( 'click', function( event ) {
53
			lthis.arreter( event );
54
			$( this ).css({
55
				'background-color': 'rgba(0, 159, 184, 0.7)',
56
				'color': '#fff'
57
			});
58
			$( '#identite' ).removeClass( 'hidden' );
59
			$( '#courriel' ).focus();
60
		});
61
		if ( '' === $( '#nom-complet').text() ) {
62
			$( '#courriel' ).on( 'blur', this.requeterIdentiteCourriel.bind( this ) );
63
			$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
64
		}
65
		$( '#prenom' ).on( 'change', function() {
66
			lthis.formaterPrenom();
67
			lthis.reduireVoletIdentite();
68
		});
69
		$( '#nom' ).on( 'change', function() {
70
			lthis.formaterNom();
71
			lthis.reduireVoletIdentite();
72
		});
73
		$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
74
		$( '#courriel_confirmation' ).on( 'blur', this.reduireVoletIdentite.bind( this ) );
75
		$( '#courriel_confirmation' ).on( 'keypress', function( event ) {
76
			if ( lthis.valOk( event.which, true, 13 ) ) {
77
				lthis.reduireVoletIdentite();
78
				event.preventDefault();
79
				event.stopPropagation();
80
			}
81
		});
82
	}
83
};
84
 
85
WidgetsSaisiesCommun.prototype.initEvtsFichier = function() {
86
	const lthis = this;
87
 
88
	function fileInputFonctionne() {
89
		var ua = navigator.userAgent;
90
 
91
		if (
92
			ua.match( /(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/ ) ||
93
			ua.match( /\swv\).+(chrome)\/([\w\.]+)/i )
94
		) {
95
		  return false;
96
		}
97
 
98
		var elem = document.createElement( 'input' );
99
 
100
		elem.type = 'file';
101
 
102
		return !elem.disabled;
103
	}
104
 
105
	if ( fileInputFonctionne() ) {
106
		// Sur téléchargement image
107
		$( '#fichier' ).on( 'change', function ( event ) {
108
			lthis.arreter ( event );
109
 
110
			var options        = {
111
				beforeSend : function ( jqXHR, settings ) {
112
					$( '#miniatures' ).on( 'click', '.effacer-miniature', function() {
113
						jqXHR.abort(jqXHR);
114
					});
115
				},
116
				success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
117
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
118
				resetForm: true // reset the form after successful submit
119
			};
120
			var imgCheminTmp    = $( '#fichier' ).val(),
121
				parts           = imgCheminTmp.split( '\\' ),
122
				nomImage        = parts[ parts.length - 1 ],
123
				formatImgOk     = lthis.verifierFormat( nomImage ),
124
				imgNonDupliquee = lthis.verifierDuplication( nomImage );
125
 
126
			if( formatImgOk && imgNonDupliquee ) {
127
				$( '#form-upload' ).ajaxSubmit( options );
128
				$( '#miniatures' ).append(
129
					'<div class="miniature mr-3 miniature-chargement loading">'+
130
						'<img class="miniature-img chargement-img" alt="chargement" src="' + lthis.chargementImageIconeUrl + '" style="min-height:100%;"/>'+
131
						'<a class="effacer-miniature">Supprimer</a>'+
132
					'</div>'
133
				);
134
				$( '#ajouter-obs' ).addClass( 'hidden' );
135
				$( '#message-chargement' ).removeClass( 'hidden' );
136
			} else {
137
				$( '#form-upload' )[0].reset();
138
				if ( !formatImgOk ) {
139
					lthis.activerModale( lthis.msgTraduction( 'format-non-supporte' ) + ' : ' + $( '#fichier' ).attr( 'accept' ) );
140
				}
141
				if ( !imgNonDupliquee ) {
142
					lthis.activerModale( lthis.msgTraduction( 'image-deja-chargee' ) );
143
				}
144
			}
145
			return false;
146
		});
147
		$( 'body' ).on( 'click', '.effacer-miniature', function() {
148
			$( this ).parent().remove();
149
			if ( !lthis.valOk( $('.miniature-chargement' ) ) ) {
150
				$( '#ajouter-obs' ).removeClass( 'hidden' );
151
				$( '#message-chargement' ).addClass( 'hidden' );
152
			}
153
		});
154
	} else {
155
		$( '#form-upload' )
156
			.addClass( 'hidden' )
157
			.after(
158
				'<div class="alert alert-info" role="alert">'+
159
					this.msgTraduction( 'upload-non-suppote' )+
160
				'</div>'
161
			);
162
	}
163
 
164
};
165
 
166
WidgetsSaisiesCommun.prototype.initEvtsGeoloc = function( isFormArbre = false ) {
167
	const lthis = this;
168
 
169
	var ancre               = '-observation',
170
		complementSelecteur = '';
171
 
172
	if ( isFormArbre ) {
173
		ancre               = '-arbres';
174
		complementSelecteur = ancre;
175
	}
176
	// Empêcher que le module carto ne bind ses events partout
177
	$( '#zone' + ancre ).on( 'submit blur click focus mousedown mouseleave mouseup change', '#tb-geolocation' + complementSelecteur + ' *', function( event ) {
178
		event.preventDefault();
179
		return false;
180
	});
181
	// evenement location
182
	$( '#tb-geolocation' + complementSelecteur ).on( 'location' , this.locationHandler.bind( this ) );
183
};
184
 
185
WidgetsSaisiesCommun.prototype.initEvtsObs = function() {
186
	const lthis = this;
187
 
188
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
189
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
190
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
191
		event.preventDefault();
192
		lthis.defilerMiniatures( $( this ) );
193
	});
194
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
195
		event.preventDefault();
196
		lthis.defilerMiniatures( $( this ) );
197
	});
198
	// mécanisme de suppression d'une obs
199
	$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
200
		var buttons = [
201
				{
202
					label   : 'Annuler',
203
					class   : 'btn-secondary',
204
					dismiss : true
205
				},
206
				{
207
					label   : 'Confirmer',
208
					class   : 'btn-success confirmer',
209
					dismiss : true
210
				}
211
			];
212
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
213
		var that    = this,
214
			suppObs = lthis.supprimerObs.bind( lthis );
215
 
216
		lthis.activerModale( lthis.msgTraduction( 'confirmation-suppression' ), '', buttons );
217
		$( '.confirmer' ).on( 'click', function() {
218
			suppObs( that );
219
		});
220
	});
221
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
222
};
223
 
224
// Alertes et aides
225
WidgetsSaisiesCommun.prototype.initEvtsAlertes = function() {
226
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
227
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
228
};
229
 
230
/**
231
 * Interroge le SSO pour connaître le statut de l'utilisateur, et change le menu
232
 * à droite de la barre en fonction
233
 */
234
WidgetsSaisiesCommun.prototype.chargerStatutSSO = function() {
235
	const lthis = this;
236
	var urlAuth = this.urlBaseAuth + '/identite';
237
 
238
	if( 'local' !== this.mode ) {
239
		this.connexion( urlAuth, true );
240
		if( this.isASL) {
241
			$( '#connexion' ).on( 'click', function( event ) {
242
				event.preventDefault();
243
				if( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) || !lthis.valOk( $( '#nom-complet' ).text() ) ) {
244
					var login = $( '#courriel' ).val(),
245
						mdp   = $( '#mdp' ).val();
246
					if ( lthis.valOk( login ) && lthis.valOk( mdp ) ) {
247
						urlAuth = lthis.urlBaseAuth + '/connexion?login=' + login + '&password=' + mdp;
248
						lthis.connexion( urlAuth, true );
249
					} else {
250
						lthis.activerModale( lthis.msgTraduction( 'non-connexion' ) );
251
					}
252
				}
253
			});
254
		}
255
	} else {
256
		urlAuth = this.urlWidgets + 'modules/saisie/test-token.json';
257
		// $( '#connexion' ).on( 'click', function( event ) {
258
		// 	event.preventDefault();
259
			// lthis.connexion( urlAuth, true );
260
			this.connexion( urlAuth, true );
261
		// });
262
	}
263
};
264
 
265
/**
266
 * Déconnecte l'utilisateur du SSO
267
 */
268
WidgetsSaisiesCommun.prototype.deconnecterUtilisateur = function() {
269
	var urlAuth = this.urlBaseAuth + '/deconnexion';
270
 
271
	if( 'local' === this.mode ) {
272
		this.definirUtilisateur();
273
		window.location.reload();
274
		return;
275
	}
276
	this.connexion( urlAuth, false );
277
};
278
 
279
WidgetsSaisiesCommun.prototype.connexion = function( urlAuth, connexionOnOff ) {
280
	const lthis = this;
281
 
282
	$.ajax({
283
		url: urlAuth,
284
		type: "GET",
285
		dataType: 'json',
286
		xhrFields: {
287
			withCredentials: true
288
		}
289
	})
290
	.done( function( data ) {
291
		if( connexionOnOff ) {
292
			// connecté
293
			lthis.definirUtilisateur( data.token );
294
		} else {
295
			lthis.definirUtilisateur();
296
			window.location.reload();
297
		}
298
	})
299
	.fail( function( error ) {
300
		// @TODO gérer l'affichage de l'erreur, mais pas facile à placer
301
		// dans l'interface actuelle sans que ce soit moche
302
		//afficherErreurServeur();
303
	});
304
};
305
 
306
WidgetsSaisiesCommun.prototype.definirUtilisateur = function( jeton ) {
307
	const thisObj = this;
308
	var idUtilisateur = '',
309
		prenom        = '',
310
		nom           = '',
311
		nomComplet    = '',
312
		courriel      = '';
313
 
314
	// affichage
315
	if ( undefined !== jeton ) {
316
		// décodage jeton
317
		this.infosUtilisateur = this.decoderJeton( jeton );
318
		idUtilisateur = this.infosUtilisateur.id;
319
		prenom        = this.infosUtilisateur.prenom;
320
		nom           = this.infosUtilisateur.nom;
321
		nomComplet    = this.infosUtilisateur.intitule;
322
		courriel      = this.infosUtilisateur.sub;
323
		$( '#courriel' ).attr( 'disabled', 'disabled' );
324
		$( '#utilisateur-connecte, #identite' ).removeClass( 'hidden' );
325
		if ( this.isASL ) {
326
			$( '#bloc-connexion' ).addClass( 'hidden' );
327
		} else {
328
			$( '#courriel_confirmation' ).attr( 'disabled', 'disabled' );
329
			$( '#prenom' ).attr( 'disabled', 'disabled' );
330
			$( '#nom' ).attr( 'disabled', 'disabled' );
331
			$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
332
			$( '#zone-courriel, #zone-prenom-nom' ).addClass( 'hidden' );
333
			$( '#date-releve' ).focus();
334
		}
335
	}
336
	$( '#id_utilisateur' ).val( idUtilisateur );
337
	$( '#prenom' ).val( prenom );
338
	$( '#nom' ).val( nom );
339
	$( '#nom-complet' ).html( nomComplet );
340
	$( '#courriel' ).val( courriel );
341
	$( '#profil-utilisateur a' ).attr( 'href', this.urlSiteTb() + 'membres/me' );
342
	if ( this.isASL ) {
343
		if ( this.valOk( idUtilisateur ) ) {
344
			var nomSquelette = $( '#charger-form' ).data( 'load' ) || 'arbres';
345
			this.chargerForm( nomSquelette, thisObj );
346
		}
347
	} else {
348
		$( '.warning' ).remove();
349
		$( '#courriel_confirmation' ).val( courriel );
350
	}
351
};
352
 
353
/**
354
 * Décodage à l'arrache d'un jeton JWT, ATTENTION CONSIDERE QUE LE
355
 * JETON EST VALIDE, ne pas décoder n'importe quoi - pas trouvé de lib simple
356
 */
357
WidgetsSaisiesCommun.prototype.decoderJeton = function( jeton ) {
358
	var parts = jeton.split( '.' ),
359
		payload = parts[1];
360
	payload = this.b64d( payload );
361
	payload = JSON.parse( payload, true );
362
	return payload;
363
};
364
 
365
/**
366
 * Décodage "url-safe" des chaînes base64 retournées par le SSO (lib jwt)
367
 */
368
WidgetsSaisiesCommun.prototype.b64d = function( input ) {
369
  var remainder = input.length % 4;
370
 
371
  if ( 0 !== remainder ) {
372
	var padlen = 4 - remainder;
373
 
374
	for ( var i = 0; i < padlen; i++ ) {
375
	  input += '=';
376
	}
377
  }
378
  input = input.replace( '-', '+' );
379
  input = input.replace( '_', '/' );
380
  return atob( input );
381
};
382
 
383
WidgetsSaisiesCommun.prototype.urlSiteTb = function() {
384
	var urlPart = ( 'test' === this.mode ) ? '/test/' : '/';
385
 
386
	return this.urlRacine + urlPart;
387
};
388
 
389
// uniquement utilisé si taxon-liste ******************************************/
390
/**
391
 * Affiche/Cache le champ taxon
392
 */
393
WidgetsSaisiesCommun.prototype.surChangementTaxonListe = function() {
394
	if ( utils.valOk( $( '#taxon-liste' ).val() ) ) {
395
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
396
			$( '#taxon-input-groupe' )
397
				.hide( 200, function () {
398
					$( this ).addClass( 'hidden' ).show();
399
				})
400
				.find( '#taxon-autre' ).val( '' );
401
		} else {
402
			$( '#taxon-input-groupe' )
403
				.hide()
404
				.removeClass( 'hidden' )
405
				.show(200)
406
				.find( '#taxon-autre' )
407
					.on( 'change', function() {
408
						if( !utils.valOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
409
							$( '#taxon' ).val( $( '#taxon-autre' ).val() )
410
								.data( 'value', $( '#taxon-autre' ).val() )
411
								.removeData([
412
									'numNomSel',
413
									'nomRet',
414
									'numNomRet',
415
									'nt',
416
									'famille'
417
								]);
418
						}
419
						$( '#taxon' ).trigger( 'change' );
420
					});
421
		}
422
	}
423
};
424
 
425
WidgetsSaisiesCommun.prototype.surChangementValeurTaxon = function() {
426
	var numNomSel = 0;
427
 
428
	if( this.valOk( $( '#taxon-liste' ).val() ) ) {
429
		if( 'autre' === $( '#taxon-liste' ).val() ) {
430
			this.ajouterAutocompletionNoms();
431
		} else {
432
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
433
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
434
				.data( 'value', $( '#taxon-liste' ).val() )
435
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
436
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
437
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
438
				.data( 'nt', optionRetenue.data( 'nt' ) )
439
				.data( 'famille', optionRetenue.data( 'famille' ) );
440
			$( '#taxon' ).trigger( 'change' );
441
 
442
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
443
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
444
			if( !this.valOk( numNomSel ) ) {
445
				$( '#certitude' ).find( 'option' ).each( function() {
446
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
447
						$( this ).attr( 'selected', true );
448
					} else {
449
						$( this ).attr( 'selected', false );
450
					}
451
				});
452
			}
453
		}
454
	}
455
};
456
 
457
// Autocompletion taxons ******************************************************/
458
/**
459
 * Initialise l'autocompletion taxons
460
 */
461
WidgetsSaisiesCommun.prototype.ajouterAutocompletionNoms = function() {
462
	const lthis = this;
463
	var taxonSelecteur = '#taxon';
464
 
465
	if ( this.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
466
		taxonSelecteur += '-autre';
467
	}
468
	$( taxonSelecteur ).autocomplete({
469
		source: function( requete, add ) {
470
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
471
			requete = '';
472
			$( '#taxon-autocomplete-label' ).addClass( 'loading' );
473
			if( lthis.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
474
				var url = lthis.getUrlAutocompletionNomsSci();
475
				$.getJSON( url, requete, function( data ) {
476
					var suggestions = lthis.traiterRetourNomsSci( data );
477
					add( suggestions );
478
				})
479
				.fail( function() {
480
					$( '#certitude' ).find( 'option' ).each( function() {
481
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
482
							$( this ).prop( 'selected', true );
483
						} else {
484
							$( this ).prop( 'selected', false );
485
						}
486
					});
487
				})
488
				.always(function() {
489
					$( '#taxon-autocomplete-label' ).removeClass( 'loading' );
490
				});
491
			}
492
		},
493
		html: true
494
	});
495
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
496
};
497
 
498
WidgetsSaisiesCommun.prototype.getUrlAutocompletionNomsSci = function() {
499
	var taxonSelecteur = '#taxon';
500
 
501
	if ( this.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
502
		taxonSelecteur += '-autre';
503
	}
504
	var mots = $( taxonSelecteur ).val();
505
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
506
	url = url.replace( '{masque}', mots );
507
 
508
	return url;
509
};
510
 
511
/**
512
 * Objet taxons pour autocompletion en fonction de la recherche
513
 */
514
WidgetsSaisiesCommun.prototype.traiterRetourNomsSci = function( data ) {
515
	var taxonSelecteur = '#taxon',
516
		suggestions    = [];
517
 
518
	if ( this.valOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
519
		taxonSelecteur += '-autre';
520
	}
521
	if ( undefined != data.resultat ) {
522
		$.each( data.resultat, function( i, val ) {
523
			val.nn = i;
524
 
525
			var nom = {
526
				label : '',
527
				value : '',
528
				nt : 0,
529
				nomSel : '',
530
				nomSelComplet : '',
531
				numNomSel : 0,
532
				nomRet : '',
533
				numNomRet : 0,
534
				famille : '',
535
				retenu : false
536
			};
537
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
538
				nom.label = '...';
539
				nom.value = $( taxonSelecteur ).val();
540
				suggestions.push( nom );
541
				return false;
542
			} else {
543
				nom.label = val.nom_sci_complet;
544
				nom.value = val.nom_sci_complet;
545
				nom.nt = val.num_taxonomique;
546
				nom.nomSel = val.nom_sci;
547
				nom.nomSelComplet = val.nom_sci_complet;
548
				nom.numNomSel = val.nn;
549
				nom.nomRet = val.nom_retenu_complet;
550
				nom.numNomRet = val['nom_retenu.id'];
551
				nom.famille = val.famille;
552
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
553
				// en tout cas c'est harmonisé avec le CeL
554
				nom.retenu = ( 'true' == val.retenu );
555
				suggestions.push( nom );
556
			}
557
		});
558
	}
559
	return suggestions;
560
};
561
 
562
/**
563
 * charge les données dans #taxon
564
 */
565
WidgetsSaisiesCommun.prototype.surAutocompletionTaxon = function( event, ui ) {
566
	if ( utils.valOk( ui ) ) {
567
		$( '#taxon' ).val( ui.item.value );
568
		$( '#taxon' ).data( 'value', ui.item.value )
569
			.data( 'numNomSel', ui.item.numNomSel )
570
			.data( 'nomRet', ui.item.nomRet )
571
			.data( 'numNomRet', ui.item.numNomRet )
572
			.data( 'nt', ui.item.nt )
573
			.data( 'famille', ui.item.famille );
574
		if ( ui.item.retenu ) {
575
			$( '#taxon' ).addClass( 'ns-retenu' );
576
		} else {
577
			$( '#taxon' ).removeClass( 'ns-retenu' );
578
		}
579
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
580
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
581
			$( '#certitude' ).find( 'option' ).each( function() {
582
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
583
					$( this ).attr( 'selected', true );
584
				} else {
585
					$( this ).attr( 'selected', false );
586
				}
587
			});
588
		}
589
	}
590
	$( '#taxon' ).change();
591
};
592
 
593
// Fichier Images *************************************************************/
594
/**
595
 * Affiche temporairement (formulaire)
596
 * la miniature d'une image ajoutée à l'obs
597
 */
598
WidgetsSaisiesCommun.prototype.afficherMiniature = function( reponse ) {
599
	if ( this.debug ) {
600
		var debogage = $( 'debogage', reponse ).text();
601
	}
602
 
603
	var message        = $( 'message', reponse ).text();
604
		$blocMiniature = $( '#miniatures .miniature.loading').first();
605
 
606
	if( this.valOk( $blocMiniature ) ) {
607
		if ( this.valOk( message ) ) {
608
			$( '.miniature-msg' ).text( message );
609
			$blocMiniature.remove();
610
 
611
		} else {
612
			this.creerWidgetMiniature( reponse, $blocMiniature );
613
			$blocMiniature.removeClass('loading');
614
		}
615
		if ( !lthis.valOk( $( '.miniature-chargement' ) ) ) {
616
			$( '#ajouter-obs' ).removeClass( 'hidden' );
617
			$( '#message-chargement' ).addClass( 'hidden' );
618
		}
619
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
620
	}
621
};
622
 
623
/**
624
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
625
 */
626
WidgetsSaisiesCommun.prototype.creerWidgetMiniature = function( reponse, $blocMiniature ) {
627
	var miniatureUrl = $( 'miniature-url', reponse ).text();
628
	var imgNom       = $( 'image-nom', reponse ).text();
629
 
630
	$blocMiniature.removeClass( 'miniature-chargement' );
631
	$( '.miniature-img', $blocMiniature )
632
		.removeClass( 'chargement-img' )
633
		.attr({
634
			'alt' : imgNom,
635
			'src' : miniatureUrl
636
		});
637
};
638
 
639
/**
640
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
641
 */
642
WidgetsSaisiesCommun.prototype.verifierFormat = function( nomImage ) {
643
	var parts     = nomImage.split( '.' ),
644
		extension = parts[ parts.length - 1 ];
645
 
646
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
647
};
648
 
649
/**
650
 * Check les miniatures déjà téléchargées
651
 * renvoie false si le même nom est rencontré 2 fois
652
 * renvoie true sinon
653
 */
654
WidgetsSaisiesCommun.prototype.verifierDuplication = function( nomImage ) {
655
	const lthis = this;
656
 
657
	var thisSrcParts = [],
658
		thisNomImage = '',
659
		nonDupliquee = true;
660
 
661
	nomImage = nomImage.toLowerCase();
662
 
663
	$( 'img.miniature-img,img.miniature' ).each( function() {
664
		// vérification avec alt de l'image
665
		if ( lthis.valOk ( $( this ).attr( 'alt' ) ) && $( this ).attr('alt' ).toLowerCase() === nomImage ) {
666
			nonDupliquee = false;
667
			return false;// Pas besoin de poursuivre la boucle
668
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
669
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
670
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' ).toLowerCase();
671
			if ( lthis.valOk( thisNomImage, true, nomImage ) ) {
672
				nonDupliquee = false;
673
				return false;
674
			}
675
		}
676
	});
677
	return nonDupliquee;
678
};
679
 
680
/**
681
 * Efface une miniature (formulaire)
682
 */
683
WidgetsSaisiesCommun.prototype.supprimerMiniature = function( miniature ) {
684
	miniature.parents( '.miniature' ).remove();
685
};
686
 
687
// Geoloc *********************************************************************/
688
WidgetsSaisiesCommun.prototype.transfererCarto = function( donnees ) {
689
	var typeLocalisation = donnees.typeLocalisation || 'point',
690
		isPoint          = ( typeLocalisation === 'point' ).toString(),
691
		suffixe          = ( this.valOk( donnees.suffixe ) ) ? '-' + donnees.suffixe : '',
692
		$cartoRemplacee  = donnees.cartoRemplacee || $( '#tb-geolocation' ),
693
		layer            = donnees.layer || 'osm',
694
		latitude         = donnees.latitude || '46.5',
695
		longitude        = donnees.longitude || '2.9',
696
		// 18 est le zoom max
697
		zoomInit         = donnees.zoomInit || 18;
698
 
699
	$cartoRemplacee.remove();
700
	$( '#geoloc' + suffixe ).append(
701
		'<tb-geolocation-element'+
702
			' id="tb-geolocation' + suffixe +'"'+
703
			' layer="' + layer + '"'+
704
			' zoom_init="' + zoomInit + '"'+
705
			' lat_init="' + latitude + '"'+
706
			' lng_init="' + longitude + '"'+
707
			' marker="' + isPoint + '"'+
708
			' polyline="' + !isPoint + '"'+
709
			' polygon="false"'+
710
			' show_lat_lng_elevation_inputs="' + isPoint + '"'+
711
			' osm_class_filter=""'+
712
			' elevation_provider="mapquest"'+
713
			' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
714
		'>'+
715
		'</tb-geolocation-element>'
716
	);
717
	this.initEvtsGeoloc( true );
718
};
719
 
720
// Ajouter Obs ****************************************************************/
721
/**
722
 * Ajoute une observation à la liste des obs à transmettre
723
 * (résumé obs)
724
 */
725
WidgetsSaisiesCommun.prototype.ajouterObs = function() {
726
	if ( this.isASL ) {
727
		this.scrollFormTop( '#zone-' + this.sujet );
728
	}
729
	// Fermeture automatique des dialogue de transmission de données
730
	// @WARNING TEST
731
	$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
732
	if ( this.validerForm() ) {
733
		this.masquerPanneau( '#dialogue-form-invalide' );
734
		this.obsNbre += 1;
735
		if ( this.isASL && 'arbres' === this.sujet ) {
736
			this.numArbre += 1;
737
			// bouton info de cet arbre et affichage numéro du prochain arbre
738
			this.lienArbreInfo( this.numArbre );
739
			$( '#arbre-nb' ).text( this.numArbre + 1 );
740
		}
741
		$( '.obs-nbre' ).text( this.obsNbre );
742
		$( '.obs-nbre' ).triggerHandler( 'changement' );
743
		//formatage des données
744
		var obsData = this.formaterFormObsData();
745
		this.afficherObs( obsData );
746
		this.stockerObsData( obsData );
747
		if ( this.isASL && 'arbres' === this.sujet ) {
748
			var arbreData = obsData.sujet;
749
			// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
750
			arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
751
			arbreData['id_observation']    = 0;
752
			this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
753
			this.releveDatas[this.obsNbre] = arbreData;
754
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
755
			this.modeArbresBasculerActivation( false );
756
		} else {
757
			this.reinitialiserForm();
758
		}
759
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
760
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
761
	} else {
762
		this.afficherPanneau( '#dialogue-form-invalide' );
763
	}
764
};
765
 
766
/**
767
 * Formatage des données du formulaire pour stockage et envoi
768
 */
769
WidgetsSaisiesCommun.prototype.formaterFormObsData = function() {
770
	var obsData      = { obsNum : this.obsNbre, sujet : {}},
771
		numNomSel    = $( '#taxon' ).data( 'numNomSel' ),
772
		nomSel       = $( '#taxon' ).val(),
773
		nomRet       = $( '#taxon' ).data( 'nomRet' ),
774
		numNomRet    = $( '#taxon' ).data( 'numNomRet' ),
775
		numTaxon     = $( '#taxon' ).data( 'nt' ),
776
		famille      = $( '#taxon' ).data( 'famille' ),
777
		referentiel  = ( this.valOk( numNomSel ) ) ? this.nomSciReferentiel : 'autre',
778
		certitude    = ( this.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
779
		imgB64       = [],
780
		imgNom       = [],
781
		date         = '',
782
		notes        = '',
783
		pays         = '',
784
		communeNom   = '',
785
		communeInsee = '',
786
		geometry     = '',
787
		latitude     = '',
788
		longitude    = '',
789
		altitude     = '',
790
		obsEtendue   = [];
791
 
792
	if( !this.isASL ) {
793
		notes            = $( '#notes' ).val().trim() || '';
794
		pays             = $( '#pays' ).val() || '';
795
		communeNom       = $( '#commune-nom' ).val();
796
		communeInsee     = $( '#commune-insee' ).val() || '';
797
		geometry         = $( '#geometry' ).val();
798
		latitude         = $( '#latitude' ).val();
799
		longitude        = $( '#longitude' ).val();
800
		altitude         = $( '#altitude' ).val();
801
		obsEtendue       = this.getObsChpSpecifiques();
802
		date             = this.fournirDate( $('#date_releve').val());
803
	} else {
804
		var miniatureImg = [];
805
		notes = $( '#commentaire' ).val() || '';
806
		if ( 'arbres' === this.sujet ) {
807
		// Dans ce cas cette fonction doit renvoyer des données au même format que l'input hidden "releve-data"
808
		// car les données dans stockerObsData provenir soit de cette fonction soit de l'input
809
			$( '.miniature-img' ).each( function() {
810
				if ( $( this ).hasClass( 'b64' ) ) {
811
					imgB64 = $( this ).attr( 'src' ) || '';
812
				} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
813
					imgB64 = $( this ).data( 'b64' ) || '';
814
				}
815
				miniatureImg.push({
816
					'nom' : $( this ).attr( 'alt' ),
817
					'src' : $( this ).attr( 'src' ),
818
					'b64' : imgB64
819
				});
820
			});
821
			obsData.sujet = {
822
				'num-arbre' : this.numArbre,
823
				taxon       : {
824
					'numNomSel' : numNomSel,
825
					'value'     : nomSel,
826
					'nomRet'    : nomRet,
827
					'numNomRet' : numNomRet,
828
					'nt'        : numTaxon,
829
					'famille'   : famille
830
				},
831
				'referentiel'      : referentiel,
832
				'certitude'        : certitude,
833
				'rue-arbres'       : ( $( '#rue-arbres' ).val() ) ? $('#rue-arbres').val() : '',
834
				'geometry-arbres'  : $( '#geometry-arbres' ).val(),
835
				'latitude-arbres'  : $( '#latitude-arbres' ).val(),
836
				'longitude-arbres' : $( '#longitude-arbres' ).val(),
837
				'altitude-arbres'  : $( '#altitude-arbres' ).val(),
838
				'circonference'    : $( '#circonference' ).val(),
839
				'com-arbres'       : ( $( '#com-arbres' ).val() ) ? $('#com-arbres').val() : '',
840
				'miniature-img'    : miniatureImg
841
			};
842
			obsData.releve = {
843
				'date'                  : this.fournirDate( $( '#releve-date' ).val() ),
844
				'rue'                   : $( '#rue' ).val(),
845
				'geometry-releve'       : $( '#geometry-releve' ).val(),
846
				'latitude-releve'       : $( '#latitude-releve' ).val(),
847
				'longitude-releve'      : $( '#longitude-releve' ).val(),
848
				'altitude-releve'       : $( '#altitude-releve' ).val(),
849
				'commune-nom'           : $( '#commune-nom' ).val(),
850
				'commune-insee'         : ( $( '#commune-insee' ).val() ) ? $('#commune-insee').val() : '',
851
				'pays'                  : ( $( '#pays' ).val() ) ? $('#pays').val() : '',
852
				'commentaires'          : notes
853
			};
854
			if ( 'tb_lichensgo' !== this.projet ) {
855
				obsData.sujet['surface-pied']          = $( '#surface-pied' ).val();
856
				obsData.sujet['equipement-pied-arbre'] = $( '#equipement-pied-arbre' ).val();
857
				obsData.sujet['tassement']             = $( '#tassement' ).val() || '';
858
				obsData.sujet['dejections']            = $( '#dejections input:checked' ).val() || '';
859
				obsData.releve['zone-pietonne']        = $( '#zone-pietonne input:checked' ).val();
860
				obsData.releve['pres-lampadaires']     = $( '#pres-lampadaires input:checked' ).val() || '';
861
			}
862
			if ( 'tb_streets' !== this.projet ) {
863
				var faceOmbre = [];
864
				$( '#face-ombre input' ).each( function() {
865
					if( $( this ).is( ':checked' ) ) {
866
						faceOmbre.push( $( this ).val() );
867
					}
868
				});
869
				obsData.sujet['face-ombre'] = faceOmbre;
870
			}
871
		} else {
872
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
873
			obsData.numArbre = $( '#choisir-arbre' ).val();
874
			pays             = this.releveDatas[0].pays || '';
875
			communeNom       = this.releveDatas[0]['commune-nom'];
876
			communeInsee     = this.releveDatas[0]['commune-insee'] || '';
877
			geometry         = this.releveDatas[obsData.numArbre]['geometry-arbres'];
878
			latitude         = this.releveDatas[obsData.numArbre]['latitude-arbres'];
879
			longitude        = this.releveDatas[obsData.numArbre]['longitude-arbres'];
880
			altitude         = this.releveDatas[obsData.numArbre]['altitude-arbres'];
881
			obsEtendue       = this.getObsChpSpecifiques( obsData.numArbre );
882
			date             = this.fournirDate( $( '#obs-date' ).val() );
883
		}
884
	}
885
	if ( !this.isASL || 'arbres' !== this.sujet ) {
886
		imgNom        = this.getNomsImgsOriginales();
887
		imgB64        = this.getB64ImgsOriginales();
888
 
889
		obsData.sujet = {
890
			'num_nom_sel'        : numNomSel,
891
			'nom_sel'            : nomSel,
892
			'nom_ret'            : nomRet,
893
			'num_nom_ret'        : numNomRet,
894
			'num_taxon'          : numTaxon,
895
			'famille'            : famille,
896
			'referentiel'        : referentiel,
897
			'certitude'          : certitude,
898
			'date'               : date,
899
			'notes'              : notes,
900
			'pays'               : pays,
901
			'commune_nom'        : communeNom,
902
			'commune_code_insee' : communeInsee,
903
			'geometry'           : geometry,
904
			'latitude'           : latitude,
905
			'longitude'          : longitude,
906
			'altitude'           : altitude,
907
			//Ajout des champs images
908
			'image_nom'          : imgNom,
909
			'image_b64'          : imgB64,
910
			// Ajout des champs étendus de l'obs
911
			'obs_etendue'        : obsEtendue
912
		};
913
		if ( !this.isASL ) {
914
			obsData.sujet['lieudit'] = $( '#lieudit' ).val() || '';
915
			obsData.sujet['station'] = $( '#station' ).val() || '';
916
			obsData.sujet['milieu']  = $( '#milieu' ).val() || '';
917
		}
918
	}
919
	return obsData;
920
};
921
 
922
/**
923
 * Affiche une observation dans la liste des observations à transmettre
924
 */
925
WidgetsSaisiesCommun.prototype.afficherObs = function( datasObs ) {
926
	// différences html liéees au responsive
927
	var responsivDiff1 = '',
928
		responsivDiff2 = '',
929
		responsivDiff3 = '',
930
		responsivDiff4 = '',
931
		responsivDiff5 = '',
932
		responsivDiff6 = '';
933
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
934
		/* La largeur minimum de l'affichage est 600 px inclus */
935
		responsivDiff1 = ' droite';
936
		responsivDiff2 = '<div></div>';
937
		responsivDiff3 = '<div class="row">';
938
		responsivDiff4 = ( !this.isASL ) ? ' col-md-2 col-sm-4' : ' col-md-4 col-sm-5';
939
		responsivDiff5 = ( !this.isASL ) ? ' class="col-md-9 col-sm-7"' : ' class="col-md-7 col-sm-6"';
940
		responsivDiff6 = '</div>';
941
	}
942
 
943
	var obsNum           = datasObs.obsNum,
944
		numNomSel        = datasObs.sujet['num_nom_sel'] || '',
945
		taxon            = '',
946
		miniatures       = '',
947
		notes            = '',
948
		commentaires     = '',
949
		date             = '',
950
		geometry         = '',
951
		latitude         = '',
952
		longitude        = '',
953
		coordonnees      = '',
954
		commune          = '',
955
		lieuObs          = '',
956
		inseeCommuneText = '',
957
		referentiel      = '',
958
		nn               = '',
959
		lieudit          = '',
960
		station          = '',
961
		milieu           = '',
962
		certitude        = '',
963
		numArbre         = '',
964
		obsArbre         = '';
965
 
966
	if ( !this.isASL ) {
967
		geometry     = datasObs.sujet['geometry'] || '';
968
		latitude     = datasObs.sujet['latitude'] || '';
969
		longitude    = datasObs.sujet['longitude'] || '';
970
		inseeCommune = datasObs.sujet['commune_code_insee'] || '';
971
		commune      = datasObs.sujet['commune_nom'] || '';
972
		if ( this.valOk( inseeCommune ) ) {
973
			inseeCommuneText = '(INSEE Commune:' + inseeCommune + ') ';
974
		}
975
		if ( this.valOk( numNomSel ) ) {
976
			referentiel = '<span class="referentiel-obs">' + '[' + datasObs.sujet['referentiel'] + ']' + '</span>';
977
		}
978
		if ( this.valOk( datasObs.sujet['lieudit'] ) ) {
979
			lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + datasObs.sujet['lieudit'] + ' ';
980
		}
981
		if ( this.valOk( datasObs.sujet['station'] ) ) {
982
			station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + datasObs.sujet['station'] + ' ';
983
		}
984
		if ( this.valOk( datasObs.sujet['milieu'] ) ) {
985
			milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + datasObs.sujet['milieu'] + ' ';
986
		}
987
		nn = this.ajouterNumNomSel( numNomSel );
988
	} else {
989
		certitude = ' [certitude : ' + datasObs.sujet.certitude + ']';
990
		if ( 'arbres' === this.sujet ) {
991
			numArbre   = datasObs.sujet['num-arbre'];
992
			numNomSel  = datasObs.sujet.taxon.numNomSel;
993
			taxon      = datasObs.sujet.taxon.value;
994
			miniatures = this.ajouterImgMiniatureAuTransfert(datasObs.sujet['miniature-img'] );
995
			notes      = datasObs.sujet['com-arbres'] || '';
996
			geometry   = datasObs.sujet['geometry-arbres'];
997
			latitude   = datasObs.sujet['latitude-arbres'];
998
			longitude  = datasObs.sujet['longitude-arbres'];
999
			numArbre   = datasObs.sujet['num-arbre'];
1000
			// s'assurer que la date est au bon format
1001
			date       = this.fournirDate( datasObs.releve.date );
1002
			commune    = datasObs.releve['commune-nom'] || '';
1003
		} else {
1004
			numArbre   = datasObs.numArbre;
1005
		}
1006
		obsArbre = '<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>';
1007
	}
1008
	if ( !this.isASL || 'arbres' !== this.sujet ) {
1009
		taxon      = datasObs.sujet['nom_sel'];
1010
		miniatures = this.ajouterImgMiniatureAuTransfert();
1011
		notes      = datasObs.sujet['notes'] || '';
1012
		date       = this.fournirDate( datasObs.sujet.date );
1013
	}
1014
	if( !this.isASL || 'arbres' === this.sujet ) {
1015
		if ( this.valOk( commune ) ) {
1016
			lieuObs = ' '  + this.msgTraduction( 'lieu-obs' ) + ' ' + '<span class="commune">' + commune + '</span> ';
1017
		}
1018
		if ( this.valOk( latitude ) && this.valOk( longitude ) ) {
1019
			coordonnees = '[' + latitude + ' / ' + longitude + ']';
1020
		}
1021
	}
1022
	if ( this.valOk( notes ) ) {
1023
		commentaires =
1024
			this.msgTraduction( 'commentaires' ) +
1025
			' : <span>'+
1026
				notes +
1027
			'</span> ';
1028
	}
1029
	// html du bloc résumé de l'obs
1030
	$( '#liste-obs' ).prepend(
1031
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
1032
			'<div '+
1033
				'class="obs-action" '+
1034
				'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1035
			'>'+
1036
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.msgTraduction( 'obs-numero' ) + obsNum + '">'+
1037
				'<i class="far fa-trash-alt"></i>'+
1038
				'</button>'+
1039
				responsivDiff2 +
1040
			'</div> '+
1041
			responsivDiff3 +
1042
				'<div class="thumbnail' + responsivDiff4 + '">'+
1043
					miniatures +
1044
				'</div>'+
1045
				'<div' + responsivDiff5 + '>'+
1046
					'<ul class="unstyled">'+
1047
						'<li>'+
1048
							// isASL
1049
							obsArbre +
1050
							// toujours
1051
							'<span class="nom-sci">' + taxon + '</span> '+
1052
							// !isASL
1053
							nn +
1054
							referentiel +
1055
							// isASL
1056
							certitude +
1057
							// !this.isASL || 'arbres' === this.sujet
1058
							lieuObs +
1059
							// !isASL
1060
							inseeCommuneText +
1061
							// !this.isASL || 'arbres' === this.sujet
1062
							coordonnees +
1063
							// toujours
1064
							' ' + this.msgTraduction( 'obs-le' ) + ' '+
1065
							'<span class="date">' + date + '</span>'+
1066
						'</li>'+
1067
						'<li>'+
1068
							// !isASL
1069
							lieudit +
1070
							station +
1071
							milieu +
1072
						'</li>'+
1073
						'<li>'+
1074
							// this.valOk( notes )
1075
							commentaires +
1076
						'</li>'+
1077
					'</ul>'+
1078
				'</div>'+
1079
			responsivDiff6+
1080
		'</div>'
1081
	);
1082
 
1083
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1084
};
1085
 
1086
/**
1087
 * Ajoute une boîte de miniatures avec défilement des images,
1088
 * pour une obs de la liste des obs à transmettre
1089
 */
1090
WidgetsSaisiesCommun.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages = undefined ) {
1091
	const lthis = this;
1092
	var html         =
1093
			'<div class="defilement-miniatures">'+
1094
				'<figure class="centre">'+
1095
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1096
				'</figure>'+
1097
			'</div>',
1098
		miniatures   = '',
1099
		centre       = '',
1100
		defilVisible = '',
1101
		length       = 0;
1102
 
1103
	if ( this.valOk( chargerImages ) || this.valOk( $( '#miniatures img' ) ) ) {
1104
		if ( this.valOk( chargerImages ) ) {
1105
			$.each(  chargerImages, function( i, value ) {
1106
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
1107
 
1108
				var css        = ( lthis.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
1109
					src        = value.src,
1110
					alt        = value.nom,
1111
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1112
 
1113
				miniatures += miniature;
1114
			});
1115
			length = chargerImages.length;
1116
		} else {
1117
			var premiere     = true;
1118
			$( '#miniatures img' ).each( function() {
1119
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1120
				premiere = false;
1121
 
1122
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1123
					src        = $( this ).attr( 'src' ),
1124
					alt        = $( this ).attr( 'alt' ),
1125
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1126
 
1127
				miniatures += miniature;
1128
			});
1129
			length = $( '#miniatures img' ).length;
1130
		}
1131
		if ( 1 === length ) {
1132
			centre       = 'centre';
1133
			defilVisible = ' defilement-miniatures-cache';
1134
		}
1135
		html             =
1136
			'<div class="defilement-miniatures">'+
1137
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1138
				'<figure class="' + centre + '">'+
1139
					miniatures+
1140
				'</figure>'+
1141
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1142
			'</div>';
1143
	}
1144
 
1145
	return html;
1146
};
1147
 
1148
/**
1149
 * Construit le html à afficher pour le numNom
1150
 */
1151
WidgetsSaisiesCommun.prototype.ajouterNumNomSel = function( numNomSel ) {
1152
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1153
 
1154
	if ( !this.valOk( numNomSel ) ) {
1155
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1156
	}
1157
 
1158
	return nn;
1159
};
1160
 
1161
/**
1162
 * Stocke des données d'obs à envoyer à la bdd
1163
 */
1164
WidgetsSaisiesCommun.prototype.stockerObsData = function( obsDatas ) {
1165
	if ( this.isASL && 'arbres' === this.sujet ) {
1166
		// Dans ce cas la fonction formaterFormObsData renvoie des données au même format que l'input hidden "releve-data"
1167
		// car les données peuvent provenir soit de la formaterFormObsData soit de cet input
1168
		const lthis = this;
1169
		// si releve dupliqué on ne stocke pas l'image :
1170
		var stockerImg  = this.valOk( obsDatas.sujet['miniature-img'] ),
1171
			imgNom      = [],
1172
			imgB64      = [];
1173
 
1174
		// Si on a bien un 'miniature-img' dans les données
1175
		if( stockerImg ) {
1176
			$.each( obsDatas.sujet['miniature-img'], function( i, obj ) {
1177
				if( obj.hasOwnProperty( 'id' ) ) {
1178
					stockerImg = false;
1179
				}
1180
				return stockerImg;
1181
			});
1182
		}
1183
		// Si les miniatures ne sont pas déjà stockées (résultat de la loop précédente)
1184
		if( stockerImg ) {
1185
			$.each( obsDatas.sujet['miniature-img'] , function( i, obj ) {
1186
				if( lthis.valOk( obj.nom ) ) {
1187
					imgNom.push( obj.nom );
1188
				}
1189
				if( lthis.valOk( obj['b64'] ) ) {
1190
					imgB64.push( obj['b64'] );
1191
				}
1192
			});
1193
		} else {
1194
			imgNom = lthis.getNomsImgsOriginales();
1195
			imgB64 = lthis.getB64ImgsOriginales();
1196
		}
1197
		// Stockage en data des données d'obs à transmettre
1198
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, {
1199
			'num_nom_sel'        : obsDatas.sujet.taxon.numNomSel,
1200
			'nom_sel'            : obsDatas.sujet.taxon.value,
1201
			'nom_ret'            : obsDatas.sujet.taxon.nomRet,
1202
			'num_nom_ret'        : obsDatas.sujet.taxon.numNomRet,
1203
			'num_taxon'          : obsDatas.sujet.taxon.nt,
1204
			'famille'            : obsDatas.sujet.taxon.famille,
1205
			'referentiel'        : obsDatas.sujet.referentiel,
1206
			'certitude'          : obsDatas.sujet.certitude,
1207
			// La date provenant de input "releve-data" n'est pas au bon format
1208
			'date'               : this.fournirDate( obsDatas.releve.date ),
1209
			'notes'              : obsDatas.releve.commentaires.trim(),
1210
			'pays'               : obsDatas.releve.pays,
1211
			'commune_nom'        : obsDatas.releve['commune-nom'],
1212
			'commune_code_insee' : obsDatas.releve['commune-insee'],
1213
			'geometry'           : obsDatas.sujet['geometry-arbres'],
1214
			'latitude'           : obsDatas.sujet['latitude-arbres'],
1215
			'longitude'          : obsDatas.sujet['longitude-arbres'],
1216
			'altitude'           : obsDatas.sujet['altitude-arbres'],
1217
			'image_nom'          : imgNom,
1218
			'image_b64'          : imgB64,
1219
			// Ajout des champs étendus de l'obs
1220
			'obs_etendue'        : lthis.getObsChpSpecifiques( obsDatas )
1221
		});
1222
	} else {
1223
		// Stockage en data des données d'obs à transmettre
1224
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, obsDatas.sujet );
1225
	}
1226
};
1227
 
1228
WidgetsSaisiesCommun.prototype.getNomsImgsOriginales = function() {
1229
	var noms = new Array();
1230
 
1231
	$( '.miniature-img' ).each( function() {
1232
		noms.push( $( this ).attr( 'alt' ) );
1233
	});
1234
 
1235
	return noms;
1236
};
1237
 
1238
WidgetsSaisiesCommun.prototype.getB64ImgsOriginales = function() {
1239
	var b64 = new Array();
1240
 
1241
	$( '.miniature-img' ).each( function() {
1242
		if ( $( this ).hasClass( 'b64' ) ) {
1243
			b64.push( $( this ).attr( 'src' ) );
1244
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1245
			b64.push( $( this ).data( 'b64' ) );
1246
		}
1247
	});
1248
 
1249
	return b64;
1250
};
1251
 
1252
/**
1253
 * Efface toutes les miniatures (formulaire)
1254
 */
1255
WidgetsSaisiesCommun.prototype.supprimerMiniatures = function() {
1256
	if ( !this.isASL ) {
1257
		// Déconnection MutationObserver miniatures
1258
		// Sinon on a une erreur avant la création d'une nouvelle obs
1259
		this.observer.disconnect();
1260
		$( '#miniatures' ).empty();
1261
		// Validation miniatures reprend à 0 pour une nouvelle obs
1262
		this.surPresenceAbsenceMiniature();
1263
	} else {
1264
		$( '#miniatures' ).empty();
1265
	}
1266
	$( '#miniature-msg' ).empty();
1267
};
1268
 
1269
WidgetsSaisiesCommun.prototype.surChangementNbreObs = function() {
1270
	if ( 0 === this.obsNbre ) {
1271
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1272
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1273
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1274
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1275
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1276
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1277
	}
1278
	if ( this.isASL && 'arbres' === this.sujet ) {
1279
		if ( 0 <= this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1280
			$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1281
		} else {
1282
			$( '#bloc-form-arbres' ).addClass( 'hidden' );
1283
		}
1284
	}
1285
};
1286
 
1287
WidgetsSaisiesCommun.prototype.defilerMiniatures = function( element ) {
1288
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1289
 
1290
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1291
	miniatureSelectionne.addClass( 'miniature-cachee' );
1292
 
1293
	var miniatureAffichee     = miniatureSelectionne;
1294
 
1295
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1296
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1297
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1298
		} else {
1299
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1300
		}
1301
	} else {
1302
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1303
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1304
		} else {
1305
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1306
		}
1307
	}
1308
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1309
	miniatureAffichee.removeClass( 'miniature-cachee' );
1310
};
1311
 
1312
WidgetsSaisiesCommun.prototype.supprimerObs = function( selector ) {
1313
	var obsId = $( selector ).val();
1314
 
1315
	// Problème avec IE 6 et 7
1316
	if ( 'Supprimer' === obsId ) {
1317
		obsId = $( selector ).attr( 'title' );
1318
	}
1319
	this.supprimerObsParId( obsId );
1320
};
1321
 
1322
/**
1323
 * Supprime l'obs et les data de l'obs
1324
 * et remonte les suivantes d'un cran
1325
 */
1326
WidgetsSaisiesCommun.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1327
	if ( this.isASL && 'arbres' === this.sujet ) {
1328
		if ( !transmission ) {
1329
			this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1330
			this.releveData.splice( obsId , 1 );
1331
			$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1332
		}
1333
		$( '#arbre-info-' + ( this.numArbre ) ).remove();
1334
		$( '#arbre-nb' ).text( this.numArbre );
1335
		this.numArbre -= 1;
1336
		if ( 1 > this.numArbre ) {
1337
			$( '#bloc-info-arbres-title' ).addClass( 'hidden' );
1338
		}
1339
 
1340
		var arbreExId   = 0,
1341
			arbreId     = 0;
1342
	}
1343
	this.obsNbre  -= 1;
1344
	$( '.obs-nbre' ).text( this.obsNbre );
1345
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1346
	$( '.obs' + obsId ).remove();
1347
	obsId = parseInt(obsId);
1348
 
1349
	if ( !transmission ) {
1350
		var listObsData = $( '#liste-obs' ).data(),
1351
			exId        = 0,
1352
			indexObs    = '',
1353
			exIndexObs  = '';
1354
 
1355
		for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1356
			exId       = parseInt(id) + 1;
1357
			indexObs   = 'obsId' + id;
1358
			exIndexObs = 'obsId' + exId;
1359
			$( '#liste-obs' ).removeData( indexObs );
1360
			$( '#obs' + exId )
1361
				.attr( 'id', 'obs' + id )
1362
				.removeClass( 'obs' + exId )
1363
				.addClass( 'obs' + id )
1364
				.find( '.supprimer-obs' )
1365
					.attr( 'title', 'Observation n°' + id )
1366
					.val( id );
1367
 
1368
			if ( this.isASL && 'arbres' === this.sujet ) {
1369
				arbreExId = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1370
				arbreId   = arbreExId - 1;
1371
				$( '#obs-arbre-' + arbreExId )
1372
					.attr( 'id', 'obs-arbre-' + arbreId )
1373
					.attr( 'data-arbre', arbreId )
1374
					.data( 'arbre', arbreId )
1375
					.text( 'Arbre ' + arbreId );
1376
				// modification du numero d'arbre dans les obs étendues
1377
				if ( this.valOk( listObsData[exIndexObs] ) ) {
1378
					$.each( listObsData[exIndexObs].obs_etendue, function( i, obsE ) {
1379
						if ('num_arbre' === obsE.cle ) {
1380
							listObsData[exIndexObs].obs_etendue[i].valeur = arbreId;
1381
							return false;
1382
						}
1383
					});
1384
				}
1385
			}
1386
 
1387
			// Mise à jour des données à transmettre
1388
			if ( this.valOk( listObsData[exIndexObs] ) ) {
1389
				$( '#liste-obs' ).data( indexObs, listObsData[exIndexObs] );
1390
			}
1391
			if ( parseInt( id ) !== this.obsNbre ) {
1392
				id = parseInt(id);
1393
			}
1394
		}
1395
	} else {
1396
		$( '#liste-obs' ).removeData( 'obsId' + obsId );
1397
	}
1398
};
1399
 
1400
WidgetsSaisiesCommun.prototype.transmettreObs = function() {
1401
	const lthis = this;
1402
	var observations = $( '#liste-obs' ).data();
1403
 
1404
	if ( this.debug ) {
1405
		console.dir( observations );
1406
	}
1407
	if ( !this.valOk( typeof observations, true, 'object' ) ) {
1408
		this.afficherPanneau( '#dialogue-zero-obs' );
1409
	} else {
1410
		this.nbObsEnCours         = 1;
1411
		this.nbObsTransmises      = 0;
1412
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1413
			return i;
1414
		}).length;
1415
		this.depilerObsPourEnvoi();
1416
	}
1417
 
1418
	return false;
1419
};
1420
 
1421
WidgetsSaisiesCommun.prototype.depilerObsPourEnvoi = function() {
1422
	var observations = $( '#liste-obs' ).data();
1423
	// la boucle est factice car on utilise un tableau
1424
	// dont on a besoin de n'extraire que le premier élément
1425
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1426
	// TODO: utiliser var.keys quand ça sera plus répandu
1427
	// ou bien utiliser un vrai tableau et pas un objet
1428
	for ( var obsNum in observations ) {
1429
		var obsATransmettre = {
1430
			'id_projet' : this.idProjet,
1431
			'projet'    : this.projet,
1432
			'tag-obs'   : this.tagObs,
1433
			'tag-img'   : this.tagImg
1434
		};
1435
		var utilisateur = {
1436
			id_utilisateur : $( '#id_utilisateur' ).val(),
1437
			prenom         : $( '#prenom' ).val(),
1438
			nom            : $( '#nom' ).val(),
1439
			courriel       : $( '#courriel' ).val()
1440
		};
1441
 
1442
		obsATransmettre['utilisateur'] = utilisateur;
1443
		obsATransmettre[obsNum]        = observations[obsNum];
1444
 
1445
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1446
 
1447
		if( '' !== idObsNumerique ) {
1448
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1449
		}
1450
		break;
1451
	}
1452
};
1453
 
1454
WidgetsSaisiesCommun.prototype.envoyerObsAuCel = function( idObs, observation ) {
1455
	const lthis = this;
1456
 
1457
	var erreurMsg = '';
1458
 
1459
	$.ajax({
1460
		url        : lthis.serviceSaisieUrl,
1461
		type       : 'POST',
1462
		data       : observation,
1463
		dataType   : 'json',
1464
		beforeSend : function() {
1465
			$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1466
			$( '.alert-txt' ).empty();
1467
			$( '.alert-txt .msg-erreur,.alert-txt .msg-debug' ).remove();
1468
			$( '#chargement' ).removeClass( 'hidden' );
1469
		},
1470
		success    : function( transfertDatas, textStatus, jqXHR ) {
1471
			if( lthis.isASL && 'arbres' === lthis.sujet ) {
1472
				// actualisation de id_observation dans '#releve-data'
1473
				lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1474
			}
1475
			// mise à jour du nombre d'obs à transmettre
1476
			// et suppression de l'obs
1477
			lthis.supprimerObsParId( idObs, true );
1478
			lthis.nbObsEnCours++;
1479
			// mise à jour du statut
1480
			lthis.mettreAJourProgression();
1481
			if( 0 < lthis.obsNbre ) {
1482
				// dépilement de la suivante
1483
				lthis.depilerObsPourEnvoi();
1484
			}
1485
		},
1486
		statusCode  : {
1487
			500 : function( jqXHR, textStatus, errorThrown ) {
1488
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1489
				}
1490
		},
1491
		error        : function( jqXHR, textStatus, errorThrown ) {
1492
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1493
			try {
1494
				reponse = jQuery.parseJSON( jqXHR.responseText );
1495
				if ( null !== reponse ) {
1496
					$.each( reponse, function( cle, valeur ) {
1497
						erreurMsg += valeur + '\n';
1498
					});
1499
				}
1500
			} catch( e ) {
1501
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1502
			}
1503
		},
1504
		complete      : function( jqXHR, textStatus ) {
1505
			var debugMsg = lthis.extraireEnteteDebug( jqXHR );
1506
 
1507
			if ( '' !== erreurMsg ) {
1508
				if ( lthis.debug ) {
1509
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1510
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1511
				}
1512
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1513
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagsMotsCles+
1514
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1515
 
1516
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1517
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1518
					$( '#tpl-transmission-ko' ).clone()
1519
						.find( '.courriel-erreur' )
1520
						.attr( 'href', hrefCourriel )
1521
						.end()
1522
						.html()
1523
				);
1524
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1525
				$( '#chargement' ).addClass( 'hidden' );
1526
				lthis.initialiserBarreProgression;
1527
			} else {
1528
				if ( lthis.debug ) {
1529
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1530
				}
1531
				if( 0 === lthis.obsNbre ) {
1532
					setTimeout( function() {
1533
						if ( lthis.isASL ) {
1534
							if ( 'arbres' === lthis.sujet ) {
1535
								if ( 'tb_streets' !== lthis.projet ) {
1536
									$( '#bouton-saisir-lichens' ).removeClass( 'hidden' );
1537
								}
1538
								if ( 'tb_lichensgo' !== lthis.projet ) {
1539
									$( '#bouton-saisir-plantes' ).removeClass( 'hidden' );
1540
								}
1541
							} else {
1542
								$( '#bouton-poursuivre' ).removeClass( 'hidden' );
1543
							}
1544
							$( '#bloc-controle-liste-obs,#bloc-gauche' ).addClass( 'hidden' );
1545
						}
1546
						$( '#chargement' ).addClass( 'hidden' );
1547
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1548
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1549
					}, 1500 );
1550
				}
1551
			}
1552
		}
1553
	});
1554
};
1555
 
1556
WidgetsSaisiesCommun.prototype.mettreAJourProgression = function() {
1557
	this.nbObsTransmises++;
1558
 
1559
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1560
 
1561
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1562
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1563
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1564
	if( 0 === this.obsNbre ) {
1565
		$( '.progress' ).removeClass( 'active' );
1566
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1567
	}
1568
};
1569
 
1570
WidgetsSaisiesCommun.prototype.initialiserBarreProgression = function() {
1571
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1572
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1573
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1574
	$( '.progress' ).addClass( 'active' );
1575
	$( '.progress' ).addClass( 'progress-bar-striped' );
1576
};
1577
 
1578
// Form Validator *************************************************************/
1579
WidgetsSaisiesCommun.prototype.configurerFormValidator = function() {
1580
	const lthis = this;
1581
 
1582
	$.validator.addMethod(
1583
		'dateCel',
1584
		function ( value, element ) {
1585
			return ( lthis.valOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
1586
		},
1587
		lthis.msgTraduction( 'date-incomplete' )
1588
	);
1589
	$.validator.addMethod(
1590
		'userEmailOk',
1591
		function ( value, element ) {
1592
			return ( lthis.valOk( value ) );
1593
		},
1594
		''
1595
	);
1596
	$.validator.addMethod(
1597
		'minMaxOk',
1598
		function ( value, element, param ) {
1599
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1600
			return lthis.validerMinMax( element ).cond;
1601
		},
1602
		$.validator.messages.minMaxOk
1603
	);
1604
	$.validator.addMethod(
1605
		'listFields',
1606
		function ( value, element ) {
1607
			return ( lthis.valOk( value ) );
1608
		},
1609
		''
1610
	);
1611
	$.extend( $.validator.defaults, {
1612
		errorElement: 'span',
1613
		errorPlacement: function( error, element ) {
1614
			if ( lthis.isASL && 'arbres' === lthis.sujet && ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) ) {
1615
				error.appendTo( element.closest( '.list' ) );
1616
			} else {
1617
				element.after( error );
1618
			}
1619
		},
1620
		onfocusout: function( element ) {
1621
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1622
				if ( $( element ).valid() ) {
1623
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1624
				} else {
1625
					$( element ).closest( '.control-group' ).addClass( 'error' );
1626
				}
1627
			}
1628
		},
1629
		onkeyup : function( element ) {
1630
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1631
				if ( $( element ).valid() ) {
1632
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1633
				} else {
1634
					$( element ).closest( '.control-group' ).addClass( 'error' );
1635
				}
1636
			}
1637
		},
1638
		unhighlight: function( element ) {
1639
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1640
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1641
			}
1642
		},
1643
		highlight: function( element ) {
1644
			$( element ).closest( '.control-group' ).addClass( 'error' );
1645
		}
1646
	});
1647
};
1648
 
1649
// Formatage date *************************************************************/
1650
WidgetsSaisiesCommun.prototype.fournirDate = function( dateObs ) {
1651
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1652
		return dateObs;
1653
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1654
		var dateArray = dateObs.split( '-' );
1655
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1656
	} else {
1657
		console.dir( 'erreur date : ' + dateObs )
1658
	}
1659
};
1660
 
1661
// scroll vers le formulaire
1662
WidgetsSaisiesCommun.prototype.scrollFormTop = function( scrollSelecteur, focus = '' ) {
1663
	const lthis = this;
1664
 
1665
	$( 'html, body' ).stop().animate({
1666
		scrollTop: $( scrollSelecteur ).offset().top
1667
	}, 300, function() {
1668
		if ( lthis.valOk( focus ) ) {
1669
			$( focus ).focus();
1670
		} else {
1671
			return;
1672
		}
1673
	});
1674
};
1675
 
1676
// Controle des panneaux d'infos **********************************************/
1677
 
1678
WidgetsSaisiesCommun.prototype.afficherPanneau = function( selecteur ) {
1679
	$( selecteur )
1680
		.removeClass( 'hidden' )
1681
		.hide()
1682
		.show( 600 )
1683
		.delay( this.dureeMessage )
1684
		.hide( 600 );
1685
	this.scrollFormTop( selecteur );
1686
};
1687
 
1688
WidgetsSaisiesCommun.prototype.masquerPanneau = function( selecteur ) {
1689
	$( selecteur ).addClass( 'hidden' );
1690
};
1691
 
1692
WidgetsSaisiesCommun.prototype.fermerPanneauAlert = function() {
1693
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1694
};
1695
 
1696
/**
1697
 * Si la langue est définie dans this.langue, et si des messages sont définis
1698
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1699
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1700
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1701
 */
1702
WidgetsSaisiesCommun.prototype.msgTraduction = function( cle ) {
1703
	var msg = 'N/A';
1704
 
1705
	if ( this.msgs ) {
1706
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1707
			msg = this.msgs[this.langue][cle];
1708
		} else if ( cle in this.msgs['fr'] ) {
1709
			msg = this.msgs['fr'][cle];
1710
		}
1711
	}
1712
	return msg;
1713
};
1714
 
1715
/**
1716
* Stope l'évènement courant quand on clique sur un lien.
1717
* Utile pour Chrome, Safari...
1718
*/
1719
WidgetsSaisiesCommun.prototype.arreter = function( event ) {
1720
	if ( event.stopPropagation ) {
1721
		event.stopPropagation();
1722
	}
1723
	if ( event.preventDefault ) {
1724
		event.preventDefault();
1725
	}
1726
 
1727
	return false;
1728
};
1729
 
1730
/**
1731
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1732
 * @param jqXHR
1733
 * @returns {String}
1734
 */
1735
WidgetsSaisiesCommun.prototype.extraireEnteteDebug = function( jqXHR ) {
1736
	var msgDebug = '';
1737
 
1738
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1739
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1740
		if ( null !== debugInfos ) {
1741
			$.each( debugInfos, function( cle, valeur ) {
1742
				msgDebug += valeur + '\n';
1743
			});
1744
		}
1745
	}
1746
 
1747
	return msgDebug;
1748
};
1749
 
1750
 
1751
WidgetsSaisiesCommun.prototype.confirmerSortie = function() {
1752
	$( window ).off( 'beforeunload' ).on( 'beforeunload', function( event ) {
1753
		if ( !event ) {
1754
			event = window.event;
1755
		}
1756
		return false;
1757
	});
1758
};
1759
 
1760
WidgetsSaisiesCommun.prototype.valOk = function ( valeur, sensComparaison = true, comparer = undefined ) {
1761
	return utils.valOk( valeur, sensComparaison, comparer );
1762
};
1763
 
1764
WidgetsSaisiesCommun.prototype.activerModale = function ( label, content = '', buttons = [] ) {
1765
	return utils.activerModale( label, content, buttons );
1766
};
1767
 
1768
// Lib hors objet
1769
 
1770
/*
1771
 * jQuery UI Autocomplete HTML Extension
1772
 *
1773
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1774
 * Dual licensed under the MIT or GPL Version 2 licenses.
1775
 *
1776
 * http://github.com/scottgonzalez/jquery-ui-extensions
1777
 *
1778
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1779
 */
1780
( function( $ ) {
1781
	var proto      = $.ui.autocomplete.prototype,
1782
		initSource = proto._initSource;
1783
 
1784
	WidgetsSaisiesCommun.prototype.filter = function( array, term ) {
1785
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1786
 
1787
		return $.grep( array, function( value ) {
1788
 
1789
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1790
		});
1791
	}
1792
	$.extend( proto, {
1793
		_initSource: function() {
1794
			if ( this.options.html && $.isArray( this.options.source ) ) {
1795
				this.source = function( request, response ) {
1796
					response( filter( this.options.source, request.term ) );
1797
				};
1798
			} else {
1799
				initSource.call( this );
1800
			}
1801
		},
1802
		_renderItem: function( ul, item) {
1803
			if ( item.retenu ) {
1804
				item.label = '<strong>' + item.label + '</strong>';
1805
			}
1806
 
1807
			return $( '<li></li>' )
1808
				.data( 'item.autocomplete', item )
1809
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1810
				.appendTo( ul );
1811
		}
1812
	});
1813
})( jQuery );