Subversion Repositories eFlore/Applications.cel

Rev

Rev 3432 | Rev 3434 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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