Subversion Repositories eFlore/Applications.cel

Rev

Rev 3428 | Rev 3433 | 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 ) {
553
	if ( this.debug ) {
554
		var debogage = $( 'debogage', reponse ).text();
555
	}
556
 
557
	var message = $( 'message', reponse ).text();
558
 
559
	if ( this.valOk( message ) ) {
560
		$( '#miniature-msg' ).append( message );
561
	} else {
562
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
563
	}
564
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
565
};
566
 
567
/**
568
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
569
 */
570
WidgetsSaisiesCommun.prototype.creerWidgetMiniature = function( reponse ) {
571
	var miniatureUrl = $( 'miniature-url', reponse ).text();
3427 idir 572
	var imgNom       = $( 'image-nom', reponse ).text();
3425 idir 573
	var html =
3427 idir 574
		'<div class="miniature mr-3">'+
575
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '" style="min-height:100%;"/>'+
576
			'<a class="effacer-miniature">Supprimer</a>'+
3425 idir 577
		'</div>';
578
 
579
	return html;
580
};
581
 
582
/**
583
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
584
 */
585
WidgetsSaisiesCommun.prototype.verifierFormat = function( cheminTmp ) {
586
	var parts     = cheminTmp.split( '.' ),
587
		extension = parts[ parts.length - 1 ];
588
 
589
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
590
};
591
 
592
/**
593
 * Check les miniatures déjà téléchargées
594
 * renvoie false si le même nom est rencontré 2 fois
595
 * renvoie true sinon
596
 */
597
WidgetsSaisiesCommun.prototype.verifierDuplication = function( cheminTmp ) {
598
	const lthis = this;
599
 
600
	var parts        = cheminTmp.split( '\\' ),
601
		nomImage     = parts[ parts.length - 1 ],
602
		thisSrcParts = [],
603
		thisNomImage = '',
604
		nonDupliquee = true;
605
 
606
	$( 'img.miniature-img,img.miniature' ).each( function() {
607
		// vérification avec alt de l'image
608
		if ( lthis.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
609
			nonDupliquee = false;
610
			return false;// Pas besoin de poursuivre la boucle
611
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
612
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
613
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
614
			if ( lthis.valOk ( thisNomImage, true, nomImage ) ) {
615
				nonDupliquee = false;
616
				return false;
617
			}
618
		}
619
	});
620
	return nonDupliquee;
621
};
622
 
623
/**
624
 * Efface une miniature (formulaire)
625
 */
626
WidgetsSaisiesCommun.prototype.supprimerMiniature = function( miniature ) {
627
	miniature.parents( '.miniature' ).remove();
628
};
629
 
630
// Geoloc *********************************************************************/
631
WidgetsSaisiesCommun.prototype.transfererCarto = function( donnees ) {
632
	var typeLocalisation = donnees.typeLocalisation || 'point',
633
		isPoint          = ( typeLocalisation === 'point' ).toString(),
634
		suffixe          = ( this.valOk( donnees.suffixe ) ) ? '-' + donnees.suffixe : '',
635
		$cartoRemplacee  = donnees.cartoRemplacee || $( '#tb-geolocation' ),
636
		layer            = donnees.layer || 'osm',
637
		latitude         = donnees.latitude || '46.5',
638
		longitude        = donnees.longitude || '2.9',
639
		// 18 est le zoom max
640
		zoomInit         = donnees.zoomInit || 18;
641
 
642
	$cartoRemplacee.remove();
643
	$( '#geoloc' + suffixe ).append(
644
		'<tb-geolocation-element'+
645
			' id="tb-geolocation' + suffixe +'"'+
646
			' layer="' + layer + '"'+
647
			' zoom_init="' + zoomInit + '"'+
648
			' lat_init="' + latitude + '"'+
649
			' lng_init="' + longitude + '"'+
650
			' marker="' + isPoint + '"'+
651
			' polyline="' + !isPoint + '"'+
652
			' polygon="false"'+
653
			' show_lat_lng_elevation_inputs="' + isPoint + '"'+
654
			' osm_class_filter=""'+
655
			' elevation_provider="mapquest"'+
656
			' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
657
		'>'+
658
		'</tb-geolocation-element>'
659
	);
660
	this.initEvtsGeoloc( true );
661
};
662
 
663
// Ajouter Obs ****************************************************************/
664
/**
665
 * Ajoute une observation à la liste des obs à transmettre
666
 * (résumé obs)
667
 */
668
WidgetsSaisiesCommun.prototype.ajouterObs = function() {
669
	if ( this.isASL ) {
3426 idir 670
		this.scrollFormTop( '#zone-' + this.sujet );
3425 idir 671
	}
672
	// Fermeture automatique des dialogue de transmission de données
673
	// @WARNING TEST
674
	$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
675
	if ( this.validerForm() ) {
676
		this.masquerPanneau( '#dialogue-form-invalide' );
677
		this.obsNbre += 1;
678
		if ( this.isASL && 'arbres' === this.sujet ) {
679
			this.numArbre += 1;
680
			// bouton info de cet arbre et affichage numéro du prochain arbre
681
			this.lienArbreInfo( this.numArbre );
682
			$( '#arbre-nb' ).text( this.numArbre + 1 );
683
		}
684
		$( '.obs-nbre' ).text( this.obsNbre );
685
		$( '.obs-nbre' ).triggerHandler( 'changement' );
686
		//formatage des données
687
		var obsData = this.formaterFormObsData();
688
		this.afficherObs( obsData );
689
		this.stockerObsData( obsData );
690
		if ( this.isASL && 'arbres' === this.sujet ) {
691
			var arbreData = obsData.sujet;
692
			// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
693
			arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
694
			arbreData['id_observation']    = 0;
695
			this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
696
			this.releveDatas[this.obsNbre] = arbreData;
697
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
698
			this.modeArbresBasculerActivation( false );
699
		} else {
700
			this.reinitialiserForm();
701
		}
702
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
703
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
704
	} else {
705
		this.afficherPanneau( '#dialogue-form-invalide' );
706
	}
707
};
708
 
709
/**
710
 * Formatage des données du formulaire pour stockage et envoi
711
 */
712
WidgetsSaisiesCommun.prototype.formaterFormObsData = function() {
713
	var obsData      = { obsNum : this.obsNbre, sujet : {}},
714
		numNomSel    = $( '#taxon' ).data( 'numNomSel' ),
715
		nomSel       = $( '#taxon' ).val(),
716
		nomRet       = $( '#taxon' ).data( 'nomRet' ),
717
		numNomRet    = $( '#taxon' ).data( 'numNomRet' ),
718
		numTaxon     = $( '#taxon' ).data( 'nt' ),
719
		famille      = $( '#taxon' ).data( 'famille' ),
720
		referentiel  = ( this.valOk( numNomSel ) ) ? this.nomSciReferentiel : 'autre',
721
		certitude    = ( this.valOk( numNomSel ) ) ? $( '#certitude' ).val() : 'à determiner',
722
		imgB64       = [],
723
		imgNom       = [],
724
		date         = '',
725
		notes        = '',
726
		pays         = '',
727
		communeNom   = '',
728
		communeInsee = '',
729
		latitude     = '',
730
		longitude    = '',
731
		altitude     = '',
732
		obsEtendue   = [];
733
 
734
	if( !this.isASL ) {
735
		notes            = $( '#notes' ).val().trim() || '';
736
		pays             = $( '#pays' ).val() || '';
737
		communeNom       = $( '#commune-nom' ).val();
738
		communeInsee     = $( '#commune-insee' ).val() || '';
739
		latitude         = $( '#latitude' ).val();
740
		longitude        = $( '#longitude' ).val();
741
		altitude         = $( '#altitude' ).val();
742
		obsEtendue       = this.getObsChpSpecifiques();
3426 idir 743
		date             = this.fournirDate( $('#date_releve').val());
3425 idir 744
	} else {
745
		var miniatureImg = [];
746
		notes = $( '#commentaire' ).val() || '';
747
		if ( 'arbres' === this.sujet ) {
748
		// Dans ce cas cette fonction doit renvoyer des données au même format que l'input hidden "releve-data"
749
		// car les données dans stockerObsData provenir soit de cette fonction soit de l'input
750
			$( '.miniature-img' ).each( function() {
751
				if ( $( this ).hasClass( 'b64' ) ) {
752
					imgB64 = $( this ).attr( 'src' ) || '';
753
				} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
754
					imgB64 = $( this ).data( 'b64' ) || '';
755
				}
756
				miniatureImg.push({
757
					'nom' : $( this ).attr( 'alt' ),
758
					'src' : $( this ).attr( 'src' ),
759
					'b64' : imgB64
760
				});
761
			});
762
			obsData.sujet = {
763
				'num-arbre' : this.numArbre,
764
				taxon       : {
765
					'numNomSel' : numNomSel,
766
					'value'     : nomSel,
767
					'nomRet'    : nomRet,
768
					'numNomRet' : numNomRet,
769
					'nt'        : numTaxon,
770
					'famille'   : famille
771
				},
772
				'referentiel'      : referentiel,
773
				'certitude'        : certitude,
774
				'rue-arbres'       : ( $( '#rue-arbres' ).val() ) ? $('#rue-arbres').val() : '',
775
				'latitude-arbres'  : $( '#latitude-arbres' ).val(),
776
				'longitude-arbres' : $( '#longitude-arbres' ).val(),
777
				'altitude-arbres'  : $( '#altitude-arbres' ).val(),
778
				'circonference'    : $( '#circonference' ).val(),
779
				'com-arbres'       : ( $( '#com-arbres' ).val() ) ? $('#com-arbres').val() : '',
780
				'miniature-img'    : miniatureImg
781
			};
782
			obsData.releve = {
783
				'date'                  : this.fournirDate( $( '#releve-date' ).val() ),
784
				'rue'                   : $( '#rue' ).val(),
785
				'latitude-releve'       : $( '#latitude-releve' ).val(),
786
				'longitude-releve'      : $( '#longitude-releve' ).val(),
787
				'altitude-releve'       : $( '#altitude-releve' ).val(),
788
				'commune-nom'           : $( '#commune-nom' ).val(),
789
				'commune-insee'         : ( $( '#commune-insee' ).val() ) ? $('#commune-insee').val() : '',
790
				'pays'                  : ( $( '#pays' ).val() ) ? $('#pays').val() : '',
791
				'commentaires'          : notes
792
			};
793
			if ( 'tb_lichensgo' !== this.module ) {
794
				obsData.sujet['surface-pied']          = $( '#surface-pied' ).val();
795
				obsData.sujet['equipement-pied-arbre'] = $( '#equipement-pied-arbre' ).val();
796
				obsData.sujet['tassement']             = $( '#tassement' ).val() || '';
797
				obsData.sujet['dejections']            = $( '#dejections input:checked' ).val() || '';
798
				obsData.releve['zone-pietonne']        = $( '#zone-pietonne input:checked' ).val();
799
				obsData.releve['pres-lampadaires']     = $( '#pres-lampadaires input:checked' ).val() || '';
800
			}
801
			if ( 'tb_streets' !== this.module ) {
802
				var faceOmbre = [];
803
				$( '#face-ombre input' ).each( function() {
804
					if( $( this ).is( ':checked' ) ) {
805
						faceOmbre.push( $( this ).val() );
806
					}
807
				});
808
				obsData.sujet['face-ombre'] = faceOmbre;
809
			}
810
		} else {
811
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
812
			obsData.numArbre = $( '#choisir-arbre' ).val();
813
			pays             = this.releveDatas[0].pays || '';
814
			communeNom       = this.releveDatas[0]['commune-nom'];
815
			communeInsee     = this.releveDatas[0]['commune-insee'] || '';
816
			latitude         = this.releveDatas[obsData.numArbre]['latitude-arbres'];
817
			longitude        = this.releveDatas[obsData.numArbre]['longitude-arbres'];
818
			altitude         = this.releveDatas[obsData.numArbre]['altitude-arbres'];
819
			obsEtendue       = this.getObsChpSpecifiques( obsData.numArbre );
3426 idir 820
			date             = this.fournirDate( $( '#obs-date' ).val() );
3425 idir 821
		}
822
	}
823
	if ( !this.isASL || 'arbres' !== this.sujet ) {
824
		imgNom        = this.getNomsImgsOriginales();
825
		imgB64        = this.getB64ImgsOriginales();
826
 
827
		obsData.sujet = {
828
			'num_nom_sel'        : numNomSel,
829
			'nom_sel'            : nomSel,
830
			'nom_ret'            : nomRet,
831
			'num_nom_ret'        : numNomRet,
832
			'num_taxon'          : numTaxon,
833
			'famille'            : famille,
834
			'referentiel'        : referentiel,
835
			'certitude'          : certitude,
836
			'date'               : date,
837
			'notes'              : notes,
838
			'pays'               : pays,
839
			'commune_nom'        : communeNom,
840
			'commune_code_insee' : communeInsee,
841
			'latitude'           : latitude,
842
			'longitude'          : longitude,
843
			'altitude'           : altitude,
844
			//Ajout des champs images
845
			'image_nom'          : imgNom,
846
			'image_b64'          : imgB64,
847
			// Ajout des champs étendus de l'obs
848
			'obs_etendue'        : obsEtendue
849
		};
850
		if ( !this.isASL ) {
851
			obsData.sujet['lieudit'] = $( '#lieudit' ).val() || '';
852
			obsData.sujet['station'] = $( '#station' ).val() || '';
853
			obsData.sujet['milieu']  = $( '#milieu' ).val() || '';
854
		}
855
	}
856
	return obsData;
857
};
858
 
859
/**
860
 * Affiche une observation dans la liste des observations à transmettre
861
 */
862
WidgetsSaisiesCommun.prototype.afficherObs = function( datasObs ) {
863
	// différences html liéees au responsive
864
	var responsivDiff1 = '',
865
		responsivDiff2 = '',
866
		responsivDiff3 = '',
867
		responsivDiff4 = '',
868
		responsivDiff5 = '',
869
		responsivDiff6 = '';
870
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
871
		/* La largeur minimum de l'affichage est 600 px inclus */
872
		responsivDiff1 = ' droite';
873
		responsivDiff2 = '<div></div>';
874
		responsivDiff3 = '<div class="row">';
875
		responsivDiff4 = ( !this.isASL ) ? ' col-md-2 col-sm-4' : ' col-md-4 col-sm-5';
876
		responsivDiff5 = ( !this.isASL ) ? ' class="col-md-9 col-sm-7"' : ' class="col-md-7 col-sm-6"';
877
		responsivDiff6 = '</div>';
878
	}
879
 
880
	var obsNum           = datasObs.obsNum,
3426 idir 881
		numNomSel        = datasObs.sujet['num_nom_sel'] || '',
3425 idir 882
		taxon            = '',
883
		miniatures       = '',
884
		notes            = '',
885
		commentaires     = '',
886
		date             = '',
887
		latitude         = '',
888
		longitude        = '',
889
		coordonnees      = '',
890
		commune          = '',
891
		lieuObs          = '',
892
		inseeCommuneText = '',
893
		referentiel      = '',
894
		nn               = '',
895
		lieudit          = '',
896
		station          = '',
897
		milieu           = '',
898
		certitude        = '',
899
		numArbre         = '',
900
		obsArbre         = '';
901
 
902
	if ( !this.isASL ) {
903
		latitude     = datasObs.sujet['latitude'] || '';
904
		longitude    = datasObs.sujet['longitude'] || '';
905
		inseeCommune = datasObs.sujet['commune_code_insee'] || '';
3426 idir 906
		commune      = datasObs.sujet['commune_nom'] || '';
3425 idir 907
		if ( this.valOk( inseeCommune ) ) {
908
			inseeCommuneText = '(INSEE Commune:' + inseeCommune + ') ';
909
		}
910
		if ( this.valOk( numNomSel ) ) {
911
			referentiel = '<span class="referentiel-obs">' + '[' + datasObs.sujet['referentiel'] + ']' + '</span>';
912
		}
913
		if ( this.valOk( datasObs.sujet['lieudit'] ) ) {
914
			lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + datasObs.sujet['lieudit'] + ' ';
915
		}
916
		if ( this.valOk( datasObs.sujet['station'] ) ) {
917
			station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + datasObs.sujet['station'] + ' ';
918
		}
919
		if ( this.valOk( datasObs.sujet['milieu'] ) ) {
920
			milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + datasObs.sujet['milieu'] + ' ';
921
		}
922
		nn = this.ajouterNumNomSel( numNomSel );
923
	} else {
924
		certitude = ' [certitude : ' + datasObs.sujet.certitude + ']';
925
		if ( 'arbres' === this.sujet ) {
926
			numArbre   = datasObs.sujet['num-arbre'];
927
			numNomSel  = datasObs.sujet.taxon.numNomSel;
928
			taxon      = datasObs.sujet.taxon.value;
929
			miniatures = this.ajouterImgMiniatureAuTransfert(datasObs.sujet['miniature-img'] );
930
			notes      = datasObs.sujet['com-arbres'] || '';
931
			latitude   = datasObs.sujet['latitude-arbres'];
932
			longitude  = datasObs.sujet['longitude-arbres'];
933
			numArbre   = datasObs.sujet['num-arbre'];
934
			// s'assurer que la date est au bon format
935
			date       = this.fournirDate( datasObs.releve.date );
3426 idir 936
			commune    = datasObs.releve['commune-nom'] || '';
3425 idir 937
		} else {
3426 idir 938
			numArbre   = datasObs.numArbre;
3425 idir 939
		}
940
		obsArbre = '<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>';
941
	}
942
	if ( !this.isASL || 'arbres' !== this.sujet ) {
943
		taxon      = datasObs.sujet['nom_sel'];
944
		miniatures = this.ajouterImgMiniatureAuTransfert();
945
		notes      = datasObs.sujet['notes'] || '';
946
		date       = this.fournirDate( datasObs.sujet.date );
947
	}
948
	if( !this.isASL || 'arbres' === this.sujet ) {
949
		if ( this.valOk( commune ) ) {
950
			lieuObs = ' '  + this.msgTraduction( 'lieu-obs' ) + ' ' + '<span class="commune">' + commune + '</span> ';
951
		}
952
		if ( this.valOk( latitude ) && this.valOk( longitude ) ) {
953
			coordonnees = '[' + latitude + ' / ' + longitude + ']';
954
		}
955
	}
956
	if ( this.valOk( notes ) ) {
957
		commentaires =
958
			this.msgTraduction( 'commentaires' ) +
959
			' : <span>'+
960
				notes +
961
			'</span> ';
962
	}
963
	// html du bloc résumé de l'obs
964
	$( '#liste-obs' ).prepend(
965
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
966
			'<div '+
967
				'class="obs-action" '+
968
				'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
969
			'>'+
970
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.msgTraduction( 'obs-numero' ) + obsNum + '">'+
971
				'<i class="far fa-trash-alt"></i>'+
972
				'</button>'+
973
				responsivDiff2 +
974
			'</div> '+
975
			responsivDiff3 +
976
				'<div class="thumbnail' + responsivDiff4 + '">'+
977
					miniatures +
978
				'</div>'+
979
				'<div' + responsivDiff5 + '>'+
980
					'<ul class="unstyled">'+
981
						'<li>'+
982
							// isASL
983
							obsArbre +
984
							// toujours
985
							'<span class="nom-sci">' + taxon + '</span> '+
986
							// !isASL
987
							nn +
988
							referentiel +
989
							// isASL
990
							certitude +
991
							// !this.isASL || 'arbres' === this.sujet
992
							lieuObs +
993
							// !isASL
994
							inseeCommuneText +
995
							// !this.isASL || 'arbres' === this.sujet
996
							coordonnees +
997
							// toujours
998
							' ' + this.msgTraduction( 'obs-le' ) + ' '+
999
							'<span class="date">' + date + '</span>'+
1000
						'</li>'+
1001
						'<li>'+
1002
							// !isASL
1003
							lieudit +
1004
							station +
1005
							milieu +
1006
						'</li>'+
1007
						'<li>'+
1008
							// this.valOk( notes )
1009
							commentaires +
1010
						'</li>'+
1011
					'</ul>'+
1012
				'</div>'+
1013
			responsivDiff6+
1014
		'</div>'
1015
	);
1016
 
1017
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1018
};
1019
 
1020
/**
1021
 * Ajoute une boîte de miniatures avec défilement des images,
1022
 * pour une obs de la liste des obs à transmettre
1023
 */
1024
WidgetsSaisiesCommun.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages = undefined ) {
1025
	const lthis = this;
1026
	var html         =
1027
			'<div class="defilement-miniatures">'+
1028
				'<figure class="centre">'+
1029
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1030
				'</figure>'+
1031
			'</div>',
1032
		miniatures   = '',
1033
		centre       = '',
1034
		defilVisible = '',
1035
		length       = 0;
1036
 
1037
	if ( this.valOk( chargerImages ) || this.valOk( $( '#miniatures img' ) ) ) {
1038
		if ( this.valOk( chargerImages ) ) {
1039
			$.each(  chargerImages, function( i, value ) {
1040
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
1041
 
1042
				var css        = ( lthis.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
1043
					src        = value.src,
1044
					alt        = value.nom,
1045
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1046
 
1047
				miniatures += miniature;
1048
			});
1049
			length = chargerImages.length;
1050
		} else {
1051
			var premiere     = true;
1052
			$( '#miniatures img' ).each( function() {
1053
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1054
				premiere = false;
1055
 
1056
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1057
					src        = $( this ).attr( 'src' ),
1058
					alt        = $( this ).attr( 'alt' ),
1059
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1060
 
1061
				miniatures += miniature;
1062
			});
1063
			length = $( '#miniatures img' ).length;
1064
		}
1065
		if ( 1 === length ) {
1066
			centre       = 'centre';
1067
			defilVisible = ' defilement-miniatures-cache';
1068
		}
1069
		html             =
1070
			'<div class="defilement-miniatures">'+
1071
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1072
				'<figure class="' + centre + '">'+
1073
					miniatures+
1074
				'</figure>'+
1075
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1076
			'</div>';
1077
	}
1078
 
1079
	return html;
1080
};
1081
 
1082
/**
1083
 * Construit le html à afficher pour le numNom
1084
 */
1085
WidgetsSaisiesCommun.prototype.ajouterNumNomSel = function( numNomSel ) {
1086
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1087
 
1088
	if ( !this.valOk( numNomSel ) ) {
1089
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1090
	}
1091
 
1092
	return nn;
1093
};
1094
 
1095
/**
1096
 * Stocke des données d'obs à envoyer à la bdd
1097
 */
1098
WidgetsSaisiesCommun.prototype.stockerObsData = function( obsDatas ) {
1099
	if ( this.isASL && 'arbres' === this.sujet ) {
1100
		// Dans ce cas la fonction formaterFormObsData renvoie des données au même format que l'input hidden "releve-data"
1101
		// car les données peuvent provenir soit de la formaterFormObsData soit de cet input
1102
		const lthis = this;
3428 idir 1103
		// si releve dupliqué on ne stocke pas l'image :
1104
		var stockerImg  = this.valOk( obsDatas.sujet['miniature-img'] ),
3425 idir 1105
			imgNom      = [],
1106
			imgB64      = [];
1107
 
1108
		// Si on a bien un 'miniature-img' dans les données
1109
		if( stockerImg ) {
1110
			$.each( obsDatas.sujet['miniature-img'], function( i, obj ) {
1111
				if( obj.hasOwnProperty( 'id' ) ) {
1112
					stockerImg = false;
1113
				}
1114
				return stockerImg;
1115
			});
1116
		}
1117
		// Si les miniatures ne sont pas déjà stockées (résultat de la loop précédente)
1118
		if( stockerImg ) {
1119
			$.each( obsDatas.sujet['miniature-img'] , function( i, obj ) {
1120
				if( lthis.valOk( obj.nom ) ) {
1121
					imgNom.push( obj.nom );
1122
				}
1123
				if( lthis.valOk( obj['b64'] ) ) {
1124
					imgB64.push( obj['b64'] );
1125
				}
1126
			});
1127
		} else {
1128
			imgNom = lthis.getNomsImgsOriginales();
1129
			imgB64 = lthis.getB64ImgsOriginales();
1130
		}
1131
		// Stockage en data des données d'obs à transmettre
3428 idir 1132
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, {
1133
			'num_nom_sel'        : obsDatas.sujet.taxon.numNomSel,
3425 idir 1134
			'nom_sel'            : obsDatas.sujet.taxon.value,
1135
			'nom_ret'            : obsDatas.sujet.taxon.nomRet,
1136
			'num_nom_ret'        : obsDatas.sujet.taxon.numNomRet,
1137
			'num_taxon'          : obsDatas.sujet.taxon.nt,
1138
			'famille'            : obsDatas.sujet.taxon.famille,
1139
			'referentiel'        : obsDatas.sujet.referentiel,
1140
			'certitude'          : obsDatas.sujet.certitude,
1141
			// La date provenant de input "releve-data" n'est pas au bon format
3428 idir 1142
			'date'               : this.fournirDate( obsDatas.releve.date ),
3425 idir 1143
			'notes'              : obsDatas.releve.commentaires.trim(),
1144
			'pays'               : obsDatas.releve.pays,
1145
			'commune_nom'        : obsDatas.releve['commune-nom'],
1146
			'commune_code_insee' : obsDatas.releve['commune-insee'],
1147
			'latitude'           : obsDatas.sujet['latitude-arbres'],
1148
			'longitude'          : obsDatas.sujet['longitude-arbres'],
1149
			'altitude'           : obsDatas.sujet['altitude-arbres'],
1150
			'image_nom'          : imgNom,
1151
			'image_b64'          : imgB64,
1152
			// Ajout des champs étendus de l'obs
1153
			'obs_etendue'        : lthis.getObsChpSpecifiques( obsDatas )
1154
		});
1155
	} else {
1156
		// Stockage en data des données d'obs à transmettre
1157
		$( '#liste-obs' ).data( 'obsId' + obsDatas.obsNum, obsDatas.sujet );
1158
	}
1159
};
1160
 
1161
WidgetsSaisiesCommun.prototype.getNomsImgsOriginales = function() {
1162
	var noms = new Array();
1163
 
1164
	$( '.miniature-img' ).each( function() {
1165
		noms.push( $( this ).attr( 'alt' ) );
1166
	});
1167
 
1168
	return noms;
1169
};
1170
 
1171
WidgetsSaisiesCommun.prototype.getB64ImgsOriginales = function() {
1172
	var b64 = new Array();
1173
 
1174
	$( '.miniature-img' ).each( function() {
1175
		if ( $( this ).hasClass( 'b64' ) ) {
1176
			b64.push( $( this ).attr( 'src' ) );
1177
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1178
			b64.push( $( this ).data( 'b64' ) );
1179
		}
1180
	});
1181
 
1182
	return b64;
1183
};
1184
 
1185
/**
1186
 * Efface toutes les miniatures (formulaire)
1187
 */
1188
WidgetsSaisiesCommun.prototype.supprimerMiniatures = function() {
1189
	if ( !this.isASL ) {
1190
		// Déconnection MutationObserver miniatures
1191
		// Sinon on a une erreur avant la création d'une nouvelle obs
1192
		this.observer.disconnect();
1193
		$( '#miniatures' ).empty();
1194
		// Validation miniatures reprend à 0 pour une nouvelle obs
1195
		this.surPresenceAbsenceMiniature();
1196
	} else {
1197
		$( '#miniatures' ).empty();
1198
	}
1199
	$( '#miniature-msg' ).empty();
1200
};
1201
 
1202
WidgetsSaisiesCommun.prototype.surChangementNbreObs = function() {
1203
	if ( 0 === this.obsNbre ) {
1204
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1205
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1206
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1207
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1208
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1209
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1210
	}
1211
	if ( this.isASL && 'arbres' === this.sujet ) {
1212
		if ( 0 <= this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1213
			$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1214
		} else {
1215
			$( '#bloc-form-arbres' ).addClass( 'hidden' );
1216
		}
1217
	}
1218
};
1219
 
1220
WidgetsSaisiesCommun.prototype.defilerMiniatures = function( element ) {
1221
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1222
 
1223
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1224
	miniatureSelectionne.addClass( 'miniature-cachee' );
1225
 
1226
	var miniatureAffichee     = miniatureSelectionne;
1227
 
1228
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1229
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1230
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1231
		} else {
1232
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1233
		}
1234
	} else {
1235
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1236
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1237
		} else {
1238
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1239
		}
1240
	}
1241
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1242
	miniatureAffichee.removeClass( 'miniature-cachee' );
1243
};
1244
 
1245
WidgetsSaisiesCommun.prototype.supprimerObs = function( selector ) {
1246
	var obsId = $( selector ).val();
1247
 
1248
	// Problème avec IE 6 et 7
1249
	if ( 'Supprimer' === obsId ) {
1250
		obsId = $( selector ).attr( 'title' );
1251
	}
1252
	this.supprimerObsParId( obsId );
1253
};
1254
 
1255
/**
1256
 * Supprime l'obs et les data de l'obs
1257
 * et remonte les suivantes d'un cran
1258
 */
1259
WidgetsSaisiesCommun.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1260
	if ( this.isASL && 'arbres' === this.sujet ) {
1261
		if ( !transmission ) {
1262
			this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1263
			this.releveData.splice( obsId , 1 );
1264
			$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1265
		}
1266
		$( '#arbre-info-' + ( this.numArbre ) ).remove();
1267
		$( '#arbre-nb' ).text( this.numArbre );
1268
		this.numArbre -= 1;
1269
		if ( 1 > this.numArbre ) {
1270
			$( '#bloc-info-arbres-title' ).addClass( 'hidden' );
1271
		}
1272
 
1273
		var arbreExId   = 0,
1274
			arbreId     = 0;
1275
	}
1276
	this.obsNbre  -= 1;
1277
	$( '.obs-nbre' ).text( this.obsNbre );
1278
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1279
	$( '.obs' + obsId ).remove();
1280
	obsId = parseInt(obsId);
1281
 
1282
	if ( !transmission ) {
1283
		var listObsData = $( '#liste-obs' ).data(),
1284
			exId        = 0,
1285
			indexObs    = '',
1286
			exIndexObs  = '';
1287
 
1288
		for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1289
			exId       = parseInt(id) + 1;
1290
			indexObs   = 'obsId' + id;
1291
			exIndexObs = 'obsId' + exId;
1292
			$( '#liste-obs' ).removeData( indexObs );
1293
			$( '#obs' + exId )
1294
				.attr( 'id', 'obs' + id )
1295
				.removeClass( 'obs' + exId )
1296
				.addClass( 'obs' + id )
1297
				.find( '.supprimer-obs' )
1298
					.attr( 'title', 'Observation n°' + id )
1299
					.val( id );
1300
 
1301
			if ( this.isASL && 'arbres' === this.sujet ) {
1302
				arbreExId = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1303
				arbreId   = arbreExId - 1;
1304
				$( '#obs-arbre-' + arbreExId )
1305
					.attr( 'id', 'obs-arbre-' + arbreId )
1306
					.attr( 'data-arbre', arbreId )
1307
					.data( 'arbre', arbreId )
1308
					.text( 'Arbre ' + arbreId );
1309
				// modification du numero d'arbre dans les obs étendues
1310
				if ( this.valOk( listObsData[exIndexObs] ) ) {
1311
					$.each( listObsData[exIndexObs].obs_etendue, function( i, obsE ) {
1312
						if ('num_arbre' === obsE.cle ) {
1313
							listObsData[exIndexObs].obs_etendue[i].valeur = arbreId;
1314
							return false;
1315
						}
1316
					});
1317
				}
1318
			}
1319
 
1320
			// Mise à jour des données à transmettre
1321
			if ( this.valOk( listObsData[exIndexObs] ) ) {
1322
				$( '#liste-obs' ).data( indexObs, listObsData[exIndexObs] );
1323
			}
1324
			if ( parseInt( id ) !== this.obsNbre ) {
1325
				id = parseInt(id);
1326
			}
1327
		}
1328
	} else {
1329
		$( '#liste-obs' ).removeData( 'obsId' + obsId );
1330
	}
1331
};
1332
 
1333
WidgetsSaisiesCommun.prototype.transmettreObs = function() {
1334
	const lthis = this;
1335
	var observations = $( '#liste-obs' ).data();
1336
 
1337
	if ( this.debug ) {
1338
		console.dir( observations );
1339
	}
1340
	if ( !this.valOk( typeof observations, true, 'object' ) ) {
1341
		this.afficherPanneau( '#dialogue-zero-obs' );
1342
	} else {
1343
		this.nbObsEnCours         = 1;
1344
		this.nbObsTransmises      = 0;
1345
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1346
			return i;
1347
		}).length;
1348
		this.depilerObsPourEnvoi();
1349
	}
1350
 
1351
	return false;
1352
};
1353
 
1354
WidgetsSaisiesCommun.prototype.depilerObsPourEnvoi = function() {
1355
	var observations = $( '#liste-obs' ).data();
1356
	// la boucle est factice car on utilise un tableau
1357
	// dont on a besoin de n'extraire que le premier élément
1358
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1359
	// TODO: utiliser var.keys quand ça sera plus répandu
1360
	// ou bien utiliser un vrai tableau et pas un objet
1361
	for ( var obsNum in observations ) {
1362
		var obsATransmettre = {
1363
			'projet'  : this.tagsProjet,
1364
			'tag-obs' : this.tagObs,
1365
			'tag-img' : this.tagImg
1366
		};
1367
		var utilisateur = {
1368
			id_utilisateur : $( '#id_utilisateur' ).val(),
1369
			prenom         : $( '#prenom' ).val(),
1370
			nom            : $( '#nom' ).val(),
1371
			courriel       : $( '#courriel' ).val()
1372
		};
1373
 
1374
		obsATransmettre['utilisateur'] = utilisateur;
1375
		obsATransmettre[obsNum]        = observations[obsNum];
1376
 
1377
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1378
 
1379
		if( '' !== idObsNumerique ) {
1380
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1381
		}
1382
		break;
1383
	}
1384
};
1385
 
1386
WidgetsSaisiesCommun.prototype.envoyerObsAuCel = function( idObs, observation ) {
1387
	const lthis = this;
1388
 
1389
	var erreurMsg = '';
1390
 
1391
	$.ajax({
1392
		url        : lthis.serviceSaisieUrl,
1393
		type       : 'POST',
1394
		data       : observation,
1395
		dataType   : 'json',
1396
		beforeSend : function() {
1397
			$( '#dialogue-obs-transaction-ko,#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1398
			$( '.alert-txt' ).empty();
1399
			$( '.alert-txt .msg-erreur,.alert-txt .msg-debug' ).remove();
1400
			$( '#chargement' ).removeClass( 'hidden' );
1401
		},
1402
		success    : function( transfertDatas, textStatus, jqXHR ) {
1403
			if( lthis.isASL && 'arbres' === lthis.sujet ) {
1404
				// actualisation de id_observation dans '#releve-data'
1405
				lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1406
			}
1407
			// mise à jour du nombre d'obs à transmettre
1408
			// et suppression de l'obs
1409
			lthis.supprimerObsParId( idObs, true );
1410
			lthis.nbObsEnCours++;
1411
			// mise à jour du statut
1412
			lthis.mettreAJourProgression();
1413
			if( 0 < lthis.obsNbre ) {
1414
				// dépilement de la suivante
1415
				lthis.depilerObsPourEnvoi();
1416
			}
1417
		},
1418
		statusCode  : {
1419
			500 : function( jqXHR, textStatus, errorThrown ) {
1420
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1421
				}
1422
		},
1423
		error        : function( jqXHR, textStatus, errorThrown ) {
1424
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1425
			try {
1426
				reponse = jQuery.parseJSON( jqXHR.responseText );
1427
				if ( null !== reponse ) {
1428
					$.each( reponse, function( cle, valeur ) {
1429
						erreurMsg += valeur + '\n';
1430
					});
1431
				}
1432
			} catch( e ) {
1433
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1434
			}
1435
		},
1436
		complete      : function( jqXHR, textStatus ) {
1437
			var debugMsg = lthis.extraireEnteteDebug( jqXHR );
1438
 
1439
			if ( '' !== erreurMsg ) {
1440
				if ( lthis.debug ) {
1441
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1442
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1443
				}
1444
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1445
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagsProjet+
1446
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1447
 
1448
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1449
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1450
					$( '#tpl-transmission-ko' ).clone()
1451
						.find( '.courriel-erreur' )
1452
						.attr( 'href', hrefCourriel )
1453
						.end()
1454
						.html()
1455
				);
1456
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1457
				$( '#chargement' ).addClass( 'hidden' );
1458
				lthis.initialiserBarreProgression;
1459
			} else {
1460
				if ( lthis.debug ) {
1461
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1462
				}
1463
				if( 0 === lthis.obsNbre ) {
1464
					setTimeout( function() {
1465
						if ( lthis.isASL ) {
1466
							if ( 'arbres' === lthis.sujet ) {
1467
								if ( 'tb_streets' !== lthis.module ) {
1468
									$( '#bouton-saisir-lichens' ).removeClass( 'hidden' );
1469
								}
1470
								if ( 'tb_lichensgo' !== lthis.module ) {
1471
									$( '#bouton-saisir-plantes' ).removeClass( 'hidden' );
1472
								}
1473
							} else {
1474
								$( '#bouton-poursuivre' ).removeClass( 'hidden' );
1475
							}
1476
							$( '#bloc-controle-liste-obs,#bloc-gauche' ).addClass( 'hidden' );
1477
						}
1478
						$( '#chargement' ).addClass( 'hidden' );
1479
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1480
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1481
						if ( !lthis.isASL ) {
1482
							lthis.initialiserObs.bind( lthis );
1483
						}
1484
					}, 1500 );
1485
				}
1486
			}
1487
		}
1488
	});
1489
};
1490
 
1491
WidgetsSaisiesCommun.prototype.mettreAJourProgression = function() {
1492
	this.nbObsTransmises++;
1493
 
1494
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1495
 
1496
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1497
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1498
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1499
	if( 0 === this.obsNbre ) {
1500
		$( '.progress' ).removeClass( 'active' );
1501
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1502
	}
1503
};
1504
 
1505
WidgetsSaisiesCommun.prototype.initialiserBarreProgression = function() {
1506
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1507
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1508
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1509
	$( '.progress' ).addClass( 'active' );
1510
	$( '.progress' ).addClass( 'progress-bar-striped' );
1511
};
1512
 
1513
// Form Validator *************************************************************/
1514
WidgetsSaisiesCommun.prototype.configurerFormValidator = function() {
1515
	const lthis = this;
1516
 
1517
	$.validator.addMethod(
1518
		'dateCel',
1519
		function ( value, element ) {
1520
			return ( lthis.valOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
1521
		},
1522
		lthis.msgTraduction( 'date-incomplete' )
1523
	);
1524
	$.validator.addMethod(
1525
		'userEmailOk',
1526
		function ( value, element ) {
1527
			return ( lthis.valOk( value ) );
1528
		},
1529
		''
1530
	);
1531
	$.validator.addMethod(
1532
		'minMaxOk',
1533
		function ( value, element, param ) {
1534
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1535
			return lthis.validerMinMax( element ).cond;
1536
		},
1537
		$.validator.messages.minMaxOk
1538
	);
1539
	$.validator.addMethod(
1540
		'listFields',
1541
		function ( value, element ) {
1542
			return ( lthis.valOk( value ) );
1543
		},
1544
		''
1545
	);
1546
	$.extend( $.validator.defaults, {
1547
		errorElement: 'span',
1548
		errorPlacement: function( error, element ) {
1549
			if ( lthis.isASL && 'arbres' === lthis.sujet && ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) ) {
1550
				error.appendTo( element.closest( '.list' ) );
1551
			} else {
1552
				element.after( error );
1553
			}
1554
		},
1555
		onfocusout: function( element ) {
1556
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1557
				if ( $( element ).valid() ) {
1558
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1559
				} else {
1560
					$( element ).closest( '.control-group' ).addClass( 'error' );
1561
				}
1562
			}
1563
		},
1564
		onkeyup : function( element ) {
1565
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1566
				if ( $( element ).valid() ) {
1567
					$( element ).closest( '.control-group' ).removeClass( 'error' );
1568
				} else {
1569
					$( element ).closest( '.control-group' ).addClass( 'error' );
1570
				}
1571
			}
1572
		},
1573
		unhighlight: function( element ) {
1574
			if( lthis.valOk( element.id, false, 'taxon' ) || ( lthis.isASL && 'arbres' === lthis.sujet ) ) {
1575
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1576
			}
1577
		},
1578
		highlight: function( element ) {
1579
			$( element ).closest( '.control-group' ).addClass( 'error' );
1580
		}
1581
	});
1582
};
1583
 
1584
// Formatage date *************************************************************/
1585
WidgetsSaisiesCommun.prototype.fournirDate = function( dateObs ) {
1586
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1587
		return dateObs;
1588
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1589
		var dateArray = dateObs.split( '-' );
1590
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1591
	} else {
1592
		console.dir( 'erreur date : ' + dateObs )
1593
	}
1594
};
1595
 
1596
// scroll vers le formulaire
1597
WidgetsSaisiesCommun.prototype.scrollFormTop = function( scrollSelecteur, focus = '' ) {
1598
	const lthis = this;
1599
 
1600
	$( 'html, body' ).stop().animate({
1601
		scrollTop: $( scrollSelecteur ).offset().top
1602
	}, 300, function() {
1603
		if ( lthis.valOk( focus ) ) {
1604
			$( focus ).focus();
1605
		} else {
1606
			return;
1607
		}
1608
	});
1609
};
1610
 
1611
// Controle des panneaux d'infos **********************************************/
1612
 
1613
WidgetsSaisiesCommun.prototype.afficherPanneau = function( selecteur ) {
1614
	$( selecteur )
1615
		.removeClass( 'hidden' )
1616
		.hide()
1617
		.show( 600 )
1618
		.delay( this.dureeMessage )
1619
		.hide( 600 );
1620
	this.scrollFormTop( selecteur );
1621
};
1622
 
1623
WidgetsSaisiesCommun.prototype.masquerPanneau = function( selecteur ) {
1624
	$( selecteur ).addClass( 'hidden' );
1625
};
1626
 
1627
WidgetsSaisiesCommun.prototype.fermerPanneauAlert = function() {
1628
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1629
};
1630
 
1631
/**
1632
 * Si la langue est définie dans this.langue, et si des messages sont définis
1633
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1634
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1635
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1636
 */
1637
WidgetsSaisiesCommun.prototype.msgTraduction = function( cle ) {
1638
	var msg = 'N/A';
1639
 
1640
	if ( this.msgs ) {
1641
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1642
			msg = this.msgs[this.langue][cle];
1643
		} else if ( cle in this.msgs['fr'] ) {
1644
			msg = this.msgs['fr'][cle];
1645
		}
1646
	}
1647
	return msg;
1648
};
1649
 
1650
/**
1651
* Stope l'évènement courant quand on clique sur un lien.
1652
* Utile pour Chrome, Safari...
1653
*/
1654
WidgetsSaisiesCommun.prototype.arreter = function( event ) {
1655
	if ( event.stopPropagation ) {
1656
		event.stopPropagation();
1657
	}
1658
	if ( event.preventDefault ) {
1659
		event.preventDefault();
1660
	}
1661
 
1662
	return false;
1663
};
1664
 
1665
/**
1666
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1667
 * @param jqXHR
1668
 * @returns {String}
1669
 */
1670
WidgetsSaisiesCommun.prototype.extraireEnteteDebug = function( jqXHR ) {
1671
	var msgDebug = '';
1672
 
1673
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1674
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1675
		if ( null !== debugInfos ) {
1676
			$.each( debugInfos, function( cle, valeur ) {
1677
				msgDebug += valeur + '\n';
1678
			});
1679
		}
1680
	}
1681
 
1682
	return msgDebug;
1683
};
1684
 
1685
 
1686
WidgetsSaisiesCommun.prototype.confirmerSortie = function() {
1687
	$( window ).off( 'beforeunload' ).on( 'beforeunload', function( event ) {
1688
		if ( !event ) {
1689
			event = window.event;
1690
		}
1691
		return false;
1692
	});
1693
};
1694
 
1695
WidgetsSaisiesCommun.prototype.valOk = function ( valeur, sensComparaison = true, comparer = undefined ) {
1696
	return utils.valOk( valeur, sensComparaison, comparer );
1697
};
1698
 
1699
WidgetsSaisiesCommun.prototype.activerModale = function ( label, content = '', buttons = [] ) {
1700
	return utils.activerModale( label, content, buttons );
1701
};
1702
 
1703
// Lib hors objet
1704
 
1705
/*
1706
 * jQuery UI Autocomplete HTML Extension
1707
 *
1708
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1709
 * Dual licensed under the MIT or GPL Version 2 licenses.
1710
 *
1711
 * http://github.com/scottgonzalez/jquery-ui-extensions
1712
 *
1713
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1714
 */
1715
( function( $ ) {
1716
	var proto      = $.ui.autocomplete.prototype,
1717
		initSource = proto._initSource;
1718
 
1719
	WidgetsSaisiesCommun.prototype.filter = function( array, term ) {
1720
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1721
 
1722
		return $.grep( array, function( value ) {
1723
 
1724
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1725
		});
1726
	}
1727
	$.extend( proto, {
1728
		_initSource: function() {
1729
			if ( this.options.html && $.isArray( this.options.source ) ) {
1730
				this.source = function( request, response ) {
1731
					response( filter( this.options.source, request.term ) );
1732
				};
1733
			} else {
1734
				initSource.call( this );
1735
			}
1736
		},
1737
		_renderItem: function( ul, item) {
1738
			if ( item.retenu ) {
1739
				item.label = '<strong>' + item.label + '</strong>';
1740
			}
1741
 
1742
			return $( '<li></li>' )
1743
				.data( 'item.autocomplete', item )
1744
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1745
				.appendTo( ul );
1746
		}
1747
	});
1748
})( jQuery );