Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3120 delphine 1
/**
2
 * Constructeur WidgetSaisie par défaut
3
 */
4
function WidgetSaisie() {
3260 idir 5
	this.langue = 'fr';
6
	this.obsNbre = 0;
7
	this.nbObsEnCours = 1;
8
	this.totalObsATransmettre = 0;
9
	this.nbObsTransmises = 0;
10
	this.debug = null;
11
	this.html5 = null;
12
	this.tagProjet = null;
13
	this.tagImg = null;
14
	this.tagObs = null;
15
	this.separationTagImg = null;
16
	this.separationTagObs = null;
17
	this.obsId = null;
18
	this.serviceSaisieUrl = null;
19
	this.serviceObsUrl = null;
20
	this.nomSciReferentiel = null;
21
	this.especeImposee = false;
22
	this.infosEspeceImposee = null;
23
	this.isTaxonListe = false;
24
	this.autocompletionElementsNbre = null;
25
	this.referentielImpose = null;
26
	this.serviceAutocompletionNomSciUrl = null;
27
	this.serviceAutocompletionNomSciUrlTpl = null;
28
	this.obsMaxNbre = null;
29
	this.dureeMessage = null;
30
	this.serviceAnnuaireIdUrl = null;
31
	this.serviceNomCommuneUrl = null;
32
	this.serviceNomCommuneUrlAlt = null;
33
	this.chargementIconeUrl = null;
34
	this.chargementImageIconeUrl = null;
35
	this.calendrierIconeUrl = null;
36
	this.pasDePhotoIconeUrl = null;
3271 idir 37
	this.observer = null;
3240 idir 38
 
3260 idir 39
	// système de traduction minimaliste
40
	this.msgs = {
41
		fr: {
42
			'format-non-supporte': 'Le format de fichier n\'est pas supporté, les formats acceptés sont',
43
			'date-incomplete': 'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.',
44
			'observations-transmises': 'observations transmises',
45
			'taxon-ou-image' : 'Veuillez transmettre au moins, soit une image, soit une espèce',
46
			'supprimer-observation-liste': 'Supprimer cette observation de la liste à transmettre',
47
			'milieu': 'Milieu',
48
			'commentaires': 'Commentaires',
49
			'erreur-inconnue': 'Erreur inconnue',
50
			'non-lie-au-ref': 'non lié au référentiel',
51
			'obs-le': 'le',
52
			'quitter-page' : 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.',
53
			'courriel-connu' : 'Un compte existe pour ce courriel, connectez-vous pour saisir votre observation',
54
			'obs-numero' : 'Observation n°',
55
			'erreur-ajax' : 'Erreur Ajax',
56
			'erreur' : 'Erreur',
57
			'erreur-chargement' : 'Erreur lors du chargement de l\'observation',
58
			'lieu-obs' : 'observé à',
59
			'lieu-dit' : 'Lieu-dit',
60
			'station' : 'Station'
61
		},
62
		en: {
63
			'format-non-supporte': 'The file format is not supported, the accepted formats are',
64
			'date-incomplete': 'Format: dd / mm / yyyy. Incomplete date, use 0, example: 00/12/2011.',
65
			'observations-transmises': 'observations transmitted',
66
			'taxon-ou-image' : 'Please transmit at least one image or one species',
67
			'supprimer-observation-liste': 'Delete this observation from the list to be transmitted',
68
			'milieu': 'Environment',
69
			'commentaires': 'Comments',
70
			'erreur-inconnue': 'Unknown error',
71
			'non-lie-au-ref': 'unrelated to the referencial ',
72
			'obs-le': 'the',
73
			'quitter-page' : 'Are you sure you want to leave the page?\nThe observations entered but not transmitted will be lost.',
74
			'courriel-connu' : 'An account exists for this email, log in to enter your observation',
75
			'obs-numero' : 'Observation number ',
76
			'erreur-ajax' : 'Ajax Error',
77
			'erreur' : 'Error',
78
			'erreur-chargement' : 'Error loading the observation',
79
			'lieu-obs' : 'observed at',
80
			'lieu-dit' : 'Locality',
81
			'station' : 'Place'
82
		}
83
	};
3120 delphine 84
}
85
 
86
/**
87
 * Initialisation du widget
88
 */
89
WidgetSaisie.prototype.init = function() {
3260 idir 90
	this.initForm();
91
	this.initEvts();
92
	// Auth.js s'en occuppe
93
	if ( '' === $( '#nom-complet').text() && valeurOk ( $( '#courriel' ).val() ) ) {
94
		this.requeterIdentite();
95
	}
3120 delphine 96
};
97
 
98
/**
99
 * Initialise le formulaire, les validateurs, les listes de complétion...
100
 */
101
WidgetSaisie.prototype.initForm = function() {
102
 
3260 idir 103
	var lthis = this;
104
	if ( valeurOk( this.obsId ) ) {
105
		this.chargerInfoObs();
106
	}
3120 delphine 107
 
3260 idir 108
	if( this.isTaxonListe ) {
109
		this.surChangementTaxonListe();
110
		$( '#taxon-liste' ).on( 'change', lthis.surChangementTaxonListe );
111
		$( '#taxon-liste' ).on( 'change', lthis.surChangementValeurTaxon.bind( lthis ) );
112
		if ( this.debug ) {
113
			console.log( 'Selected taxon:' + $( '#taxon-liste option:selected' ).val());
114
		}
115
	} else {
116
		this.ajouterAutocompletionNoms();
117
	}
118
	// au rafraichissement de la page,
119
	// les input date semblent conserver la valeur entrée précedemment
120
	// c'est voulu après la création d'un obs mais pas quand la page est actualisée
121
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
122
	$( 'input[type=date]' ).each( function () {
123
		( valeurOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
124
	});
125
	this.configurerFormValidator();
126
	this.definirReglesFormValidator();
127
 
128
	if( this.especeImposee ) {
129
	  $( '#taxon' ).attr( 'disabled', 'disabled' );
130
	  $( '#taxon-input-groupe' ).attr( 'title', '' );
131
	  // Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
132
	  var infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
133
	  var nomRetenuComplet = infosEspeceImposee.nom_retenu_complet,
134
	    debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
135
	  if ( -1 !== debutAnneRefBiblio ) {
136
	    nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
137
	  }
138
	  // fin bricolage cracra
139
	  var infosAssociee = {
140
	    label : infosEspeceImposee.nom_sci_complet,
141
	    value : infosEspeceImposee.nom_sci_complet,
142
	    nt : infosEspeceImposee.num_taxonomique,
143
	    nomSel : infosEspeceImposee.nom_sci,
144
	    nomSelComplet : infosEspeceImposee.nom_sci_complet,
145
	    numNomSel : infosEspeceImposee.id,
146
	    nomRet : nomRetenuComplet,
147
	    numNomRet : infosEspeceImposee['nom_retenu.id'],
148
	    famille : infosEspeceImposee.famille,
149
	    retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
150
	  };
151
	  $( '#taxon' ).data( infosAssociee );
152
	}
3120 delphine 153
};
154
 
155
/**
156
 * Initialise les écouteurs d'événements
157
 */
158
WidgetSaisie.prototype.initEvts = function() {
3260 idir 159
	var lthis = this;
3120 delphine 160
 
3260 idir 161
	// identité
162
	$( '#bouton-anonyme' ).on( 'click', function() {
163
		$( this ).css({
164
			'background-color': 'rgba(0, 159, 184, 0.7)',
165
			'color': '#fff'
166
		});
167
		$( '#anonyme' ).removeClass( 'hidden' );
168
		$( '#courriel' ).focus();
169
	});
170
	if ( '' === $( '#nom-complet').text() ) {
171
		$( '#courriel' ).on( 'blur', this.requeterIdentite.bind( this ) );
172
		$( '#courriel' ).on( 'keypress', this.testerLancementRequeteIdentite.bind( this ) );
173
	}
174
	$( '#prenom' ).on( 'change', this.formaterPrenom );
175
	$( '#nom' ).on( 'change', this.formaterNom );
176
	$( '#courriel_confirmation' ).on( 'paste', this.bloquerCopierCollerCourriel.bind( this ) );
3208 idir 177
 
3260 idir 178
	// Sur téléchargement image
179
	$( '#fichier' ).on( 'change', function ( e ) {
180
		arreter( e );
181
		var options = {
182
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
183
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
184
			resetForm: true // reset the form after successful submit
185
		};
186
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
187
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
188
		if( lthis.verifierFormat( $( '#fichier' ).val() ) ) {
189
			$( '#form-upload' ).ajaxSubmit( options );
190
		} else {
191
			$( '#form-upload' )[0].reset();
192
			window.alert( lthis.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
193
		}
194
		return false;
195
	});
3208 idir 196
 
3260 idir 197
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
198
		$( this ).parent().remove();
199
	});
3208 idir 200
 
3260 idir 201
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
3208 idir 202
 
3260 idir 203
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
204
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
3208 idir 205
 
3260 idir 206
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
207
		event.preventDefault();
208
		lthis.defilerMiniatures( $( this ) );
209
	});
210
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
211
		event.preventDefault();
212
		lthis.defilerMiniatures( $( this ) );
213
	});
214
	$( 'body' ).on( 'click', '.supprimer-obs', function() {
215
	 var that = this,
216
			suppObs = lthis.supprimerObs.bind( lthis );
217
	 // bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
218
	 suppObs( that );
219
	});
3208 idir 220
 
3260 idir 221
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
3120 delphine 222
 
3260 idir 223
	// Alertes et tooltips
224
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
225
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
226
	$( '.has-tooltip' ).tooltip( 'enable' );
3120 delphine 227
};
228
 
3260 idir 229
// Identité Observateur *******************************************************/
230
WidgetSaisie.prototype.requeterIdentite = function() {
231
	var lthis = this;
232
	var courriel = $( '#courriel' ).val();
233
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
234
	if ( valeurOk( courriel ) ) {
235
		$.ajax({
236
			url : urlAnnuaire,
237
			type : 'GET',
238
			success : function( data, textStatus, jqXHR ) {
239
				if ( lthis.debug ) {
240
					console.log( 'SUCCESS: ' + textStatus );
241
				}
242
				if ( valeurOk( data ) && valeurOk( data[courriel] ) ) {
243
					var infos = data[courriel];
244
					lthis.surSuccesCompletionCourriel( infos, courriel );
245
				} else {
246
					lthis.surErreurCompletionCourriel();
247
				}
248
			},
249
			error : function( jqXHR, textStatus, errorThrown ) {
250
				if ( lthis.debug ) {
251
					console.log( 'ERREUR: '+ textStatus );
252
				}
253
				lthis.surErreurCompletionCourriel();
254
			},
255
			complete : function( jqXHR, textStatus ) {
256
				if ( lthis.debug ) {
257
					console.log( 'COMPLETE: '+ textStatus );
258
				}
259
			}
260
		});
261
	}
3120 delphine 262
};
263
 
3260 idir 264
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
265
	$( '#zone-courriel' ).before( '<p class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
266
	$( '#bouton-inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
267
	$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
268
	$( '#bouton-connexion a' ).css( 'box-shadow', '0 0 1.5px 1px red' );
3120 delphine 269
};
270
 
3260 idir 271
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
272
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
273
	$( '.warning' ).remove();
274
	$( '#bouton-connexion a' ).css( 'box-shadow', '' );
3120 delphine 275
 
3260 idir 276
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' );
277
	$( '#prenom, #nom, #courriel_confirmation' ).removeAttr( 'disabled' );
3120 delphine 278
};
279
 
3208 idir 280
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
3260 idir 281
	if ( valeurOk( event.which, true, 13 ) ) {
282
		this.requeterIdentite();
283
		event.preventDefault();
284
		event.stopPropagation();
285
	}
3120 delphine 286
};
287
 
3260 idir 288
WidgetSaisie.prototype.formaterNom = function() {
289
	$( this ).val( $( this ).val().toUpperCase() );
3120 delphine 290
};
291
 
3260 idir 292
WidgetSaisie.prototype.formaterPrenom = function() {
293
	var prenom = new Array(),
294
			mots = $( this ).val().split( ' ' ),
295
			motsLength = mots.length;
3120 delphine 296
 
3260 idir 297
	for ( var i = 0; i < motsLength; i++ ) {
298
		var mot = mots[i];
299
		if ( 0 <= mot.indexOf( '-' ) ) {
300
			var prenomCompose = new Array(),
301
					motsComposes = mot.split( '-' )
302
					motsComposesLength = motsComposes.length;
303
			for ( var j = 0; j < motsComposesLength; j++ ) {
304
				var motSimple = motsComposes[j],
305
						motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
3208 idir 306
 
3260 idir 307
				prenomCompose.push( motMajuscule );
308
			}
309
			prenom.push( prenomCompose.join( '-' ) );
310
		} else {
311
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
312
			prenom.push( motMajuscule );
313
		}
314
	}
315
	$( this ).val( prenom.join( ' ' ) );
3120 delphine 316
};
317
 
3260 idir 318
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
319
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
320
	return false;
3208 idir 321
};
322
 
3260 idir 323
// Préchargement des infos-obs ************************************************/
324
WidgetSaisie.prototype.chargerInfoObs = function() {
325
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
326
	var lthis = this;
327
	$.ajax({
328
		url: urlObs,
329
		type: 'GET',
330
		success: function( data, textStatus, jqXHR ) {
331
			if ( valeurOk( data ) ) {
332
				lthis.prechargerForm( data );
333
			} else {
334
				lthis.surErreurChargementInfosObs.bind( lthis );
335
			}
336
		},
337
		error: function( jqXHR, textStatus, errorThrown ) {
338
			lthis.surErreurChargementInfosObs();
339
		}
340
	});
3120 delphine 341
};
342
 
3260 idir 343
// @TODO faire mieux que ça !
344
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
345
	alert( this.msgTraduction( 'erreur-chargement' ) );
346
};
3208 idir 347
 
3260 idir 348
WidgetSaisie.prototype.prechargerForm = function( data ) {
3208 idir 349
 
3260 idir 350
	$( '#milieu' ).val( data.milieu );
3208 idir 351
 
3260 idir 352
	// $( '#carte-recherche' ).val( data.zoneGeo );
353
	// $( '#commune-nom' ).text( data.zoneGeo );
3208 idir 354
 
3260 idir 355
	// if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
356
	//   // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
357
	//   $( '#commune-code-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
358
	// }
3208 idir 359
 
3260 idir 360
	// if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
361
	//   var latLng = new google.maps.LatLng( data.latitude, data.longitude );
362
	//   this.mettreAJourMarkerPosition( latLng );
363
	//   this.marker.setPosition( latLng );
364
	//   this.map.setCenter( latLng );
365
	//   this.map.setZoom( 16 );
366
	// }
3120 delphine 367
};
368
 
3260 idir 369
// uniquement utilisé si taxon-liste ******************************************/
370
// Affiche/Cache le champ taxon
371
WidgetSaisie.prototype.surChangementTaxonListe = function() {
372
	if ( valeurOk( $( '#taxon-liste' ).val() ) ) {
373
		if ( 'autre' !== $( '#taxon-liste' ).val() ) {
3270 idir 374
			$( '#taxon-input-groupe' )
375
				.hide( 200, function () {
376
					$( this ).addClass( 'hidden' ).show();
377
				})
378
				.find( '#taxon-autre' ).val( '' );
3260 idir 379
		} else {
3270 idir 380
			$( '#taxon-input-groupe' )
381
				.hide()
382
				.removeClass( 'hidden' )
383
				.show(200)
384
				.find( '#taxon-autre' )
385
					.on( 'change', function() {
386
						if( !valeurOk( $( '#taxon-autre' ).data( 'numNomSel' ) ) ) {
387
							$( '#taxon' ).val( $( '#taxon-autre' ).val() );
388
							$( '#taxon' ).data( 'numNomSel', '' )
389
								.data( 'nomRet','' )
390
								.data( 'numNomRet', '' )
391
								.data( 'nt', '' )
392
								.data( 'famille', '' );
393
						}
394
						$( '#taxon' ).trigger( 'change' );
395
					});
3260 idir 396
		}
397
	}
3120 delphine 398
};
399
 
3208 idir 400
 
3260 idir 401
WidgetSaisie.prototype.surChangementValeurTaxon = function() {
402
	var numNomSel = 0;
403
 
404
	if( valeurOk( $( '#taxon-liste' ).val() ) ) {
405
		if( 'autre' === $( '#taxon-liste' ).val() ) {
406
			this.ajouterAutocompletionNoms();
407
		} else {
408
			var optionRetenue = $( '#taxon-liste' ).find( 'option[value="' + $( '#taxon-liste' ).val() + '"]' );
409
			// $( '#taxon' ).val( $( '#taxon-liste' ).val() );
410
			$( '#taxon' ).val( $( '#taxon-liste' ).val() )
411
				.data( 'value', $( '#taxon-liste' ).val() )
412
				.data( 'numNomSel', optionRetenue.data( 'num-nom-sel' ) )
413
				.data( 'nomRet', optionRetenue.data( 'nom-ret' ) )
414
				.data( 'numNomRet', optionRetenue.data( 'num-nom-ret' ) )
415
				.data( 'nt', optionRetenue.data( 'nt' ) )
416
				.data( 'famille', optionRetenue.data( 'famille' ) );
3270 idir 417
			$( '#taxon' ).trigger( 'change' );
3260 idir 418
 
419
			numNomSel = $( '#taxon' ).data( 'numNomSel' );
420
			// Si l'espèce est mal déterminée la certitude est "à déterminer"
421
			if( !valeurOk( numNomSel ) ) {
422
				$( '#certitude' ).find( 'option' ).each( function() {
423
					if ( $( this ).hasClass( 'aDeterminer' ) ) {
424
						$( this ).attr( 'selected', true );
425
					} else {
426
						$( this ).attr( 'selected', false );
427
					}
428
				});
429
			}
430
		}
431
	}
3120 delphine 432
};
433
 
3260 idir 434
// Autocompletion taxons ******************************************************/
435
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
436
	var lthis = this;
3208 idir 437
 
3260 idir 438
	var taxonSelecteur = '#taxon';
439
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
440
		taxonSelecteur += '-autre';
441
	}
442
	$( taxonSelecteur ).autocomplete({
443
		source: function( requete, add ) {
444
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
445
			requete = '';
446
			if( valeurOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
447
				var url = lthis.getUrlAutocompletionNomsSci();
448
				$.getJSON( url, requete, function( data ) {
449
					var suggestions = lthis.traiterRetourNomsSci( data );
450
					add( suggestions );
3263 idir 451
				})
452
				.fail( function() {
453
				    $( '#certitude' ).find( 'option' ).each( function() {
454
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
455
							$( this ).attr( 'selected', true );
456
						} else {
457
							$( this ).attr( 'selected', false );
458
						}
459
					});
3260 idir 460
				});
461
			}
462
		},
463
		html: true
464
	});
3270 idir 465
	$( taxonSelecteur ).on( 'autocompleteselect', this.surAutocompletionTaxon );
3260 idir 466
};
3208 idir 467
 
3260 idir 468
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
469
	var taxonSelecteur = '#taxon';
470
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
471
		taxonSelecteur += '-autre';
472
	}
473
	var mots = $( taxonSelecteur ).val();
474
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
475
	url = url.replace( '{masque}', mots );
476
	return url;
477
};
3208 idir 478
 
3260 idir 479
WidgetSaisie.prototype.traiterRetourNomsSci = function( data ) {
3208 idir 480
 
3260 idir 481
	var taxonSelecteur = '#taxon';
482
	if ( valeurOk ( $( '#taxon-liste' ).val(), true, 'autre' ) ) {
483
		taxonSelecteur += '-autre';
484
	}
485
	var suggestions = [];
486
	if ( undefined != data.resultat ) {
487
		$.each( data.resultat, function( i, val ) {
488
			val.nn = i;
489
			var nom = {
490
				label : '',
491
				value : '',
492
				nt : 0,
493
				nomSel : '',
494
				nomSelComplet : '',
495
				numNomSel : 0,
496
				nomRet : '',
497
				numNomRet : 0,
498
				famille : '',
499
				retenu : false
500
			};
501
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
502
				nom.label = '...';
503
				nom.value = $( taxonSelecteur ).val();
504
				suggestions.push( nom );
505
				return false;
506
			} else {
507
				nom.label = val.nom_sci_complet;
508
				nom.value = val.nom_sci_complet;
509
				nom.nt = val.num_taxonomique;
510
				nom.nomSel = val.nom_sci;
511
				nom.nomSelComplet = val.nom_sci_complet;
512
				nom.numNomSel = val.nn;
513
				nom.nomRet = val.nom_retenu_complet;
514
				nom.numNomRet = val['nom_retenu.id'];
515
				nom.famille = val.famille;
516
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
517
				// en tout cas c'est harmonisé avec le CeL
518
				nom.retenu = ( 'true' == val.retenu );
3208 idir 519
 
3260 idir 520
				suggestions.push( nom );
521
			}
522
		});
523
	}
524
	return suggestions;
525
};
3240 idir 526
 
3260 idir 527
WidgetSaisie.prototype.surAutocompletionTaxon = function( event, ui ) {
528
	if ( valeurOk( ui ) ) {
529
		$( '#taxon' ).val( ui.item.value );
530
		$( '#taxon' ).data( 'value', ui.item.value )
531
			.data( 'numNomSel', ui.item.numNomSel )
532
			.data( 'nomRet', ui.item.nomRet )
533
			.data( 'numNomRet', ui.item.numNomRet )
534
			.data( 'nt', ui.item.nt )
535
			.data( 'famille', ui.item.famille );
536
		if ( ui.item.retenu ) {
537
			$( '#taxon' ).addClass( 'ns-retenu' );
538
		} else {
539
			$( '#taxon' ).removeClass( 'ns-retenu' );
540
		}
3208 idir 541
 
3260 idir 542
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
543
		if( !valeurOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
544
			$( '#certitude' ).find( 'option' ).each( function() {
545
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
546
					$( this ).attr( 'selected', true );
547
				} else {
548
					$( this ).attr( 'selected', false );
549
				}
550
			});
551
		}
552
	}
3270 idir 553
	$( '#taxon' ).trigger( 'change' );
3208 idir 554
};
555
 
3260 idir 556
// Form Validator *************************************************************/
557
WidgetSaisie.prototype.configurerFormValidator = function() {
3270 idir 558
	var lthis = this;
3240 idir 559
 
3260 idir 560
	$.validator.addMethod(
561
		'dateCel',
562
		function ( value, element ) {
563
			return ( valeurOk( value ) && ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) ) );
564
		},
565
		lthis.msgTraduction( 'date-incomplete' )
566
	);
3240 idir 567
 
3260 idir 568
	$.validator.addMethod(
569
		'userEmailOk',
570
		function ( value, element ) {
571
			return ( valeurOk( value ) );
572
		},
573
		''
574
	);
3240 idir 575
 
3260 idir 576
	$.validator.addMethod(
577
		'minMaxOk',
578
		function ( value, element, param ) {
579
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
580
			return lthis.validerMinMax( element ).cond;
581
		},
582
		$.validator.messages.minMaxOk
583
	);
3208 idir 584
 
3260 idir 585
	$.validator.addMethod(
586
		'listFields',
587
		function ( value, element ) {
588
			return ( valeurOk( value ) );
589
		},
590
		''
591
	);
3240 idir 592
 
3260 idir 593
	$.extend( $.validator.defaults, {
594
		errorElement: 'span',
595
		onfocusout: function( element ) {
3270 idir 596
			if( valeurOk( element.id, false, 'taxon' ) ) {
597
				if ( $( element ).valid() ) {
598
					$( element ).closest( '.control-group' ).removeClass( 'error' );
599
				} else {
600
					$( element ).closest( '.control-group' ).addClass( 'error' );
601
				}
3260 idir 602
			}
603
		},
604
		onkeyup : function( element ) {
3270 idir 605
			if( valeurOk( element.id, false, 'taxon' ) ) {
606
				if ( $( element ).valid() ) {
607
					$( element ).closest( '.control-group' ).removeClass( 'error' );
608
				} else {
609
					$( element ).closest( '.control-group' ).addClass( 'error' );
610
				}
611
			}
612
		},
613
		unhighlight: function( element ) {
614
			if( valeurOk( element.id, false, 'taxon' ) ) {
3260 idir 615
				$( element ).closest( '.control-group' ).removeClass( 'error' );
616
			}
617
		},
618
		highlight: function( element ) {
619
			$( element ).closest( '.control-group' ).addClass( 'error' );
3270 idir 620
		}
3260 idir 621
	});
622
};
3208 idir 623
 
3260 idir 624
WidgetSaisie.prototype.chpEtendusValidation = function() {
625
	var lthis = this;
626
	var $thisForm = $( '#form-supp' ),
627
			elements  =
628
				'.checkbox,'+
629
				'.radio,'+
630
				'.checkboxes,'+
631
				'.select,'+
632
				'textarea,'+
633
				'input[type=text]:not(.collect-other),'+
634
				'input[type=email],'+
635
				'input[type=number],'+
636
				'input[type=range],'+
637
				'input[type=date]',
638
			speFields = ['checkbox','radio','checkboxes','select'],
639
			spefieldsCount = speFields.length,
640
			chpSuppValidation = {
641
				rules : {},
642
				messages : {},
643
				minmax : []
644
			},
645
			errors = {},
646
			namesListFields = [],
647
			picked = '';
3208 idir 648
 
3260 idir 649
	$( elements, $thisForm ).each( function() {
650
		for( var fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
651
			if ( valeurOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valeurOk( chpSuppValidation.rules[ dataName ] ) ) {
652
				var dataName = $( this ).data( 'name' );
3240 idir 653
 
3260 idir 654
				namesListFields.push( dataName );
655
				chpSuppValidation.rules[ dataName ] = { required : true };
3240 idir 656
 
3260 idir 657
				if ( valeurOk( $( '.other', $( this ) ) ) ) {
658
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
659
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
660
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
661
						minlength: 1
662
					};
663
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
664
				}
665
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
666
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
667
				errors[dataName] = '.' + speFields[fieldsClass];
668
			}
669
		}
670
		if ( valeurOk( $( this ).attr( 'name' ) ) && valeurOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
671
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
672
			if(
673
					( valeurOk( $( this ).attr( 'type' ), true, 'number' ) || valeurOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
674
					( valeurOk( $( this )[0].min ) || valeurOk( $( this )[0].max ) )
675
				) {
676
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
677
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
678
			}
679
		}
680
	});
681
	if ( valeurOk( chpSuppValidation.rules ) ) {
682
		$.each( chpSuppValidation.rules, function( key ) {
683
			if ( !valeurOk( chpSuppValidation.messages[key] ) ) {
684
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
685
			}
686
		});
687
		if ( 0 < Object.keys( errors ).length ) {
688
			chpSuppValidation['errors'] = errors;
689
		}
690
	}
691
	return chpSuppValidation;
3208 idir 692
};
693
 
3260 idir 694
WidgetSaisie.prototype.validerMinMax = function( element ) {
3208 idir 695
 
3260 idir 696
	var mMCond      = new Boolean(),
697
			minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
698
			maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
699
			messageMnMx = 'La valeur entrée doit être',
700
			returnMnMx  = { cond : true , message : '' };
3208 idir 701
 
3260 idir 702
	if(
703
			( valeurOk( element.type, true, 'number' ) || valeurOk( element.type, true, 'range' ) ) &&
704
			( valeurOk( element.min ) || valeurOk( element.max ) )
705
		) {
706
		if ( element.min && element.max ) {
707
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
708
			mnMxCond     = ( minCond && maxCond );
709
		} else if ( element.min ) {
710
			messageMnMx += ' supérieure à ' + element.min;
711
			mnMxCond     = minCond;
712
		} else {
713
			messageMnMx += ' inférieure à ' + element.max;
714
			mnMxCond     = maxCond;
715
		}
716
		returnMnMx.cond    = mnMxCond;
717
		returnMnMx.message = messageMnMx;
718
	}
719
	return returnMnMx;
3208 idir 720
 
721
};
722
 
723
 
3260 idir 724
WidgetSaisie.prototype.definirReglesFormValidator = function() {
3270 idir 725
	var formSuppValidation = this.chpEtendusValidation(),
726
		lthis = this;
3208 idir 727
 
3260 idir 728
	$( '#form-supp' ).validate({
729
		onclick : function( element ) {
730
			if (
731
				(
732
					valeurOk( element.type, true, 'checkbox' ) ||
733
					valeurOk( element.type, true, 'radio' )
734
				) &&
735
				(
736
					!valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
737
					valeurOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
738
					!valeurOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
739
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
740
					(
741
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
742
						$( element ).closest( '.control-group' ).hasClass('error')
743
					)
744
				)
745
			) {
746
				$( element ).valid();
747
				if ( $( element ).valid() ) {
748
					$( element ).closest( '.control-group' ).removeClass( 'error' );
749
					$( element ).next( $( 'span.error' ) ).remove();
750
				} else {
751
					$( element ).closest( '.control-group' ).addClass( 'error' );
752
				}
753
			}
754
			return false;
755
		},
756
		rules : formSuppValidation.rules,
757
		messages : formSuppValidation.messages,
758
		errorPlacement : function( error , element ) {
759
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
760
				var errorsKeys = Object.keys( formSuppValidation.errors ),
761
						thisKey = '',
762
						errorsFlag = true;
763
				for ( i = 0 ; i < errorsKeys.length ; i++ ) {
764
					thisKey = errorsKeys[i];
765
					if( $( element ).attr( 'name' ) === thisKey ) {
766
						$( formSuppValidation.errors[thisKey] ).append( error );
767
						errorsFlag = false;
768
					}
769
				}
770
				if ( errorsFlag ) {
771
					error.insertAfter( element );
772
				}
773
			} else {
774
				error.insertAfter( element );
775
			}
776
		}
777
	});
3208 idir 778
 
3260 idir 779
	$( '#form-supp .select' ).change( function() {
780
		$( this ).valid();
781
	});
3208 idir 782
 
3260 idir 783
	$( 'input[type=date]' ).on( 'input', function() {
784
		$( this ).valid();
785
	});
3208 idir 786
 
3270 idir 787
	$( '#taxon' ).on( 'change', function() {
788
		var images = valeurOk( $( '#miniatures .miniature' ) );
789
		lthis.validerTaxonImage( valeurOk( $( this ).val() ), images );
790
	});
791
 
3271 idir 792
	// MutationObserver sur les miniatures pour validation
3270 idir 793
	this.surPresenceAbsenceMiniature();
794
 
3260 idir 795
	$( '#form-observation' ).validate({
796
		rules : {
797
			date_releve : {
798
				required : true,
799
				'dateCel' : true
800
			},
801
			latitude : {
802
				range: [-90, 90]
803
			},
804
			longitude : {
805
				range: [-180, 180]
806
			}
807
		}
808
	});
3208 idir 809
 
3260 idir 810
	$( '#form-observateur' ).validate({
811
		rules : {
812
			courriel : {
813
				required : true,
814
				email : true,
815
				'userEmailOk' : true
816
			},
817
			courriel_confirmation : {
818
				required : true,
819
				equalTo : '#courriel'
820
			}
821
		}
822
	});
3208 idir 823
};
824
 
3270 idir 825
WidgetSaisie.prototype.validerTaxonImage = function( taxon = false, images = false ) {
826
	var taxonOuImage = ( images || taxon );
827
	if ( images || taxon ) {
828
		this.masquerPanneau( '#dialogue-taxon-or-image' );
829
		$( '#bloc-taxon' ).removeClass( 'error' )
830
			.find( 'span.error' ).hide();
831
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
832
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
833
	} else {
834
		this.afficherPanneau( '#dialogue-taxon-or-image' );
835
		$( '#bloc-taxon' ).addClass( 'error' )
836
			.find( 'span.error' ).show();
837
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
838
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
839
	}
840
	return ( images || taxon );
841
};
842
 
843
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
844
	var lthis = this;
3271 idir 845
 
3270 idir 846
	// Selectionne le noeud dont les mutations seront observées
847
	var targetNode = document.getElementById( 'miniatures' );
848
	// Fonction callback à éxécuter quand une mutation est observée
849
	var callback = function( mutationsList ) {
850
	    for( var mutation of mutationsList ) {
851
	    	var taxon = valeurOk( $( '#taxon' ).val() );
852
	        images = ( 0 < mutation.target.childElementCount );
853
		 	lthis.validerTaxonImage( taxon, images );
854
	    }
855
	};
856
	// Créé une instance de l'observateur lié à la fonction de callback
3271 idir 857
	this.observer = new MutationObserver( callback );
3270 idir 858
	// Commence à observer le noeud cible pour les mutations précédemment configurées
3271 idir 859
	this.observer.observe( targetNode, { childList: true } );
3270 idir 860
};
861
 
3208 idir 862
WidgetSaisie.prototype.validerFormulaire = function() {
3270 idir 863
	var observateur  = $( '#form-observateur' ).valid();
864
	var obs          = $( '#form-observation' ).valid();
865
	var images       = valeurOk( $( '#miniatures .miniature' ) );
866
	var taxon        = valeurOk( $( '#taxon' ).val() );
867
	// validation et panneau taxon/images
868
 	var taxonOuImage = this.validerTaxonImage( taxon, images );
3271 idir 869
 	// console.log(taxonOuImage);
3270 idir 870
	var chpsSupp     = new Boolean();
3260 idir 871
	if ( valeurOk( $( '#form-supp' ) ) ) {
872
		chpsSupp = ( function () {
873
			var otherFlag = $( '#form-supp' ).valid();
874
			if( valeurOk( $( '.other', $( '#form-supp' ) ) ) ) {
875
				$( '.other', $( '#form-supp' ) ).each( function() {
876
					var picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
877
						if ( $( this ).is( picked ) && valeurOk( $( this ).val(), true, 'other' ) ) {
878
							otherFlag = false;
879
						}
880
				});
881
			}
882
			return otherFlag;
883
		})();
884
	} else {
885
		chpsSupp = true;
886
	}
3270 idir 887
	// panneau geoloc
888
	( $( '#latitude' ).valid() && $( '#longitude' ).valid() ) ? this.masquerPanneau( '#dialogue-geoloc-ko' ) : this.afficherPanneau( '#dialogue-geoloc-ko' );
889
	// panneau observateur
890
	( observateur ) ? this.masquerPanneau( '#dialogue-utilisateur-non-identifie' ) : this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
3208 idir 891
 
3270 idir 892
	return ( observateur && obs && taxonOuImage && chpsSupp );
3208 idir 893
};
894
 
3260 idir 895
// Fichier Images *************************************************************/
896
/**
897
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
898
 */
899
WidgetSaisie.prototype.afficherMiniature = function( reponse ) {
900
	if ( this.debug ) {
901
		var debogage = $( 'debogage', reponse ).text();
902
		//console.log( 'Débogage upload : '+debogage);
903
	}
904
	var message = $( 'message', reponse ).text();
905
	if ( valeurOk( message ) ) {
906
		$( '#miniature-msg' ).append( message );
907
	} else {
908
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
909
	}
910
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
3208 idir 911
};
912
 
3260 idir 913
/**
914
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
915
 */
916
WidgetSaisie.prototype.creerWidgetMiniature = function( reponse ) {
917
	var miniatureUrl = $( 'miniature-url', reponse ).text();
918
	var imgNom = $( 'image-nom', reponse ).text();
919
	var html =
920
		'<div class="miniature mb-3 mr-3">'+
921
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
922
			'<a class="effacer-miniature"><i class="far fa-trash-alt"></i></a>'+
3270 idir 923
		'</div>';
3260 idir 924
	return html;
3208 idir 925
};
926
 
3260 idir 927
/**
928
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
929
 */
930
WidgetSaisie.prototype.verifierFormat = function( nom ) {
931
	var parts = nom.split( '.' );
932
	extension = parts[ parts.length - 1 ];
933
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
3208 idir 934
};
935
 
3260 idir 936
/**
937
 * Efface une miniature (formulaire)
938
 */
939
WidgetSaisie.prototype.supprimerMiniature = function( miniature ) {
940
	miniature.parents( '.miniature' ).remove();
3208 idir 941
};
942
 
3260 idir 943
// Referentiel ****************************************************************/
944
// N'est pas utilisé en cas de taxon-liste
945
WidgetSaisie.prototype.surChangementReferentiel = function() {
946
	this.nomSciReferentiel = $( '#referentiel' ).val();
947
	//réinitialise taxon.val
948
	$( '#taxon' ).val( '' );
3263 idir 949
	$( '#taxon' ).data( 'numNomSel', '' );
3260 idir 950
	// this.initialiserAutocompleteCommune();
951
	// this.initialiserGoogleMap( false );
3208 idir 952
};
953
 
3260 idir 954
// Ajouter Obs ****************************************************************/
955
/**
956
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
957
 */
958
WidgetSaisie.prototype.ajouterObs = function() {
959
	// Fermeture automatique des dialogue de transmission de données
960
	// @WARNING TEST
961
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
962
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
963
 
964
	if ( this.validerFormulaire() ) {
965
		this.masquerPanneau( '#dialogue-form-invalide' );
966
		this.obsNbre = this.obsNbre + 1;
967
		$( '.obs-nbre' ).text( this.obsNbre );
968
		$( '.obs-nbre' ).triggerHandler( 'changement' );
969
		this.afficherObs();
970
		this.stockerObsData();
971
		this.supprimerMiniatures();
972
		if( !this.especeImposee ) {
973
			$( '#taxon' ).val( '' );
974
			$( '#taxon' ).data( 'numNomSel', '' )
3271 idir 975
				.data( 'nomRet','' )
976
				.data( 'numNomRet', '' )
977
				.data( 'nt', '' )
978
				.data( 'famille', '' );
3260 idir 979
			if( this.isTaxonListe ) {
980
				$( '#taxon-liste' ).find( 'option' ).each( function() {
981
					if ( $( this ).hasClass( 'choisir' ) ) {
982
						$( this ).attr( 'selected', true );
983
					} else {
984
						$( this ).attr( 'selected', false );
985
					}
986
				});
987
				$( '#taxon-input-groupe' ).addClass( 'hidden' );
988
				$('#taxon-autre').val('');
989
			}
990
		}
991
		if ( valeurOk( $( '#form-supp' ) ) ) {
992
			$( '#form-supp' ).validate().resetForm();
993
			// if ( valeurOk( $( '#form-supp' ) ) ) {
994
		}
995
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
996
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.msgTraduction( 'observations-transmises' ) );
997
	} else {
998
		this.afficherPanneau( '#dialogue-form-invalide' );
999
	}
3208 idir 1000
};
1001
 
1002
/**
3260 idir 1003
 * Affiche une observation dans la liste des observations à transmettre
1004
 */
1005
WidgetSaisie.prototype.afficherObs = function() {
1006
 
1007
	var numNomSel = $( '#taxon' ).data( 'numNomSel' ),
1008
			taxon = $( '#taxon' ).val(),
1009
			referentiel = '',
1010
			commune = '',
1011
			inseeLatitudeLongitude = '',
1012
			lieudit = '',
1013
			station = '',
1014
			milieu = '',
1015
			commentaires = '';
1016
 
1017
	if ( valeurOk( numNomSel ) ) {
1018
		referentiel = '<span class="referentiel-obs">' + '[' + this.nomSciReferentiel + ']' + '</span>';
1019
	}
1020
	if ( valeurOk( $( '#commune-nom' ).val() ) ) {
1021
		commune = ' '  + this.msgTraduction( 'lieu-obs' ) + ' <span class="commune">' + $( '#commune-nom' ).val() + '</span> ';
1022
	}
1023
	if ( valeurOk( $( '#commune-insee' ).val() ) &&  valeurOk( $( '#latitude' ).val() ) && valeurOk( $( '#longitude' ).val() ) ) {
1024
		inseeLatitudeLongitude = '(INSEE Commune:' + $('#commune-insee').val() + ') [' + $( '#latitude' ).val() + ' / ' + $( '#longitude' ).val() + ']';
1025
	}
1026
	if ( valeurOk( $( '#lieudit' ).val() ) ) {
1027
		lieudit = '<span>' + this.msgTraduction( 'lieu-dit' ) + ' :</span> ' + $( '#lieudit' ).val() + ' ';
1028
	}
1029
	if ( valeurOk( $( '#station' ).val() ) ) {
1030
		station = '<span>' + this.msgTraduction( 'station' ) + ' :</span> ' + $( '#station' ).val() + ' ';
1031
	}
1032
	if ( valeurOk( $( '#milieu' ).val() ) ) {
1033
		milieu = '<span>' + this.msgTraduction( 'milieu' ) + ' :</span> ' + $( '#milieu' ).val() + ' ';
1034
	}
1035
	if ( valeurOk( $( '#notes' ).val() ) ) {
1036
		commentaires = this.msgTraduction( 'commentaires' ) + ' : <span class="discretion">' + $( '#notes' ).val() + '</span>' + ' ';
1037
	}
1038
 
1039
	var responsivDiff1 = '',
1040
			responsivDiff2 = '',
1041
			responsivDiff3 = '',
1042
			responsivDiff4 = '',
1043
			responsivDiff5 = '',
1044
			responsivDiff6 = '';
1045
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
1046
		/* La largeur minimum de l'affichage est 600 px inclus */
1047
		responsivDiff1 = ' droite';
1048
		responsivDiff2 = '<div></div>';
1049
		responsivDiff3 = '<div class="row">';
1050
		responsivDiff4 = ' col-md-2 col-sm-4';
1051
		responsivDiff5 = ' class="col-md-9 col-sm-7"';
1052
		responsivDiff6 = '</div>';
1053
	}
1054
 
1055
 
1056
		$( '#liste-obs' ).prepend(
1057
			'<div id="obs' + this.obsNbre + '" class="obs obs' + this.obsNbre + ' mb-2">'+
1058
 
1059
				'<div '+
1060
					'class="obs-action" '+
1061
					'title="' + this.msgTraduction( 'supprimer-observation-liste' ) + '"'+
1062
				'>'+
1063
					'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ this.obsNbre + '" title="' + this.msgTraduction( 'obs-numero' ) + this.obsNbre + '">'+
1064
					'<i class="far fa-trash-alt"></i>'+
1065
					'</button>'+
1066
					responsivDiff2 +
1067
				'</div> '+
1068
 
1069
				responsivDiff3 +
1070
					'<div class="thumbnail' + responsivDiff4 + '">'+
1071
						this.ajouterImgMiniatureAuTransfert()+
1072
					'</div>'+
1073
					'<div' + responsivDiff5 + '>'+
1074
						'<ul class="unstyled">'+
1075
							'<li>'+
1076
								'<span class="nom-sci">' + taxon + '</span> '+
1077
								this.ajouterNumNomSel( numNomSel ) +
1078
								referentiel +
1079
								commune +
1080
								inseeLatitudeLongitude +
1081
								' ' + this.msgTraduction( 'obs-le' ) + ' ' +
1082
								'<span class="date">' + this.fournirDate( $( '#date_releve' ).val() ) + '</span>'+
1083
							'</li>'+
1084
							'<li>'+
1085
								lieudit +
1086
								station +
1087
								milieu +
1088
							'</li>'+
1089
							'<li>'+
1090
								commentaires +
1091
							'</li>'+
1092
						'</ul>'+
1093
					'</div>'+
1094
				responsivDiff6+
1095
			'</div>'
1096
		);
1097
 
1098
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
1099
};
1100
 
1101
/**
3208 idir 1102
 * Ajoute une boîte de miniatures avec défilement des images,
1103
 * pour une obs de la liste des obs à transmettre
1104
 */
1105
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
3260 idir 1106
	var html        =
1107
				'<div class="defilement-miniatures">'+
1108
					'<figure class="centre">'+
1109
						'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
1110
					'</figure>'+
1111
				'</div>',
1112
			miniatures   = '',
1113
			premiere     = true,
1114
			centre       = '';
1115
			defilVisible = '';
3208 idir 1116
 
3260 idir 1117
	if ( valeurOk( $( '#miniatures img' ) ) ) {
1118
		$( '#miniatures img' ).each( function() {
1119
			var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1120
			premiere = false;
3208 idir 1121
 
3260 idir 1122
			var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1123
					src        = $( this ).attr( 'src' ),
1124
					alt        = $( this ).attr( 'alt' ),
1125
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
3208 idir 1126
 
3260 idir 1127
			miniatures += miniature;
1128
		});
1129
		if ( 1 === $( '#miniatures img' ).length ) {
1130
			centre       = 'centre';
1131
			defilVisible = ' defilement-miniatures-cache';
1132
		}
1133
		html             =
1134
			'<div class="defilement-miniatures">'+
1135
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1136
				'<figure class="' + centre + '">'+
1137
					miniatures+
1138
				'</figure>'+
1139
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1140
			'</div>';
1141
	}
1142
	return html;
1143
};
3208 idir 1144
 
3260 idir 1145
WidgetSaisie.prototype.fournirDate = function( dateObs ) {
1146
	if ( /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test( dateObs ) ) {
1147
		return dateObs;
1148
	} else if ( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test( dateObs ) ) {
1149
		var dateArray = dateObs.split( '-' );
1150
		return dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0]
1151
	} else {
1152
		console.log( 'erreur date : ' + dateObs )
1153
	}
1154
}
3208 idir 1155
 
3260 idir 1156
WidgetSaisie.prototype.ajouterNumNomSel = function( numNomSel ) {
1157
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1158
	if ( !valeurOk( numNomSel ) ) {
1159
		nn = '<span class="alert-error">[' + this.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1160
	}
1161
	return nn;
3208 idir 1162
};
1163
 
1164
 
3260 idir 1165
WidgetSaisie.prototype.stockerObsData = function() {
1166
	var lthis = this;
3208 idir 1167
 
3260 idir 1168
	var numNomSel   = $( '#taxon' ).data( 'numNomSel' ),
1169
			nomSel      = $( '#taxon' ).val(),
1170
			nomRet      = $( '#taxon' ).data( 'nomRet' ),
1171
			numNomRet   = $( '#taxon' ).data( 'numNomRet' ),
1172
			numTaxon    = $( '#taxon' ).data( 'nt' ),
1173
			famille     = $( '#taxon' ).data( 'famille' ),
3263 idir 1174
			referentiel = ( !valeurOk( numNomSel ) ) ? 'autre' : this.nomSciReferentiel;
3208 idir 1175
 
3260 idir 1176
	$( '#liste-obs' ).data( 'obsId' + this.obsNbre, {
1177
		'num_nom_sel'        : numNomSel,
1178
		'nom_sel'            : nomSel,
1179
		'nom_ret'            : nomRet,
1180
		'num_nom_ret'        : numNomRet,
1181
		'num_taxon'          : numTaxon,
1182
		'famille'            : famille,
1183
		'referentiel'        : referentiel,
1184
		'certitude'          : $( '#certitude' ).val(),
1185
		'date'               : lthis.fournirDate( $( '#date_releve' ).val() ),
1186
		'notes'              : $( '#notes' ).val().trim(),
1187
		'pays'               : $( '#pays' ).val(),
1188
		'commune_nom'        : $( '#commune-nom' ).val(),
1189
		'commune_code_insee' : $( '#commune-insee' ).val(),
1190
		'latitude'           : $( '#latitude' ).val(),
1191
		'longitude'          : $( '#longitude' ).val(),
1192
		'altitude'           : $( '#altitude' ).val(),
1193
// début valeurs pour test:
1194
		// 'commune_nom'        : 'Montpellier',
1195
		// 'commune_code_insee' : '34172',
1196
		// 'latitude'           : '43.608320',
1197
		// 'longitude'          : '3.880196',
1198
		// 'altitude'           : '0',
1199
//fin valeurs pour test
1200
		'lieudit'            : $( '#lieudit' ).val(),
1201
		'station'            : $( '#station' ).val(),
1202
		'milieu'             : $( '#milieu' ).val(),
1203
		//Ajout des champs images
1204
		'image_nom'          : lthis.getNomsImgsOriginales(),
1205
		'image_b64'          : lthis.getB64ImgsOriginales(),
1206
		// Ajout des champs étendus de l'obs
1207
		'obs_etendue'        : lthis.getObsChpEtendus()
1208
	});
1209
};
3208 idir 1210
 
3260 idir 1211
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1212
	var noms = new Array();
1213
	$( '.miniature-img' ).each( function() {
1214
		noms.push( $( this ).attr( 'alt' ) );
1215
	});
1216
	return noms;
3208 idir 1217
};
1218
 
3260 idir 1219
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1220
	var b64 = new Array();
1221
	$( '.miniature-img' ).each( function() {
1222
		if ( $( this ).hasClass( 'b64' ) ) {
1223
			b64.push( $( this ).attr( 'src' ) );
1224
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1225
			b64.push( $( this ).data( 'b64' ) );
1226
		}
1227
	});
1228
	return b64;
3208 idir 1229
};
1230
 
3260 idir 1231
/**
1232
 * Retourne un Array contenant les valeurs des champs étendus
1233
 */
1234
WidgetSaisie.prototype.getObsChpEtendus = function() {
1235
	var champs    = new Array(),
1236
			$thisForm = $( '#form-supp' ),
1237
			elements  =
1238
				'input[type=text]:not(.collect-other),'+
1239
				'input[type=checkbox]:checked,'+
1240
				'input[type=radio]:checked,'+
1241
				'input[type=email],'+
1242
				'input[type=number],'+
1243
				'input[type=range],'+
1244
				'input[type=date],'+
1245
				'textarea,'+
1246
				'.select',
1247
			retour    = new Array();
3208 idir 1248
 
3260 idir 1249
	$( elements, $thisForm ).each( function() {
1250
		if ( valeurOk( $( this ).val() ) && ( valeurOk( $( this ).attr( 'name' ) ) || valeurOk( $( this ).data( 'name' ) ) ) ) {
1251
			var valeur = $( this ).val(),
1252
					cle    = ( valeurOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
1253
			if ( cle in champs ) {
1254
				champs[cle] += ';' + valeur;
1255
			} else {
1256
				champs[cle] = valeur;
1257
			}
1258
		}
1259
	});
1260
	for( var key in champs ) {
1261
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
1262
	};
1263
	return retour;
3208 idir 1264
};
1265
 
3260 idir 1266
/**
1267
 * Efface toutes les miniatures (formulaire)
1268
 */
1269
WidgetSaisie.prototype.supprimerMiniatures = function() {
3271 idir 1270
	// Déconnection MutationObserver miniatures
1271
	// Sinon on a une erreur avant la création d'une nouvelle obs
1272
	this.observer.disconnect();
3260 idir 1273
	$( '#miniatures' ).empty();
3271 idir 1274
	// la validation miniatures reprend à 0 pour une nouvelle obs
1275
	this.surPresenceAbsenceMiniature();
3260 idir 1276
	$( '#miniature-msg' ).empty();
3208 idir 1277
};
1278
 
3260 idir 1279
WidgetSaisie.prototype.surChangementNbreObs = function() {
1280
	if ( 0 === this.obsNbre ) {
1281
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1282
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1283
		$( '#transmettre-obs' ).removeAttr( 'disabled' );
1284
		$( '#ajouter-obs' ).removeAttr( 'disabled' );
1285
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1286
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1287
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1288
	}
3208 idir 1289
};
1290
 
3260 idir 1291
WidgetSaisie.prototype.defilerMiniatures = function( element ) {
3208 idir 1292
 
3260 idir 1293
	var miniatureSelectionne = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1294
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1295
	miniatureSelectionne.addClass( 'miniature-cachee' );
3208 idir 1296
 
3260 idir 1297
	var miniatureAffichee    = miniatureSelectionne;
3208 idir 1298
 
3260 idir 1299
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1300
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1301
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1302
		} else {
1303
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1304
		}
1305
	} else {
1306
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1307
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1308
		} else {
1309
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1310
		}
1311
	}
1312
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1313
	miniatureAffichee.removeClass( 'miniature-cachee' );
1314
};
3208 idir 1315
 
3260 idir 1316
WidgetSaisie.prototype.supprimerObs = function( selector ) {
1317
	var obsId = $( selector ).val();
1318
	// Problème avec IE 6 et 7
1319
	if ( 'Supprimer' === obsId ) {
1320
		obsId = $( selector ).attr( 'title' );
1321
	}
1322
	this.supprimerObsParId( obsId );
3208 idir 1323
};
1324
 
3260 idir 1325
WidgetSaisie.prototype.supprimerObsParId = function( obsId ) {
1326
	this.obsNbre = this.obsNbre - 1;
1327
	$( '.obs-nbre' ).text( this.obsNbre );
1328
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1329
	$( '.obs' + obsId ).remove();
1330
	$( '#liste-obs' ).removeData( 'obsId' + obsId );
1331
};
3208 idir 1332
 
3260 idir 1333
WidgetSaisie.prototype.transmettreObs = function() {
1334
	var observations = $( '#liste-obs' ).data();
1335
	if ( this.debug ) {
1336
		console.log( observations );
1337
	}
1338
	if ( !valeurOk( typeof observations, true, 'object' ) ) {
1339
		this.afficherPanneau( '#dialogue-zero-obs' );
1340
	} else {
1341
		this.nbObsEnCours = 1;
1342
		this.nbObsTransmises = 0;
1343
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1344
			return i;
1345
		}).length;
1346
		this.depilerObsPourEnvoi();
1347
	}
1348
	return false;
1349
};
3208 idir 1350
 
3260 idir 1351
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
1352
	var observations = $( '#liste-obs' ).data();
1353
	// la boucle est factice car on utilise un tableau
1354
	// dont on a besoin de n'extraire que le premier élément
1355
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1356
	// TODO: utiliser var.keys quand ça sera plus répandu
1357
	// ou bien utiliser un vrai tableau et pas un objet
1358
	for ( var obsNum in observations ) {
1359
		var obsATransmettre = {
1360
			'projet'  : this.tagProjet,
1361
			'tag-obs' : this.tagObs,
1362
			'tag-img' : this.tagImg
1363
		};
1364
		var utilisateur = {
1365
			id_utilisateur : $( '#id_utilisateur' ).val(),
1366
			prenom         : $( '#prenom' ).val(),
1367
			nom            : $( '#nom' ).val(),
1368
			courriel       : $( '#courriel' ).val()
1369
		};
1370
		obsATransmettre['utilisateur'] = utilisateur;
1371
		obsATransmettre[obsNum] = observations[obsNum];
1372
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1373
		if( '' !== idObsNumerique ) {
1374
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1375
		}
1376
		break;
1377
	}
1378
};
3208 idir 1379
 
3260 idir 1380
WidgetSaisie.prototype.envoyerObsAuCel = function( idObs, observation ) {
1381
	var lthis = this;
3208 idir 1382
 
3260 idir 1383
	var erreurMsg = '';
1384
	$.ajax({
1385
		url        : lthis.serviceSaisieUrl,
1386
		type       : 'POST',
1387
		data       : observation,
1388
		dataType   : 'json',
1389
		beforeSend : function() {
1390
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1391
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1392
			$( '.alert-txt' ).empty();
1393
			$( '.alert-txt .msg-erreur' ).remove();
1394
			$( '.alert-txt .msg-debug' ).remove();
1395
			$( '#chargement' ).removeClass( 'hidden' );
1396
		},
1397
		success    : function( data, textStatus, jqXHR ) {
1398
			// mise à jour du nombre d'obs à transmettre
1399
			// et suppression de l'obs
1400
			lthis.supprimerObsParId( idObs );
1401
			lthis.nbObsEnCours++;
1402
			// mise à jour du statut
1403
			lthis.mettreAJourProgression();
1404
			if( 0 < lthis.obsNbre ) {
1405
				// dépilement de la suivante
1406
				lthis.depilerObsPourEnvoi();
1407
			}
1408
		},
1409
		statusCode  : {
1410
			500 : function( jqXHR, textStatus, errorThrown ) {
1411
				erreurMsg += lthis.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1412
				}
1413
		},
1414
		error        : function( jqXHR, textStatus, errorThrown ) {
1415
			erreurMsg += lthis.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1416
			try {
1417
				reponse = jQuery.parseJSON( jqXHR.responseText );
1418
				if ( null !== reponse ) {
1419
					$.each( reponse, function( cle, valeur ) {
1420
						erreurMsg += valeur + '\n';
1421
					});
1422
				}
1423
			} catch( e ) {
1424
				erreurMsg += lthis.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1425
			}
1426
		},
1427
		complete      : function( jqXHR, textStatus ) {
1428
			var debugMsg = extraireEnteteDebug( jqXHR );
3208 idir 1429
 
3260 idir 1430
			if ( '' !== erreurMsg ) {
1431
				if ( lthis.debug ) {
1432
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1433
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1434
				}
1435
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1436
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1437
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
3208 idir 1438
 
3260 idir 1439
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1440
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1441
				window.location.hash = 'obs' + idObs;
1442
 
1443
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1444
					$( '#tpl-transmission-ko' ).clone()
1445
						.find( '.courriel-erreur' )
1446
						.attr( 'href', hrefCourriel )
1447
						.end()
1448
						.html()
1449
				);
1450
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1451
				$( '#chargement' ).addClass( 'hidden' );
1452
				lthis.initialiserBarreProgression;
1453
			} else {
1454
				if ( lthis.debug ) {
1455
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1456
				}
1457
				if( 0 === lthis.obsNbre ) {
1458
					setTimeout( function() {
1459
						$( '#chargement' ).addClass( 'hidden' );
1460
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1461
						$( '#dialogue-obs-transaction-ok' ).removeClass( 'hidden' );
1462
						window.location.hash = 'dialogue-obs-transaction-ok';
1463
						lthis.initialiserObs.bind( lthis );
1464
					}, 1500 );
1465
				}
1466
			}
1467
		}
1468
	});
3208 idir 1469
};
1470
 
3260 idir 1471
WidgetSaisie.prototype.mettreAJourProgression = function() {
1472
	this.nbObsTransmises++;
3208 idir 1473
 
3260 idir 1474
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
3208 idir 1475
 
3260 idir 1476
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1477
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1478
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.msgTraduction( 'observations-transmises' ) );
1479
	if( 0 === this.obsNbre ) {
1480
		$( '.progress' ).removeClass( 'active' );
1481
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1482
	}
3120 delphine 1483
};
1484
 
3260 idir 1485
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1486
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1487
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1488
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.msgTraduction( 'observations-transmises' ) );
1489
	$( '.progress' ).addClass( 'active' );
1490
	$( '.progress' ).addClass( 'progress-bar-striped' );
3120 delphine 1491
};
1492
 
3260 idir 1493
WidgetSaisie.prototype.initialiserObs = function() {
1494
	this.obsNbre = 0;
1495
	this.nbObsTransmises = 0;
1496
	this.nbObsEnCours = 0;
1497
	this.totalObsATransmettre = 0;
1498
	this.initialiserBarreProgression();
1499
	$( '.obs-nbre' ).text( this.obsNbre );
1500
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1501
	$( '#liste-obs' ).removeData();
1502
	$( '.obs' ).remove();
1503
	$( '#dialogue-bloquer-creer-obs' ).addClass( 'hidden' );
3120 delphine 1504
};
1505
 
3208 idir 1506
WidgetSaisie.prototype.afficherPanneau = function( selecteur ) {
3260 idir 1507
	$( selecteur )
1508
		.removeClass( 'hidden')
1509
		.hide()
1510
		.show( 600 )
1511
		.delay( this.dureeMessage )
1512
		.hide( 600 );
3120 delphine 1513
};
1514
 
3208 idir 1515
WidgetSaisie.prototype.masquerPanneau = function( selecteur ) {
3260 idir 1516
	$( selecteur ).addClass( 'hidden' );
3208 idir 1517
};
1518
 
3260 idir 1519
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1520
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1521
};
1522
 
3240 idir 1523
/**
1524
 * Si la langue est définie dans this.langue, et si des messages sont définis
1525
 * dans this.msgs, tente de trouver le message dont la clé est [cle] dans la
1526
 * langue en cours. S'il n'est pas trouvé, retourne la version française (par
1527
 * défaut); si celle-ci n'exite pas, retourne "N/A".
1528
 */
1529
WidgetSaisie.prototype.msgTraduction = function( cle ) {
3260 idir 1530
	var msg = 'N/A';
1531
	if ( this.msgs ) {
1532
		if ( this.langue in this.msgs && cle in this.msgs[this.langue] ) {
1533
			msg = this.msgs[this.langue][cle];
1534
		} else if ( cle in this.msgs['fr'] ) {
1535
			msg = this.msgs['fr'][cle];
1536
		}
1537
	}
1538
	return msg;
3240 idir 1539
};
1540
 
3208 idir 1541
// lib hors objet --
1542
 
1543
/**
3260 idir 1544
* Permet à la fois de vérifier qu'une valeur ou objet existe et n'est pas vide
1545
* et de comparer à une autre valeur :
1546
* Vérifie qu'une variable ou objet n'est pas : vide, null, undefined, NaN
1547
* Si comparer est défini on le compare à valeur en fonction de sensComparaison
1548
* Un booléen est une variable valide : on retourne true
1549
* @param { string || number || object || undefined } valeur
1550
* @param { boolean } sensComparaison : true = rechercher, false = refuser
1551
* @param { string || number || object || undefined || boolean } comparer :valeur à comparer
1552
* @returns {boolean}
1553
*/
1554
function valeurOk( valeur, sensComparaison = true, comparer = undefined ) {
1555
 
1556
	if ( 'boolean' !== typeof valeur ) {
1557
		switch( typeof valeur ) {
1558
			case 'string' :
1559
				retour = ( '' !== valeur );
1560
			 break;
1561
			case 'number' :
1562
					retour = ( NaN !== valeur );
1563
				break;
1564
			case 'object' :
1565
					retour = ( null !== valeur && undefined !== valeur && !$.isEmptyObject( valeur ) );
1566
					if ( undefined !== valeur.length ) {
1567
						retour = ( retour  && 0 < valeur.length );
1568
					}
1569
				break;
1570
			case 'undefined' :
1571
			default :
1572
				retour = false;
1573
		}
1574
		if ( retour && comparer !== undefined ) {
1575
			var resultComparaison = ( comparer === valeur );
1576
			retour = ( sensComparaison ) ? resultComparaison : !resultComparaison ;
1577
		}
1578
		return retour;
1579
	} else {
1580
		// Un booléen est une valeur valable
1581
		return true;
1582
	}
1583
}
1584
 
1585
/**
3208 idir 1586
* Stope l'évènement courant quand on clique sur un lien.
1587
* Utile pour Chrome, Safari...
1588
*/
1589
function arreter( evenement ) {
3260 idir 1590
	if ( evenement.stopPropagation ) {
1591
		evenement.stopPropagation();
1592
	}
1593
	if ( evenement.preventDefault ) {
1594
		evenement.preventDefault();
1595
	}
1596
	return false;
3208 idir 1597
}
1598
 
1599
/**
1600
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1601
 * @param jqXHR
1602
 * @returns {String}
1603
 */
1604
function extraireEnteteDebug( jqXHR ) {
3260 idir 1605
	var msgDebug = '';
1606
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1607
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1608
		if ( null !== debugInfos ) {
1609
			$.each( debugInfos, function( cle, valeur ) {
1610
				msgDebug += valeur + '\n';
1611
			});
1612
		}
1613
	}
1614
	return msgDebug;
3208 idir 1615
}
1616
 
1617
/*
1618
 * jQuery UI Autocomplete HTML Extension
1619
 *
1620
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1621
 * Dual licensed under the MIT or GPL Version 2 licenses.
1622
 *
1623
 * http://github.com/scottgonzalez/jquery-ui-extensions
1624
 *
1625
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1626
 */
3260 idir 1627
	( function( $ ) {
1628
		var proto = $.ui.autocomplete.prototype,
1629
			initSource = proto._initSource;
3208 idir 1630
 
3260 idir 1631
		WidgetSaisie.prototype.filter = function( array, term ) {
1632
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1633
			return $.grep( array, function( value ) {
1634
				return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
1635
			});
1636
		}
1637
		$.extend( proto, {
1638
			_initSource: function() {
1639
				if ( this.options.html && $.isArray( this.options.source ) ) {
1640
					this.source = function( request, response ) {
1641
						response( filter( this.options.source, request.term ) );
1642
					};
1643
				} else {
1644
					initSource.call( this );
1645
				}
1646
			},
1647
			_renderItem: function( ul, item) {
1648
				if ( item.retenu ) {
1649
					item.label = '<strong>' + item.label + '</strong>';
1650
				}
3208 idir 1651
 
3260 idir 1652
				return $( '<li></li>' )
1653
					.data( 'item.autocomplete', item )
1654
					.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
1655
					.appendTo( ul );
1656
			}
1657
		});
1658
	})( jQuery );