Subversion Repositories eFlore/Applications.cel

Rev

Rev 3638 | Rev 3811 | Go to most recent revision | Details | Compare with Previous | 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
			if( lthis.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
473
				var url = lthis.getUrlAutocompletionNomsSci();
3710 idir 474
 
475
				$( '#taxon-autocomplete-label' ).addClass( 'loading' );
3638 delphine 476
				$.getJSON( url, requete, function( data ) {
477
					var suggestions = lthis.traiterRetourNomsSci( data );
478
					add( suggestions );
479
				})
480
				.fail( function() {
481
					$( '#certitude' ).find( 'option' ).each( function() {
482
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
483
							$( this ).prop( 'selected', true );
484
						} else {
485
							$( this ).prop( 'selected', false );
486
						}
487
					});
488
				})
489
				.always(function() {
490
					$( '#taxon-autocomplete-label' ).removeClass( 'loading' );
491
				});
492
			}
493
		},
494
		html: true
495
	});
496
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
497
};
498
 
499
WidgetsSaisiesCommun.prototype.getUrlAutocompletionNomsSci = function() {
500
	var taxonSelecteur = '#taxon';
501
 
502
	if ( this.valOk( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
503
		taxonSelecteur += '-autre';
504
	}
505
	var mots = $( taxonSelecteur ).val();
506
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
507
	url = url.replace( '{masque}', mots );
508
 
509
	return url;
510
};
511
 
512
/**
513
 * Objet taxons pour autocompletion en fonction de la recherche
514
 */
515
WidgetsSaisiesCommun.prototype.traiterRetourNomsSci = function( data ) {
516
	var taxonSelecteur = '#taxon',
517
		suggestions    = [];
518
 
519
	if ( this.valOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
520
		taxonSelecteur += '-autre';
521
	}
522
	if ( undefined != data.resultat ) {
523
		$.each( data.resultat, function( i, val ) {
524
			val.nn = i;
525
 
526
			var nom = {
527
				label : '',
528
				value : '',
529
				nt : 0,
530
				nomSel : '',
531
				nomSelComplet : '',
532
				numNomSel : 0,
533
				nomRet : '',
534
				numNomRet : 0,
535
				famille : '',
536
				retenu : false
537
			};
538
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
539
				nom.label = '...';
540
				nom.value = $( taxonSelecteur ).val();
541
				suggestions.push( nom );
542
				return false;
543
			} else {
544
				nom.label = val.nom_sci_complet;
545
				nom.value = val.nom_sci_complet;
546
				nom.nt = val.num_taxonomique;
547
				nom.nomSel = val.nom_sci;
548
				nom.nomSelComplet = val.nom_sci_complet;
549
				nom.numNomSel = val.nn;
550
				nom.nomRet = val.nom_retenu_complet;
551
				nom.numNomRet = val['nom_retenu.id'];
552
				nom.famille = val.famille;
553
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
554
				// en tout cas c'est harmonisé avec le CeL
555
				nom.retenu = ( 'true' == val.retenu );
556
				suggestions.push( nom );
557
			}
558
		});
559
	}
560
	return suggestions;
561
};
562
 
563
/**
564
 * charge les données dans #taxon
565
 */
566
WidgetsSaisiesCommun.prototype.surAutocompletionTaxon = function( event, ui ) {
567
	if ( utils.valOk( ui ) ) {
568
		$( '#taxon' ).val( ui.item.value );
569
		$( '#taxon' ).data( 'value', ui.item.value )
570
			.data( 'numNomSel', ui.item.numNomSel )
571
			.data( 'nomRet', ui.item.nomRet )
572
			.data( 'numNomRet', ui.item.numNomRet )
573
			.data( 'nt', ui.item.nt )
574
			.data( 'famille', ui.item.famille );
575
		if ( ui.item.retenu ) {
576
			$( '#taxon' ).addClass( 'ns-retenu' );
577
		} else {
578
			$( '#taxon' ).removeClass( 'ns-retenu' );
579
		}
580
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
581
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
582
			$( '#certitude' ).find( 'option' ).each( function() {
583
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
584
					$( this ).attr( 'selected', true );
585
				} else {
586
					$( this ).attr( 'selected', false );
587
				}
588
			});
589
		}
590
	}
591
	$( '#taxon' ).change();
592
};
593
 
594
// Fichier Images *************************************************************/
595
/**
596
 * Affiche temporairement (formulaire)
597
 * la miniature d'une image ajoutée à l'obs
598
 */
599
WidgetsSaisiesCommun.prototype.afficherMiniature = function( reponse ) {
600
	if ( this.debug ) {
601
		var debogage = $( 'debogage', reponse ).text();
602
	}
603
 
604
	var message        = $( 'message', reponse ).text();
605
		$blocMiniature = $( '#miniatures .miniature.loading').first();
606
 
607
	if( this.valOk( $blocMiniature ) ) {
608
		if ( this.valOk( message ) ) {
609
			$( '.miniature-msg' ).text( message );
610
			$blocMiniature.remove();
611
 
612
		} else {
613
			this.creerWidgetMiniature( reponse, $blocMiniature );
614
			$blocMiniature.removeClass('loading');
615
		}
616
		if ( !lthis.valOk( $( '.miniature-chargement' ) ) ) {
617
			$( '#ajouter-obs' ).removeClass( 'hidden' );
618
			$( '#message-chargement' ).addClass( 'hidden' );
619
		}
620
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
621
	}
622
};
623
 
624
/**
625
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
626
 */
627
WidgetsSaisiesCommun.prototype.creerWidgetMiniature = function( reponse, $blocMiniature ) {
628
	var miniatureUrl = $( 'miniature-url', reponse ).text();
629
	var imgNom       = $( 'image-nom', reponse ).text();
630
 
631
	$blocMiniature.removeClass( 'miniature-chargement' );
632
	$( '.miniature-img', $blocMiniature )
633
		.removeClass( 'chargement-img' )
634
		.attr({
635
			'alt' : imgNom,
636
			'src' : miniatureUrl
637
		});
638
};
639
 
640
/**
641
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
642
 */
643
WidgetsSaisiesCommun.prototype.verifierFormat = function( nomImage ) {
644
	var parts     = nomImage.split( '.' ),
645
		extension = parts[ parts.length - 1 ];
646
 
647
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
648
};
649
 
650
/**
651
 * Check les miniatures déjà téléchargées
652
 * renvoie false si le même nom est rencontré 2 fois
653
 * renvoie true sinon
654
 */
655
WidgetsSaisiesCommun.prototype.verifierDuplication = function( nomImage ) {
656
	const lthis = this;
657
 
658
	var thisSrcParts = [],
659
		thisNomImage = '',
660
		nonDupliquee = true;
661
 
662
	nomImage = nomImage.toLowerCase();
663
 
664
	$( 'img.miniature-img,img.miniature' ).each( function() {
665
		// vérification avec alt de l'image
666
		if ( lthis.valOk ( $( this ).attr( 'alt' ) ) && $( this ).attr('alt' ).toLowerCase() === nomImage ) {
667
			nonDupliquee = false;
668
			return false;// Pas besoin de poursuivre la boucle
669
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
670
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
671
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' ).toLowerCase();
672
			if ( lthis.valOk( thisNomImage, true, nomImage ) ) {
673
				nonDupliquee = false;
674
				return false;
675
			}
676
		}
677
	});
678
	return nonDupliquee;
679
};
680
 
681
/**
682
 * Efface une miniature (formulaire)
683
 */
684
WidgetsSaisiesCommun.prototype.supprimerMiniature = function( miniature ) {
685
	miniature.parents( '.miniature' ).remove();
686
};
687
 
688
// Geoloc *********************************************************************/
689
WidgetsSaisiesCommun.prototype.transfererCarto = function( donnees ) {
690
	var typeLocalisation = donnees.typeLocalisation || 'point',
691
		isPoint          = ( typeLocalisation === 'point' ).toString(),
692
		suffixe          = ( this.valOk( donnees.suffixe ) ) ? '-' + donnees.suffixe : '',
693
		$cartoRemplacee  = donnees.cartoRemplacee || $( '#tb-geolocation' ),
694
		layer            = donnees.layer || 'osm',
695
		latitude         = donnees.latitude || '46.5',
696
		longitude        = donnees.longitude || '2.9',
697
		// 18 est le zoom max
698
		zoomInit         = donnees.zoomInit || 18;
699
 
700
	$cartoRemplacee.remove();
701
	$( '#geoloc' + suffixe ).append(
702
		'<tb-geolocation-element'+
703
			' id="tb-geolocation' + suffixe +'"'+
704
			' layer="' + layer + '"'+
705
			' zoom_init="' + zoomInit + '"'+
706
			' lat_init="' + latitude + '"'+
707
			' lng_init="' + longitude + '"'+
708
			' marker="' + isPoint + '"'+
709
			' polyline="' + !isPoint + '"'+
710
			' polygon="false"'+
711
			' show_lat_lng_elevation_inputs="' + isPoint + '"'+
712
			' osm_class_filter=""'+
713
			' elevation_provider="mapquest"'+
714
			' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
715
		'>'+
716
		'</tb-geolocation-element>'
717
	);
718
	this.initEvtsGeoloc( true );
719
};
720
 
721
// Ajouter Obs ****************************************************************/
722
/**
723
 * Ajoute une observation à la liste des obs à transmettre
724
 * (résumé obs)
725
 */
726
WidgetsSaisiesCommun.prototype.ajouterObs = function() {
727
	if ( this.isASL ) {
728
		this.scrollFormTop( '#zone-' + this.sujet );
729
	}
730
	// Fermeture automatique des dialogue de transmission de données
731
	// @WARNING TEST
732
	$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
733
	if ( this.validerForm() ) {
734
		this.masquerPanneau( '#dialogue-form-invalide' );
735
		this.obsNbre += 1;
736
		if ( this.isASL && 'arbres' === this.sujet ) {
737
			this.numArbre += 1;
738
			// bouton info de cet arbre et affichage numéro du prochain arbre
739
			this.lienArbreInfo( this.numArbre );
740
			$( '#arbre-nb' ).text( this.numArbre + 1 );
741
		}
742
		$( '.obs-nbre' ).text( this.obsNbre );
743
		$( '.obs-nbre' ).triggerHandler( 'changement' );
744
		//formatage des données
745
		var obsData = this.formaterFormObsData();
746
		this.afficherObs( obsData );
747
		this.stockerObsData( obsData );
748
		if ( this.isASL && 'arbres' === this.sujet ) {
749
			var arbreData = obsData.sujet;
750
			// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
751
			arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
752
			arbreData['id_observation']    = 0;
753
			this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
754
			this.releveDatas[this.obsNbre] = arbreData;
755
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
756
			this.modeArbresBasculerActivation( false );
757
		} else {
758
			this.reinitialiserForm();
759
		}
760
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
761
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
762
	} else {
763
		this.afficherPanneau( '#dialogue-form-invalide' );
764
	}
765
};
766
 
767
/**
768
 * Formatage des données du formulaire pour stockage et envoi
769
 */
770
WidgetsSaisiesCommun.prototype.formaterFormObsData = function() {
771
	var obsData      = { obsNum : this.obsNbre, sujet : {}},
772
		numNomSel    = $( '#taxon' ).data( 'numNomSel' ),
773
		nomSel       = $( '#taxon' ).val(),
774
		nomRet       = $( '#taxon' ).data( 'nomRet' ),
775
		numNomRet    = $( '#taxon' ).data( 'numNomRet' ),
776
		numTaxon     = $( '#taxon' ).data( 'nt' ),
777
		famille      = $( '#taxon' ).data( 'famille' ),
778
		referentiel  = ( this.valOk( numNomSel ) ) ? this.nomSciReferentiel : 'autre',
779
		certitude    = ( this.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
780
		imgB64       = [],
781
		imgNom       = [],
782
		date         = '',
783
		notes        = '',
784
		pays         = '',
785
		communeNom   = '',
786
		communeInsee = '',
787
		geometry     = '',
788
		latitude     = '',
789
		longitude    = '',
790
		altitude     = '',
791
		obsEtendue   = [];
792
 
793
	if( !this.isASL ) {
794
		notes            = $( '#notes' ).val().trim() || '';
795
		pays             = $( '#pays' ).val() || '';
796
		communeNom       = $( '#commune-nom' ).val();
797
		communeInsee     = $( '#commune-insee' ).val() || '';
798
		geometry         = $( '#geometry' ).val();
799
		latitude         = $( '#latitude' ).val();
800
		longitude        = $( '#longitude' ).val();
801
		altitude         = $( '#altitude' ).val();
802
		obsEtendue       = this.getObsChpSpecifiques();
803
		date             = this.fournirDate( $('#date_releve').val());
804
	} else {
805
		var miniatureImg = [];
806
		notes = $( '#commentaire' ).val() || '';
807
		if ( 'arbres' === this.sujet ) {
808
		// Dans ce cas cette fonction doit renvoyer des données au même format que l'input hidden "releve-data"
809
		// car les données dans stockerObsData provenir soit de cette fonction soit de l'input
810
			$( '.miniature-img' ).each( function() {
811
				if ( $( this ).hasClass( 'b64' ) ) {
812
					imgB64 = $( this ).attr( 'src' ) || '';
813
				} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
814
					imgB64 = $( this ).data( 'b64' ) || '';
815
				}
816
				miniatureImg.push({
817
					'nom' : $( this ).attr( 'alt' ),
818
					'src' : $( this ).attr( 'src' ),
819
					'b64' : imgB64
820
				});
821
			});
822
			obsData.sujet = {
823
				'num-arbre' : this.numArbre,
824
				taxon       : {
825
					'numNomSel' : numNomSel,
826
					'value'     : nomSel,
827
					'nomRet'    : nomRet,
828
					'numNomRet' : numNomRet,
829
					'nt'        : numTaxon,
830
					'famille'   : famille
831
				},
832
				'referentiel'      : referentiel,
833
				'certitude'        : certitude,
834
				'rue-arbres'       : ( $( '#rue-arbres' ).val() ) ? $('#rue-arbres').val() : '',
835
				'geometry-arbres'  : $( '#geometry-arbres' ).val(),
836
				'latitude-arbres'  : $( '#latitude-arbres' ).val(),
837
				'longitude-arbres' : $( '#longitude-arbres' ).val(),
838
				'altitude-arbres'  : $( '#altitude-arbres' ).val(),
839
				'circonference'    : $( '#circonference' ).val(),
840
				'com-arbres'       : ( $( '#com-arbres' ).val() ) ? $('#com-arbres').val() : '',
841
				'miniature-img'    : miniatureImg
842
			};
843
			obsData.releve = {
844
				'date'                  : this.fournirDate( $( '#releve-date' ).val() ),
845
				'rue'                   : $( '#rue' ).val(),
846
				'geometry-releve'       : $( '#geometry-releve' ).val(),
847
				'latitude-releve'       : $( '#latitude-releve' ).val(),
848
				'longitude-releve'      : $( '#longitude-releve' ).val(),
849
				'altitude-releve'       : $( '#altitude-releve' ).val(),
850
				'commune-nom'           : $( '#commune-nom' ).val(),
851
				'commune-insee'         : ( $( '#commune-insee' ).val() ) ? $('#commune-insee').val() : '',
852
				'pays'                  : ( $( '#pays' ).val() ) ? $('#pays').val() : '',
853
				'commentaires'          : notes
854
			};
855
			if ( 'tb_lichensgo' !== this.projet ) {
856
				obsData.sujet['surface-pied']          = $( '#surface-pied' ).val();
857
				obsData.sujet['equipement-pied-arbre'] = $( '#equipement-pied-arbre' ).val();
858
				obsData.sujet['tassement']             = $( '#tassement' ).val() || '';
859
				obsData.sujet['dejections']            = $( '#dejections input:checked' ).val() || '';
860
				obsData.releve['zone-pietonne']        = $( '#zone-pietonne input:checked' ).val();
861
				obsData.releve['pres-lampadaires']     = $( '#pres-lampadaires input:checked' ).val() || '';
862
			}
863
			if ( 'tb_streets' !== this.projet ) {
864
				var faceOmbre = [];
865
				$( '#face-ombre input' ).each( function() {
866
					if( $( this ).is( ':checked' ) ) {
867
						faceOmbre.push( $( this ).val() );
868
					}
869
				});
870
				obsData.sujet['face-ombre'] = faceOmbre;
871
			}
872
		} else {
873
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
874
			obsData.numArbre = $( '#choisir-arbre' ).val();
875
			pays             = this.releveDatas[0].pays || '';
876
			communeNom       = this.releveDatas[0]['commune-nom'];
877
			communeInsee     = this.releveDatas[0]['commune-insee'] || '';
878
			geometry         = this.releveDatas[obsData.numArbre]['geometry-arbres'];
879
			latitude         = this.releveDatas[obsData.numArbre]['latitude-arbres'];
880
			longitude        = this.releveDatas[obsData.numArbre]['longitude-arbres'];
881
			altitude         = this.releveDatas[obsData.numArbre]['altitude-arbres'];
882
			obsEtendue       = this.getObsChpSpecifiques( obsData.numArbre );
883
			date             = this.fournirDate( $( '#obs-date' ).val() );
884
		}
885
	}
886
	if ( !this.isASL || 'arbres' !== this.sujet ) {
887
		imgNom        = this.getNomsImgsOriginales();
888
		imgB64        = this.getB64ImgsOriginales();
889
 
890
		obsData.sujet = {
891
			'num_nom_sel'        : numNomSel,
892
			'nom_sel'            : nomSel,
893
			'nom_ret'            : nomRet,
894
			'num_nom_ret'        : numNomRet,
895
			'num_taxon'          : numTaxon,
896
			'famille'            : famille,
897
			'referentiel'        : referentiel,
898
			'certitude'          : certitude,
899
			'date'               : date,
900
			'notes'              : notes,
901
			'pays'               : pays,
902
			'commune_nom'        : communeNom,
903
			'commune_code_insee' : communeInsee,
904
			'geometry'           : geometry,
905
			'latitude'           : latitude,
906
			'longitude'          : longitude,
907
			'altitude'           : altitude,
908
			//Ajout des champs images
909
			'image_nom'          : imgNom,
910
			'image_b64'          : imgB64,
911
			// Ajout des champs étendus de l'obs
912
			'obs_etendue'        : obsEtendue
913
		};
914
		if ( !this.isASL ) {
915
			obsData.sujet['lieudit'] = $( '#lieudit' ).val() || '';
916
			obsData.sujet['station'] = $( '#station' ).val() || '';
917
			obsData.sujet['milieu']  = $( '#milieu' ).val() || '';
918
		}
919
	}
920
	return obsData;
921
};
922
 
923
/**
924
 * Affiche une observation dans la liste des observations à transmettre
925
 */
926
WidgetsSaisiesCommun.prototype.afficherObs = function( datasObs ) {
927
	// différences html liéees au responsive
928
	var responsivDiff1 = '',
929
		responsivDiff2 = '',
930
		responsivDiff3 = '',
931
		responsivDiff4 = '',
932
		responsivDiff5 = '',
933
		responsivDiff6 = '';
934
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
935
		/* La largeur minimum de l'affichage est 600 px inclus */
936
		responsivDiff1 = ' droite';
937
		responsivDiff2 = '<div></div>';
938
		responsivDiff3 = '<div class="row">';
939
		responsivDiff4 = ( !this.isASL ) ? ' col-md-2 col-sm-4' : ' col-md-4 col-sm-5';
940
		responsivDiff5 = ( !this.isASL ) ? ' class="col-md-9 col-sm-7"' : ' class="col-md-7 col-sm-6"';
941
		responsivDiff6 = '</div>';
942
	}
943
 
944
	var obsNum           = datasObs.obsNum,
945
		numNomSel        = datasObs.sujet['num_nom_sel'] || '',
946
		taxon            = '',
947
		miniatures       = '',
948
		notes            = '',
949
		commentaires     = '',
950
		date             = '',
951
		geometry         = '',
952
		latitude         = '',
953
		longitude        = '',
954
		coordonnees      = '',
955
		commune          = '',
956
		lieuObs          = '',
957
		inseeCommuneText = '',
958
		referentiel      = '',
959
		nn               = '',
960
		lieudit          = '',
961
		station          = '',
962
		milieu           = '',
963
		certitude        = '',
964
		numArbre         = '',
965
		obsArbre         = '';
966
 
967
	if ( !this.isASL ) {
968
		geometry     = datasObs.sujet['geometry'] || '';
969
		latitude     = datasObs.sujet['latitude'] || '';
970
		longitude    = datasObs.sujet['longitude'] || '';
971
		inseeCommune = datasObs.sujet['commune_code_insee'] || '';
972
		commune      = datasObs.sujet['commune_nom'] || '';
973
		if ( this.valOk( inseeCommune ) ) {
974
			inseeCommuneText = '(INSEE Commune:' + inseeCommune + ') ';
975
		}
976
		if ( this.valOk( numNomSel ) ) {
977
			referentiel = '<span class="referentiel-obs">' + '[' + datasObs.sujet['referentiel'] + ']' + '</span>';
978
		}
979
		if ( this.valOk( datasObs.sujet['lieudit'] ) ) {
980
			lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + datasObs.sujet['lieudit'] + ' ';
981
		}
982
		if ( this.valOk( datasObs.sujet['station'] ) ) {
983
			station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + datasObs.sujet['station'] + ' ';
984
		}
985
		if ( this.valOk( datasObs.sujet['milieu'] ) ) {
986
			milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + datasObs.sujet['milieu'] + ' ';
987
		}
988
		nn = this.ajouterNumNomSel( numNomSel );
989
	} else {
990
		certitude = ' [certitude : ' + datasObs.sujet.certitude + ']';
991
		if ( 'arbres' === this.sujet ) {
992
			numArbre   = datasObs.sujet['num-arbre'];
993
			numNomSel  = datasObs.sujet.taxon.numNomSel;
994
			taxon      = datasObs.sujet.taxon.value;
995
			miniatures = this.ajouterImgMiniatureAuTransfert(datasObs.sujet['miniature-img'] );
996
			notes      = datasObs.sujet['com-arbres'] || '';
997
			geometry   = datasObs.sujet['geometry-arbres'];
998
			latitude   = datasObs.sujet['latitude-arbres'];
999
			longitude  = datasObs.sujet['longitude-arbres'];
1000
			numArbre   = datasObs.sujet['num-arbre'];
1001
			// s'assurer que la date est au bon format
1002
			date       = this.fournirDate( datasObs.releve.date );
1003
			commune    = datasObs.releve['commune-nom'] || '';
1004
		} else {
1005
			numArbre   = datasObs.numArbre;
1006
		}
1007
		obsArbre = '<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>';
1008
	}
1009
	if ( !this.isASL || 'arbres' !== this.sujet ) {
1010
		taxon      = datasObs.sujet['nom_sel'];
1011
		miniatures = this.ajouterImgMiniatureAuTransfert();
1012
		notes      = datasObs.sujet['notes'] || '';
1013
		date       = this.fournirDate( datasObs.sujet.date );
1014
	}
1015
	if( !this.isASL || 'arbres' === this.sujet ) {
1016
		if ( this.valOk( commune ) ) {
1017
			lieuObs = ' '  + this.msgTraduction( 'lieu-obs' ) + ' ' + '<span class="commune">' + commune + '</span> ';
1018
		}
1019
		if ( this.valOk( latitude ) && this.valOk( longitude ) ) {
1020
			coordonnees = '[' + latitude + ' / ' + longitude + ']';
1021
		}
1022
	}
1023
	if ( this.valOk( notes ) ) {
1024
		commentaires =
1025
			this.msgTraduction( 'commentaires' ) +
1026
			' : <span>'+
1027
				notes +
1028
			'</span> ';
1029
	}
1030
	// html du bloc résumé de l'obs
1031
	$( '#liste-obs' ).prepend(
1032
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
1033
			'<div '+
1034
				'class="obs-action" '+
1035
				'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1036
			'>'+
1037
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.msgTraduction( 'obs-numero' ) + obsNum + '">'+
1038
				'<i class="far fa-trash-alt"></i>'+
1039
				'</button>'+
1040
				responsivDiff2 +
1041
			'</div> '+
1042
			responsivDiff3 +
1043
				'<div class="thumbnail' + responsivDiff4 + '">'+
1044
					miniatures +
1045
				'</div>'+
1046
				'<div' + responsivDiff5 + '>'+
1047
					'<ul class="unstyled">'+
1048
						'<li>'+
1049
							// isASL
1050
							obsArbre +
1051
							// toujours
1052
							'<span class="nom-sci">' + taxon + '</span> '+
1053
							// !isASL
1054
							nn +
1055
							referentiel +
1056
							// isASL
1057
							certitude +
1058
							// !this.isASL || 'arbres' === this.sujet
1059
							lieuObs +
1060
							// !isASL
1061
							inseeCommuneText +
1062
							// !this.isASL || 'arbres' === this.sujet
1063
							coordonnees +
1064
							// toujours
1065
							' ' + this.msgTraduction( 'obs-le' ) + ' '+
1066
							'<span class="date">' + date + '</span>'+
1067
						'</li>'+
1068
						'<li>'+
1069
							// !isASL
1070
							lieudit +
1071
							station +
1072
							milieu +
1073
						'</li>'+
1074
						'<li>'+
1075
							// this.valOk( notes )
1076
							commentaires +
1077
						'</li>'+
1078
					'</ul>'+
1079
				'</div>'+
1080
			responsivDiff6+
1081
		'</div>'
1082
	);
1083
 
1084
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1085
};
1086
 
1087
/**
1088
 * Ajoute une boîte de miniatures avec défilement des images,
1089
 * pour une obs de la liste des obs à transmettre
1090
 */
1091
WidgetsSaisiesCommun.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages = undefined ) {
1092
	const lthis = this;
1093
	var html         =
1094
			'<div class="defilement-miniatures">'+
1095
				'<figure class="centre">'+
1096
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1097
				'</figure>'+
1098
			'</div>',
1099
		miniatures   = '',
1100
		centre       = '',
1101
		defilVisible = '',
1102
		length       = 0;
1103
 
1104
	if ( this.valOk( chargerImages ) || this.valOk( $( '#miniatures img' ) ) ) {
1105
		if ( this.valOk( chargerImages ) ) {
1106
			$.each(  chargerImages, function( i, value ) {
1107
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
1108
 
1109
				var css        = ( lthis.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
1110
					src        = value.src,
1111
					alt        = value.nom,
1112
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1113
 
1114
				miniatures += miniature;
1115
			});
1116
			length = chargerImages.length;
1117
		} else {
1118
			var premiere     = true;
1119
			$( '#miniatures img' ).each( function() {
1120
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1121
				premiere = false;
1122
 
1123
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1124
					src        = $( this ).attr( 'src' ),
1125
					alt        = $( this ).attr( 'alt' ),
1126
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1127
 
1128
				miniatures += miniature;
1129
			});
1130
			length = $( '#miniatures img' ).length;
1131
		}
1132
		if ( 1 === length ) {
1133
			centre       = 'centre';
1134
			defilVisible = ' defilement-miniatures-cache';
1135
		}
1136
		html             =
1137
			'<div class="defilement-miniatures">'+
1138
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1139
				'<figure class="' + centre + '">'+
1140
					miniatures+
1141
				'</figure>'+
1142
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1143
			'</div>';
1144
	}
1145
 
1146
	return html;
1147
};
1148
 
1149
/**
1150
 * Construit le html à afficher pour le numNom
1151
 */
1152
WidgetsSaisiesCommun.prototype.ajouterNumNomSel = function( numNomSel ) {
1153
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1154
 
1155
	if ( !this.valOk( numNomSel ) ) {
1156
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1157
	}
1158
 
1159
	return nn;
1160
};
1161
 
1162
/**
1163
 * Stocke des données d'obs à envoyer à la bdd
1164
 */
1165
WidgetsSaisiesCommun.prototype.stockerObsData = function( obsDatas ) {
1166
	if ( this.isASL && 'arbres' === this.sujet ) {
1167
		// Dans ce cas la fonction formaterFormObsData renvoie des données au même format que l'input hidden "releve-data"
1168
		// car les données peuvent provenir soit de la formaterFormObsData soit de cet input
1169
		const lthis = this;
1170
		// si releve dupliqué on ne stocke pas l'image :
1171
		var stockerImg  = this.valOk( obsDatas.sujet['miniature-img'] ),
1172
			imgNom      = [],
1173
			imgB64      = [];
1174
 
1175
		// Si on a bien un 'miniature-img' dans les données
1176
		if( stockerImg ) {
1177
			$.each( obsDatas.sujet['miniature-img'], function( i, obj ) {
1178
				if( obj.hasOwnProperty( 'id' ) ) {
1179
					stockerImg = false;
1180
				}
1181
				return stockerImg;
1182
			});
1183
		}
1184
		// Si les miniatures ne sont pas déjà stockées (résultat de la loop précédente)
1185
		if( stockerImg ) {
1186
			$.each( obsDatas.sujet['miniature-img'] , function( i, obj ) {
1187
				if( lthis.valOk( obj.nom ) ) {
1188
					imgNom.push( obj.nom );
1189
				}
1190
				if( lthis.valOk( obj['b64'] ) ) {
1191
					imgB64.push( obj['b64'] );
1192
				}
1193
			});
1194
		} else {
1195
			imgNom = lthis.getNomsImgsOriginales();
1196
			imgB64 = lthis.getB64ImgsOriginales();
1197
		}
1198
		// Stockage en data des données d'obs à transmettre
1199
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, {
1200
			'num_nom_sel'        : obsDatas.sujet.taxon.numNomSel,
1201
			'nom_sel'            : obsDatas.sujet.taxon.value,
1202
			'nom_ret'            : obsDatas.sujet.taxon.nomRet,
1203
			'num_nom_ret'        : obsDatas.sujet.taxon.numNomRet,
1204
			'num_taxon'          : obsDatas.sujet.taxon.nt,
1205
			'famille'            : obsDatas.sujet.taxon.famille,
1206
			'referentiel'        : obsDatas.sujet.referentiel,
1207
			'certitude'          : obsDatas.sujet.certitude,
1208
			// La date provenant de input "releve-data" n'est pas au bon format
1209
			'date'               : this.fournirDate( obsDatas.releve.date ),
1210
			'notes'              : obsDatas.releve.commentaires.trim(),
1211
			'pays'               : obsDatas.releve.pays,
1212
			'commune_nom'        : obsDatas.releve['commune-nom'],
1213
			'commune_code_insee' : obsDatas.releve['commune-insee'],
1214
			'geometry'           : obsDatas.sujet['geometry-arbres'],
1215
			'latitude'           : obsDatas.sujet['latitude-arbres'],
1216
			'longitude'          : obsDatas.sujet['longitude-arbres'],
1217
			'altitude'           : obsDatas.sujet['altitude-arbres'],
1218
			'image_nom'          : imgNom,
1219
			'image_b64'          : imgB64,
1220
			// Ajout des champs étendus de l'obs
1221
			'obs_etendue'        : lthis.getObsChpSpecifiques( obsDatas )
1222
		});
1223
	} else {
1224
		// Stockage en data des données d'obs à transmettre
1225
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, obsDatas.sujet );
1226
	}
1227
};
1228
 
1229
WidgetsSaisiesCommun.prototype.getNomsImgsOriginales = function() {
1230
	var noms = new Array();
1231
 
1232
	$( '.miniature-img' ).each( function() {
1233
		noms.push( $( this ).attr( 'alt' ) );
1234
	});
1235
 
1236
	return noms;
1237
};
1238
 
1239
WidgetsSaisiesCommun.prototype.getB64ImgsOriginales = function() {
1240
	var b64 = new Array();
1241
 
1242
	$( '.miniature-img' ).each( function() {
1243
		if ( $( this ).hasClass( 'b64' ) ) {
1244
			b64.push( $( this ).attr( 'src' ) );
1245
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1246
			b64.push( $( this ).data( 'b64' ) );
1247
		}
1248
	});
1249
 
1250
	return b64;
1251
};
1252
 
1253
/**
1254
 * Efface toutes les miniatures (formulaire)
1255
 */
1256
WidgetsSaisiesCommun.prototype.supprimerMiniatures = function() {
1257
	if ( !this.isASL ) {
1258
		// Déconnection MutationObserver miniatures
1259
		// Sinon on a une erreur avant la création d'une nouvelle obs
1260
		this.observer.disconnect();
1261
		$( '#miniatures' ).empty();
1262
		// Validation miniatures reprend à 0 pour une nouvelle obs
1263
		this.surPresenceAbsenceMiniature();
1264
	} else {
1265
		$( '#miniatures' ).empty();
1266
	}
1267
	$( '#miniature-msg' ).empty();
1268
};
1269
 
1270
WidgetsSaisiesCommun.prototype.surChangementNbreObs = function() {
1271
	if ( 0 === this.obsNbre ) {
1272
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1273
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1274
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1275
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1276
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1277
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1278
	}
1279
	if ( this.isASL && 'arbres' === this.sujet ) {
1280
		if ( 0 <= this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1281
			$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1282
		} else {
1283
			$( '#bloc-form-arbres' ).addClass( 'hidden' );
1284
		}
1285
	}
1286
};
1287
 
1288
WidgetsSaisiesCommun.prototype.defilerMiniatures = function( element ) {
1289
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1290
 
1291
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1292
	miniatureSelectionne.addClass( 'miniature-cachee' );
1293
 
1294
	var miniatureAffichee     = miniatureSelectionne;
1295
 
1296
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1297
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1298
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1299
		} else {
1300
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1301
		}
1302
	} else {
1303
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1304
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1305
		} else {
1306
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1307
		}
1308
	}
1309
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1310
	miniatureAffichee.removeClass( 'miniature-cachee' );
1311
};
1312
 
1313
WidgetsSaisiesCommun.prototype.supprimerObs = function( selector ) {
1314
	var obsId = $( selector ).val();
1315
 
1316
	// Problème avec IE 6 et 7
1317
	if ( 'Supprimer' === obsId ) {
1318
		obsId = $( selector ).attr( 'title' );
1319
	}
1320
	this.supprimerObsParId( obsId );
1321
};
1322
 
1323
/**
1324
 * Supprime l'obs et les data de l'obs
1325
 * et remonte les suivantes d'un cran
1326
 */
1327
WidgetsSaisiesCommun.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1328
	if ( this.isASL && 'arbres' === this.sujet ) {
1329
		if ( !transmission ) {
1330
			this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1331
			this.releveData.splice( obsId , 1 );
1332
			$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1333
		}
1334
		$( '#arbre-info-' + ( this.numArbre ) ).remove();
1335
		$( '#arbre-nb' ).text( this.numArbre );
1336
		this.numArbre -= 1;
1337
		if ( 1 > this.numArbre ) {
1338
			$( '#bloc-info-arbres-title' ).addClass( 'hidden' );
1339
		}
1340
 
1341
		var arbreExId   = 0,
1342
			arbreId     = 0;
1343
	}
1344
	this.obsNbre  -= 1;
1345
	$( '.obs-nbre' ).text( this.obsNbre );
1346
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1347
	$( '.obs' + obsId ).remove();
1348
	obsId = parseInt(obsId);
1349
 
1350
	if ( !transmission ) {
1351
		var listObsData = $( '#liste-obs' ).data(),
1352
			exId        = 0,
1353
			indexObs    = '',
1354
			exIndexObs  = '';
1355
 
1356
		for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1357
			exId       = parseInt(id) + 1;
1358
			indexObs   = 'obsId' + id;
1359
			exIndexObs = 'obsId' + exId;
1360
			$( '#liste-obs' ).removeData( indexObs );
1361
			$( '#obs' + exId )
1362
				.attr( 'id', 'obs' + id )
1363
				.removeClass( 'obs' + exId )
1364
				.addClass( 'obs' + id )
1365
				.find( '.supprimer-obs' )
1366
					.attr( 'title', 'Observation n°' + id )
1367
					.val( id );
1368
 
1369
			if ( this.isASL && 'arbres' === this.sujet ) {
1370
				arbreExId = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1371
				arbreId   = arbreExId - 1;
1372
				$( '#obs-arbre-' + arbreExId )
1373
					.attr( 'id', 'obs-arbre-' + arbreId )
1374
					.attr( 'data-arbre', arbreId )
1375
					.data( 'arbre', arbreId )
1376
					.text( 'Arbre ' + arbreId );
1377
				// modification du numero d'arbre dans les obs étendues
1378
				if ( this.valOk( listObsData[exIndexObs] ) ) {
1379
					$.each( listObsData[exIndexObs].obs_etendue, function( i, obsE ) {
1380
						if ('num_arbre' === obsE.cle ) {
1381
							listObsData[exIndexObs].obs_etendue[i].valeur = arbreId;
1382
							return false;
1383
						}
1384
					});
1385
				}
1386
			}
1387
 
1388
			// Mise à jour des données à transmettre
1389
			if ( this.valOk( listObsData[exIndexObs] ) ) {
1390
				$( '#liste-obs' ).data( indexObs, listObsData[exIndexObs] );
1391
			}
1392
			if ( parseInt( id ) !== this.obsNbre ) {
1393
				id = parseInt(id);
1394
			}
1395
		}
1396
	} else {
1397
		$( '#liste-obs' ).removeData( 'obsId' + obsId );
1398
	}
1399
};
1400
 
1401
WidgetsSaisiesCommun.prototype.transmettreObs = function() {
1402
	const lthis = this;
1403
	var observations = $( '#liste-obs' ).data();
1404
 
1405
	if ( this.debug ) {
1406
		console.dir( observations );
1407
	}
1408
	if ( !this.valOk( typeof observations, true, 'object' ) ) {
1409
		this.afficherPanneau( '#dialogue-zero-obs' );
1410
	} else {
1411
		this.nbObsEnCours         = 1;
1412
		this.nbObsTransmises      = 0;
1413
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1414
			return i;
1415
		}).length;
1416
		this.depilerObsPourEnvoi();
1417
	}
1418
 
1419
	return false;
1420
};
1421
 
1422
WidgetsSaisiesCommun.prototype.depilerObsPourEnvoi = function() {
1423
	var observations = $( '#liste-obs' ).data();
1424
	// la boucle est factice car on utilise un tableau
1425
	// dont on a besoin de n'extraire que le premier élément
1426
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1427
	// TODO: utiliser var.keys quand ça sera plus répandu
1428
	// ou bien utiliser un vrai tableau et pas un objet
1429
	for ( var obsNum in observations ) {
1430
		var obsATransmettre = {
1431
			'id_projet' : this.idProjet,
1432
			'projet'    : this.projet,
1433
			'tag-obs'   : this.tagObs,
1434
			'tag-img'   : this.tagImg
1435
		};
1436
		var utilisateur = {
1437
			id_utilisateur : $( '#id_utilisateur' ).val(),
1438
			prenom         : $( '#prenom' ).val(),
1439
			nom            : $( '#nom' ).val(),
1440
			courriel       : $( '#courriel' ).val()
1441
		};
1442
 
1443
		obsATransmettre['utilisateur'] = utilisateur;
1444
		obsATransmettre[obsNum]        = observations[obsNum];
1445
 
1446
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1447
 
1448
		if( '' !== idObsNumerique ) {
1449
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1450
		}
1451
		break;
1452
	}
1453
};
1454
 
1455
WidgetsSaisiesCommun.prototype.envoyerObsAuCel = function( idObs, observation ) {
1456
	const lthis = this;
1457
 
1458
	var erreurMsg = '';
1459
 
1460
	$.ajax({
1461
		url        : lthis.serviceSaisieUrl,
1462
		type       : 'POST',
1463
		data       : observation,
1464
		dataType   : 'json',
1465
		beforeSend : function() {
1466
			$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1467
			$( '.alert-txt' ).empty();
1468
			$( '.alert-txt .msg-erreur,.alert-txt .msg-debug' ).remove();
1469
			$( '#chargement' ).removeClass( 'hidden' );
1470
		},
1471
		success    : function( transfertDatas, textStatus, jqXHR ) {
1472
			if( lthis.isASL && 'arbres' === lthis.sujet ) {
1473
				// actualisation de id_observation dans '#releve-data'
1474
				lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1475
			}
1476
			// mise à jour du nombre d'obs à transmettre
1477
			// et suppression de l'obs
1478
			lthis.supprimerObsParId( idObs, true );
1479
			lthis.nbObsEnCours++;
1480
			// mise à jour du statut
1481
			lthis.mettreAJourProgression();
1482
			if( 0 < lthis.obsNbre ) {
1483
				// dépilement de la suivante
1484
				lthis.depilerObsPourEnvoi();
1485
			}
1486
		},
1487
		statusCode  : {
1488
			500 : function( jqXHR, textStatus, errorThrown ) {
1489
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1490
				}
1491
		},
1492
		error        : function( jqXHR, textStatus, errorThrown ) {
1493
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1494
			try {
1495
				reponse = jQuery.parseJSON( jqXHR.responseText );
1496
				if ( null !== reponse ) {
1497
					$.each( reponse, function( cle, valeur ) {
1498
						erreurMsg += valeur + '\n';
1499
					});
1500
				}
1501
			} catch( e ) {
1502
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1503
			}
1504
		},
1505
		complete      : function( jqXHR, textStatus ) {
1506
			var debugMsg = lthis.extraireEnteteDebug( jqXHR );
1507
 
1508
			if ( '' !== erreurMsg ) {
1509
				if ( lthis.debug ) {
1510
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1511
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1512
				}
1513
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1514
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagsMotsCles+
1515
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1516
 
1517
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1518
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1519
					$( '#tpl-transmission-ko' ).clone()
1520
						.find( '.courriel-erreur' )
1521
						.attr( 'href', hrefCourriel )
1522
						.end()
1523
						.html()
1524
				);
1525
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1526
				$( '#chargement' ).addClass( 'hidden' );
1527
				lthis.initialiserBarreProgression;
1528
			} else {
1529
				if ( lthis.debug ) {
1530
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1531
				}
1532
				if( 0 === lthis.obsNbre ) {
1533
					setTimeout( function() {
1534
						if ( lthis.isASL ) {
1535
							if ( 'arbres' === lthis.sujet ) {
1536
								if ( 'tb_streets' !== lthis.projet ) {
1537
									$( '#bouton-saisir-lichens' ).removeClass( 'hidden' );
1538
								}
1539
								if ( 'tb_lichensgo' !== lthis.projet ) {
1540
									$( '#bouton-saisir-plantes' ).removeClass( 'hidden' );
1541
								}
1542
							} else {
1543
								$( '#bouton-poursuivre' ).removeClass( 'hidden' );
1544
							}
1545
							$( '#bloc-controle-liste-obs,#bloc-gauche' ).addClass( 'hidden' );
1546
						}
1547
						$( '#chargement' ).addClass( 'hidden' );
1548
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1549
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1550
					}, 1500 );
1551
				}
1552
			}
1553
		}
1554
	});
1555
};
1556
 
1557
WidgetsSaisiesCommun.prototype.mettreAJourProgression = function() {
1558
	this.nbObsTransmises++;
1559
 
1560
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1561
 
1562
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1563
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1564
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1565
	if( 0 === this.obsNbre ) {
1566
		$( '.progress' ).removeClass( 'active' );
1567
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1568
	}
1569
};
1570
 
1571
WidgetsSaisiesCommun.prototype.initialiserBarreProgression = function() {
1572
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1573
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1574
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1575
	$( '.progress' ).addClass( 'active' );
1576
	$( '.progress' ).addClass( 'progress-bar-striped' );
1577
};
1578
 
1579
// Form Validator *************************************************************/
1580
WidgetsSaisiesCommun.prototype.configurerFormValidator = function() {
1581
	const lthis = this;
1582
 
1583
	$.validator.addMethod(
1584
		'dateCel',
1585
		function ( value, element ) {
1586
			return ( lthis.valOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
1587
		},
1588
		lthis.msgTraduction( 'date-incomplete' )
1589
	);
1590
	$.validator.addMethod(
1591
		'userEmailOk',
1592
		function ( value, element ) {
1593
			return ( lthis.valOk( value ) );
1594
		},
1595
		''
1596
	);
1597
	$.validator.addMethod(
1598
		'minMaxOk',
1599
		function ( value, element, param ) {
1600
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1601
			return lthis.validerMinMax( element ).cond;
1602
		},
1603
		$.validator.messages.minMaxOk
1604
	);
1605
	$.validator.addMethod(
1606
		'listFields',
1607
		function ( value, element ) {
1608
			return ( lthis.valOk( value ) );
1609
		},
1610
		''
1611
	);
1612
	$.extend( $.validator.defaults, {
1613
		errorElement: 'span',
1614
		errorPlacement: function( error, element ) {
1615
			if ( lthis.isASL && 'arbres' === lthis.sujet && ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) ) {
1616
				error.appendTo( element.closest( '.list' ) );
1617
			} else {
1618
				element.after( error );
1619
			}
1620
		},
1621
		onfocusout: function( element ) {
1622
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1623
				if ( $( element ).valid() ) {
1624
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1625
				} else {
1626
					$( element ).closest( '.control-group' ).addClass( 'error' );
1627
				}
1628
			}
1629
		},
1630
		onkeyup : function( element ) {
1631
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1632
				if ( $( element ).valid() ) {
1633
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1634
				} else {
1635
					$( element ).closest( '.control-group' ).addClass( 'error' );
1636
				}
1637
			}
1638
		},
1639
		unhighlight: function( element ) {
1640
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1641
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1642
			}
1643
		},
1644
		highlight: function( element ) {
1645
			$( element ).closest( '.control-group' ).addClass( 'error' );
1646
		}
1647
	});
1648
};
1649
 
1650
// Formatage date *************************************************************/
1651
WidgetsSaisiesCommun.prototype.fournirDate = function( dateObs ) {
1652
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1653
		return dateObs;
1654
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1655
		var dateArray = dateObs.split( '-' );
1656
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1657
	} else {
1658
		console.dir( 'erreur date : ' + dateObs )
1659
	}
1660
};
1661
 
1662
// scroll vers le formulaire
1663
WidgetsSaisiesCommun.prototype.scrollFormTop = function( scrollSelecteur, focus = '' ) {
1664
	const lthis = this;
1665
 
1666
	$( 'html, body' ).stop().animate({
1667
		scrollTop: $( scrollSelecteur ).offset().top
1668
	}, 300, function() {
1669
		if ( lthis.valOk( focus ) ) {
1670
			$( focus ).focus();
1671
		} else {
1672
			return;
1673
		}
1674
	});
1675
};
1676
 
1677
// Controle des panneaux d'infos **********************************************/
1678
 
1679
WidgetsSaisiesCommun.prototype.afficherPanneau = function( selecteur ) {
1680
	$( selecteur )
1681
		.removeClass( 'hidden' )
1682
		.hide()
1683
		.show( 600 )
1684
		.delay( this.dureeMessage )
1685
		.hide( 600 );
1686
	this.scrollFormTop( selecteur );
1687
};
1688
 
1689
WidgetsSaisiesCommun.prototype.masquerPanneau = function( selecteur ) {
1690
	$( selecteur ).addClass( 'hidden' );
1691
};
1692
 
1693
WidgetsSaisiesCommun.prototype.fermerPanneauAlert = function() {
1694
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1695
};
1696
 
1697
/**
1698
 * Si la langue est définie dans this.langue, et si des messages sont définis
1699
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1700
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1701
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1702
 */
1703
WidgetsSaisiesCommun.prototype.msgTraduction = function( cle ) {
1704
	var msg = 'N/A';
1705
 
1706
	if ( this.msgs ) {
1707
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1708
			msg = this.msgs[this.langue][cle];
1709
		} else if ( cle in this.msgs['fr'] ) {
1710
			msg = this.msgs['fr'][cle];
1711
		}
1712
	}
1713
	return msg;
1714
};
1715
 
1716
/**
1717
* Stope l'évènement courant quand on clique sur un lien.
1718
* Utile pour Chrome, Safari...
1719
*/
1720
WidgetsSaisiesCommun.prototype.arreter = function( event ) {
1721
	if ( event.stopPropagation ) {
1722
		event.stopPropagation();
1723
	}
1724
	if ( event.preventDefault ) {
1725
		event.preventDefault();
1726
	}
1727
 
1728
	return false;
1729
};
1730
 
1731
/**
1732
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1733
 * @param jqXHR
1734
 * @returns {String}
1735
 */
1736
WidgetsSaisiesCommun.prototype.extraireEnteteDebug = function( jqXHR ) {
1737
	var msgDebug = '';
1738
 
1739
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1740
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1741
		if ( null !== debugInfos ) {
1742
			$.each( debugInfos, function( cle, valeur ) {
1743
				msgDebug += valeur + '\n';
1744
			});
1745
		}
1746
	}
1747
 
1748
	return msgDebug;
1749
};
1750
 
1751
 
1752
WidgetsSaisiesCommun.prototype.confirmerSortie = function() {
1753
	$( window ).off( 'beforeunload' ).on( 'beforeunload', function( event ) {
1754
		if ( !event ) {
1755
			event = window.event;
1756
		}
1757
		return false;
1758
	});
1759
};
1760
 
1761
WidgetsSaisiesCommun.prototype.valOk = function ( valeur, sensComparaison = true, comparer = undefined ) {
1762
	return utils.valOk( valeur, sensComparaison, comparer );
1763
};
1764
 
1765
WidgetsSaisiesCommun.prototype.activerModale = function ( label, content = '', buttons = [] ) {
1766
	return utils.activerModale( label, content, buttons );
1767
};
1768
 
1769
// Lib hors objet
1770
 
1771
/*
1772
 * jQuery UI Autocomplete HTML Extension
1773
 *
1774
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1775
 * Dual licensed under the MIT or GPL Version 2 licenses.
1776
 *
1777
 * http://github.com/scottgonzalez/jquery-ui-extensions
1778
 *
1779
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1780
 */
1781
( function( $ ) {
1782
	var proto      = $.ui.autocomplete.prototype,
1783
		initSource = proto._initSource;
1784
 
1785
	WidgetsSaisiesCommun.prototype.filter = function( array, term ) {
1786
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1787
 
1788
		return $.grep( array, function( value ) {
1789
 
1790
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1791
		});
1792
	}
1793
	$.extend( proto, {
1794
		_initSource: function() {
1795
			if ( this.options.html && $.isArray( this.options.source ) ) {
1796
				this.source = function( request, response ) {
1797
					response( filter( this.options.source, request.term ) );
1798
				};
1799
			} else {
1800
				initSource.call( this );
1801
			}
1802
		},
1803
		_renderItem: function( ul, item) {
1804
			if ( item.retenu ) {
1805
				item.label = '<strong>' + item.label + '</strong>';
1806
			}
1807
 
1808
			return $( '<li></li>' )
1809
				.data( 'item.autocomplete', item )
1810
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1811
				.appendTo( ul );
1812
		}
1813
	});
1814
})( jQuery );