Subversion Repositories eFlore/Applications.cel

Rev

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