Subversion Repositories eFlore/Applications.cel

Rev

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

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