Subversion Repositories eFlore/Applications.cel

Rev

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