Subversion Repositories eFlore/Applications.cel

Rev

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