Subversion Repositories eFlore/Applications.cel

Rev

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