Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3318 idir 1
/**
2
 * Constructeur ReleveLg par défaut
3
 */
4
function ReleveLg() {
5
	this.obsNbre = 0;
6
	this.numArbre = 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.serviceObsListUrl = null;
21
	this.serviceObsImgs = null;
22
	this.serviceObsImgUrl = null;
23
	this.nomSciReferentiel = null;
24
	this.isTaxonListe = false;
25
	this.autocompletionElementsNbre = null;
26
	this.referentielImpose = null;
27
	this.serviceAutocompletionNomSciUrl = null;
28
	this.serviceAutocompletionNomSciUrlTpl = null;
29
	this.obsMaxNbre = null;
30
	this.dureeMessage = null;
31
	this.serviceNomCommuneUrl = null;
32
	this.serviceNomCommuneUrlAlt = null;
33
	this.chargementImageIconeUrl = null;
34
	this.pasDePhotoIconeUrl = null;
35
	this.infosUtilisateur = {};
36
	this.releveDatas = null;
37
	this.utils = new UtilsLg();
38
}
39
 
40
ReleveLg.prototype.init = function() {
41
	this.initForm();
42
	this.initEvts();
43
};
44
 
45
/**
46
 * Initialise le formulaire, les validateurs, les listes de complétion...
47
 */
48
ReleveLg.prototype.initForm = function() {
49
	const lthis = this;
50
	var releveDatas = [];
51
	this.infosUtilisateur.id     = $( '#id_utilisateur' ).val();
52
	this.infosUtilisateur.prenom = $( '#prenom' ).val();
53
	this.infosUtilisateur.nom    = $( '#nom' ).val();
54
 
55
	if( this.utils.valOk( this.infosUtilisateur.id ) ) {
56
		if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
57
			const datRuComun = $.parseJSON( $( '#dates-rues-communes' ).val() );
58
			releveDatas = $.parseJSON( $( '#releve-data' ).val() );
59
 
60
			if ( !this.utils.valOk( releveDatas[1] ) || -1 === datRuComun.indexOf( releveDatas[1]['date_rue_commune'] )  ) {
61
				this.releveDatas = releveDatas;
62
				if ( this.utils.valOk( this.releveDatas[0].utilisateur, true, this.infosUtilisateur.id ) ) {
63
					$( '#releve-date' ).val( this.releveDatas[0].date );
64
					this.rechargerFormulaire();
65
					this.saisirArbres();
66
					$( '#bouton-list-releves' )
67
						.removeClass( 'hidden' )
68
						.click( function() {
69
							$( '#table-releves' ).removeClass( 'hidden' );
70
							$( this ).addClass( 'hidden' );
71
					});
72
				}
73
			}
74
		}
75
		if ( this.utils.valOk( $( '#lg-obs' ).val() ) ) {
76
			const lgObs = $.parseJSON( $( '#lg-obs' ).val() );
77
 
78
			$( '.charger-releve,.saisir-lichens' ).click( function() {
79
				var nomSquelette = $( this ).data( 'load' );
80
				releveDatas = lgObs[ $( this ).data( 'releve' ) ];
81
				$( '#releve-data' ).val( JSON.stringify( releveDatas ) );
82
				lthis.utils.chargerForm( nomSquelette, lthis );
83
				$( '#bouton-list-releves' ).removeClass( 'hidden' );
84
				$( '#table-releves' ).addClass( 'hidden' );
85
			});
86
		}
87
	}
88
	this.ajouterAutocompletionNoms();
89
	this.configurerFormValidator();
90
	this.definirReglesFormValidator();
91
};
92
 
93
/**
94
 * Initialise les écouteurs d'événements
95
 */
96
ReleveLg.prototype.initEvts = function() {
97
	const lthis = this;
98
 
99
	$( '#bouton-nouveau-releve' ).click( function() {
100
		$( '#releve-data' ).val( '' );
101
		if ( lthis.utils.valOk( lthis.infosUtilisateur.id ) ) {
102
			lthis.utils.chargerForm( 'arbres', lthis );
103
			$( 'html, body' ).stop().animate({
104
				scrollTop: $( '#zone-observation' ).offset().top
105
			}, 300 );
106
		}
107
	});
108
 
109
	// Empêcher que le module carto ne bind ses events partout
110
	$( '#tb-geolocation' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '*', function( event ) {
111
		event.preventDefault();
112
		return false;
113
	});
114
	$( '#tb-geolocation' ).on( 'location' , lthis.locationHandler.bind( lthis ) );
115
 
116
	// Sur téléchargement image
117
	$( '#fichier' ).on( 'change', function ( e ) {
118
		arreter( e );
119
 
120
		var options        = {
121
			success: lthis.afficherMiniature.bind( lthis ), // post-submit callback
122
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
123
			resetForm: true // reset the form after successful submit
124
		};
125
 
126
		$( '#miniature' ).append( '<img id="miniature-chargement" class="miniature" alt="chargement" src="' + this.chargementImageIconeUrl + '"/>' );
127
 
128
		var imgCheminTmp    = $( '#fichier' ).val(),
129
			formatImgOk     = lthis.verifierFormat( imgCheminTmp ),
130
			imgNonDupliquee = lthis.verifierDuplication( imgCheminTmp );
131
 
132
		if( formatImgOk && imgNonDupliquee ) {
133
			$( '#form-upload' ).ajaxSubmit( options );
134
		} else {
135
			$( '#form-upload' )[0].reset();
136
			if ( !formatImgOk ) {
137
				window.alert( lthis.utils.msgTraduction( 'format-non-supporte' ) + ' ' + $( '#fichier' ).attr( 'accept' ) );
138
			}
139
			if ( !imgNonDupliquee ) {
140
				window.alert( lthis.utils.msgTraduction( 'image-deja-chargee' ) );
141
			}
142
		}
143
		return false;
144
	});
145
	// Gérer une option "aucune" sur plusieurs checkboxes
146
	$( '#face-ombre input' ).on( 'click', function () {
147
		if ( 'aucune' === $( this ).val() ) {
148
			$( '#face-ombre input' ).not( '#aucune' ).prop( 'checked' , false );
149
		} else {
150
			$( '#aucune' ).prop( 'checked' , false );
151
		}
152
	});
153
	$( 'body' ).on( 'click', '.effacer-miniature', function() {
154
		$( this ).parent().remove();
155
	});
156
 
157
	$( '#soumettre-releve' ).on( 'click', function( even ) {
158
		event.preventDefault();
159
		lthis.saisirArbres();
160
	});
161
	$( '#ajouter-obs' ).on( 'click', this.ajouterObs.bind( this ) );
162
	$( '.obs-nbre' ).on( 'changement', this.surChangementNbreObs.bind( this ) );
163
	$( '#bloc-info-arbres' ).on( 'click', '.arbre-info', function ( event ) {
164
		event.preventDefault();
165
		$( this ).addClass( 'disabled' );
166
		$( '.arbre-info' ).not( $( this ) ).removeClass( 'disabled' );
167
		var numArbre = $( this ).data( 'arbre-info' );
168
		lthis.chargerInfosArbre( numArbre );
169
	});
170
	// après avoir visualisé les champs d'un arbre, retour à la saisie
171
	$( '#retour' ).on( 'click', function( event ) {
172
		event.preventDefault();
173
		var numArbre = lthis.numArbre + 1;
174
		$( 'html, body' ).stop().animate({
175
			scrollTop: $( '#zone-arbres' ).offset().top
176
		}, 300);
177
		// activation des champs et retour à la saisie
178
		lthis.modeArbresBasculerActivation( false, numArbre );
179
	});
180
	// défilement des miniatures dans le résumé obs
181
	$( 'body' ).on( 'click', '.defilement-miniatures-gauche', function( event ) {
182
		event.preventDefault();
183
		lthis.defilerMiniatures( $( this ) );
184
	});
185
	$( 'body' ).on( 'click', '.defilement-miniatures-droite', function( event ) {
186
		event.preventDefault();
187
		lthis.defilerMiniatures( $( this ) );
188
	});
189
	// mécanisme de suppression d'une obs
190
	$( '#liste-obs' ).on( 'click', '.supprimer-obs', function() {
191
		var that = this,
192
		suppObs = lthis.supprimerObs.bind( lthis );
193
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
194
		suppObs( that );
195
	});
196
 
197
	$( '#transmettre-obs' ).on( 'click', this.transmettreObs.bind( this ) );
198
 
199
	// chargement lichens
200
	$( '#charger-form' ).on( 'click', '#bouton-saisir-lichens', function() {
201
		var nomSquelette = $( this ).data( 'load' );
202
		$( '#charger-form' ).data( 'load', nomSquelette );
203
		lthis.utils.chargerForm( nomSquelette, lthis );
204
		$( 'html, body' ).stop().animate({
205
			scrollTop: $( '#charger-form' ).offset().top
206
		}, 300 );
207
	});
208
 
209
	// Alertes et tooltips
210
	$( '.alert .close' ).on( 'click', this.fermerPanneauAlert );
211
	$( '#btn-aide' ).on( 'click', this.basculerAffichageAide );
212
	// $( '.has-tooltip' ).tooltip( 'enable' );
213
};
214
 
215
// Préchargement des infos-obs ************************************************/
216
 
217
/**
218
 * Callback dans le chargement du formulaire dans #charger-form
219
 */
220
ReleveLg.prototype.chargerSquelette = function( squelette, nomSquelette ) {
221
	switch( nomSquelette ) {
222
		case 'lichens' :
223
			this.utils.chargerFormLichens( squelette, nomSquelette );
224
			break;
225
		case 'arbres' :
226
		default :
227
			this.reinitialiserWidget( squelette );
228
		break;
229
	}
230
};
231
 
232
ReleveLg.prototype.reinitialiserWidget = function( squelette ) {
233
	$( '#charger-form' ).html( squelette );
234
	if ( this.utils.valOk( $( '#releve-data' ).val() ) ) {
235
		this.rechargerFormulaire();
236
	}
237
};
238
 
239
/**
240
 * Recharge le formulaire relevé (étape 1) à partir des infos
241
 * présentes dans l'input hidden '#releve-data'
242
 */
243
ReleveLg.prototype.rechargerFormulaire = function() {
244
	const lthis = this;
245
 
246
	this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
247
	$.each( this.releveDatas[0], function( cle , valeur ) {
248
		if ( lthis.utils.valOk( $( '#' + cle ) ) ) {
249
			$( '#' + cle ).val( valeur );
250
		}
251
	});
252
 
253
	$( 'html, body' ).stop().animate({
254
		scrollTop: $( '#charger-form' ).offset().top
255
	}, 300, function() {
256
		$( '#releve-date' ).focus();
257
	});
258
	if (
259
		this.utils.valOk( $( '#latitude' ).val() ) &&
260
		this.utils.valOk( $( '#longitude' ).val() ) &&
261
		this.utils.valOk( $( '#rue' ).val() ) &&
262
		this.utils.valOk( $( '#commune-nom' ).val() )
263
	) {
264
		$( '#geoloc' ).addClass( 'hidden' );
265
		$( '#geoloc-datas' ).removeClass( 'hidden' );
266
	}
267
};
268
 
269
/**
270
 * Recharge le formulaire étape arbres à partir des infos
271
 * présentes dans l'input hidden '#releve-data'
272
 */
273
ReleveLg.prototype.chargerArbres = function() {
274
	this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
275
	this.obsNbre     = this.releveDatas.length - 1;
276
	this.numArbre    = parseInt( this.releveDatas[ this.obsNbre ]['num-arbre'] ) || this.obsNbre;
277
	$( '.obs-nbre' ).text( this.obsNbre );
278
	$( '.obs-nbre' ).triggerHandler( 'changement' );
279
	$( '#arbre-nb' ).text( this.numArbre + 1 );
280
 
281
	var infosArbre = {
282
		releve : this.releveDatas[0],
283
		obsNum : 0,
284
		arbre  : {}
285
	};
286
 
287
	for( var i = 1; i <= this.obsNbre; i ++ ) {
288
		infosArbre.obsNum = i;
289
		infosArbre.arbre = this.releveDatas[i];
290
		this.lienArbreInfo( infosArbre.arbre['num-arbre'] );
291
		this.afficherObs( infosArbre );
292
		this.stockerObsData( infosArbre, true );
293
	}
294
};
295
 
296
ReleveLg.prototype.lienArbreInfo = function( numArbre ) {
297
	$( '#bloc-info-arbres' ).append(
298
		'<div'+
299
			' id="arbre-info-' + numArbre + '"'+
300
			' class="col-sm-8"'+
301
		'>'+
302
			'<a'+
303
				' id="arbre-info-lien-' + numArbre + '"'+
304
				' href=""'+
305
				' class="arbre-info btn btn-outline-info btn-block mb-3"'+
306
				' data-arbre-info="' + numArbre + '"'+
307
			'>'+
308
				'<i class="fas fa-info-circle"></i>'+
309
				' Arbre ' + numArbre +
310
			'</a>'+
311
		'</div>'
312
	);
313
};
314
 
315
 
316
 
317
// Autocompletion taxons ******************************************************/
318
/**
319
 * Initialise l'autocompletion taxons
320
 */
321
ReleveLg.prototype.ajouterAutocompletionNoms = function() {
322
	const lthis = this;
323
 
324
	$( '#taxon' ).autocomplete({
325
		source: function( requete, add ) {
326
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
327
			requete = '';
328
			if( lthis.utils.valOk( $( '#referentiel' ).val(), false, 'autre' ) ) {
329
				var url = lthis.getUrlAutocompletionNomsSci();
330
				$.getJSON( url, requete, function( data ) {
331
					var suggestions = lthis.traiterRetourNomsSci( data );
332
					add( suggestions );
333
				})
334
				.fail( function() {
335
					$( '#certitude' ).find( 'option' ).each( function() {
336
						if ( $( this ).hasClass( 'aDeterminer' ) ) {
337
							$( this ).attr( 'selected', true );
338
						} else {
339
							$( this ).attr( 'selected', false );
340
						}
341
					});
342
				});
343
			}
344
		},
345
		html: true
346
	});
347
	$( '#taxon' ).on( 'autocompleteselect', this.surAutocompletionTaxon );
348
};
349
 
350
ReleveLg.prototype.getUrlAutocompletionNomsSci = function() {
351
	var mots = $( '#taxon' ).val();
352
	var url = this.serviceAutocompletionNomSciUrlTpl.replace( '{referentiel}', this.nomSciReferentiel );
353
	url = url.replace( '{masque}', mots );
354
 
355
	return url;
356
};
357
 
358
/**
359
 * Objet taxons pour autocompletion en fonction de la recherche
360
 */
361
ReleveLg.prototype.traiterRetourNomsSci = function( data ) {
362
	var suggestions = [];
363
 
364
	if ( undefined != data.resultat ) {
365
		$.each( data.resultat, function( i, val ) {
366
			val.nn = i;
367
 
368
			var nom = {
369
				label : '',
370
				value : '',
371
				nt : 0,
372
				nomSel : '',
373
				nomSelComplet : '',
374
				numNomSel : 0,
375
				nomRet : '',
376
				numNomRet : 0,
377
				famille : '',
378
				retenu : false
379
			};
380
			if ( suggestions.length >= this.autocompletionElementsNbre ) {
381
				nom.label = '...';
382
				nom.value = $( '#taxon' ).val();
383
				suggestions.push( nom );
384
				return false;
385
			} else {
386
				nom.label = val.nom_sci_complet;
387
				nom.value = val.nom_sci_complet;
388
				nom.nt = val.num_taxonomique;
389
				nom.nomSel = val.nom_sci;
390
				nom.nomSelComplet = val.nom_sci_complet;
391
				nom.numNomSel = val.nn;
392
				nom.nomRet = val.nom_retenu_complet;
393
				nom.numNomRet = val['nom_retenu.id'];
394
				nom.famille = val.famille;
395
				// Tester dans ce sens, permet de considérer 'absent' comme 'false' => est-ce opportun ?
396
				// en tout cas c'est harmonisé avec le CeL
397
				nom.retenu = ( 'true' == val.retenu );
398
				suggestions.push( nom );
399
			}
400
		});
401
	}
402
	return suggestions;
403
};
404
 
405
/**
406
 * charge les données dans #taxon
407
 */
408
ReleveLg.prototype.surAutocompletionTaxon = function( event, ui ) {
409
	const utils = new UtilsLg();
410
 
411
	if ( utils.valOk( ui ) ) {
412
		$( '#taxon' ).val( ui.item.value );
413
		$( '#taxon' ).data( 'value', ui.item.value )
414
			.data( 'numNomSel', ui.item.numNomSel )
415
			.data( 'nomRet', ui.item.nomRet )
416
			.data( 'numNomRet', ui.item.numNomRet )
417
			.data( 'nt', ui.item.nt )
418
			.data( 'famille', ui.item.famille );
419
		if ( ui.item.retenu ) {
420
			$( '#taxon' ).addClass( 'ns-retenu' );
421
		} else {
422
			$( '#taxon' ).removeClass( 'ns-retenu' );
423
		}
424
		// Si l'espèce est mal déterminée la certitude est "à déterminer"
425
		if( !utils.valOk( $( '#taxon' ).data( 'numNomSel' ) ) ) {
426
			$( '#certitude' ).find( 'option' ).each( function() {
427
				if ( $( this ).hasClass( 'aDeterminer' ) ) {
428
					$( this ).attr( 'selected', true );
429
				} else {
430
					$( this ).attr( 'selected', false );
431
				}
432
			});
433
		}
434
	}
435
	$( '#taxon' ).change();
436
};
437
 
438
// Referentiel ****************************************************************/
439
// N'est pas utilisé en cas de taxon-liste
440
ReleveLg.prototype.surChangementReferentiel = function() {
441
	this.nomSciReferentiel = $( '#referentiel' ).val();
442
	//réinitialise taxon.val
443
	$( '#taxon' ).val( '' );
444
	$( '#taxon' ).data( 'numNomSel', '' );
445
};
446
 
447
// Fichier Images *************************************************************/
448
/**
449
 * Affiche temporairement (formulaire)
450
 * la miniature d'une image ajoutée à l'obs
451
 */
452
ReleveLg.prototype.afficherMiniature = function( reponse ) {
453
	if ( this.debug ) {
454
		var debogage = $( 'debogage', reponse ).text();
455
	}
456
 
457
	var message = $( 'message', reponse ).text();
458
 
459
	if ( this.utils.valOk( message ) ) {
460
		$( '#miniature-msg' ).append( message );
461
	} else {
462
		$( '#miniatures' ).append( this.creerWidgetMiniature( reponse ) );
463
	}
464
	$( '#ajouter-obs' ).removeAttr( 'disabled' );
465
};
466
 
467
/**
468
 * Crée la miniature temporaire (formulaire) + bouton pour l'effacer
469
 */
470
ReleveLg.prototype.creerWidgetMiniature = function( reponse ) {
471
	var miniatureUrl = $( 'miniature-url', reponse ).text();
472
	var imgNom = $( 'image-nom', reponse ).text();
473
	var html =
474
		'<div class="miniature mb-3 mr-3">'+
475
			'<img class="miniature-img" class="miniature img-rounded" alt="' + imgNom + '" src="' + miniatureUrl + '"/>'+
476
			'<a class="effacer-miniature"><i class="fas fa-times"></i></a>'+
477
		'</div>';
478
 
479
	return html;
480
};
481
 
482
/**
483
 * Retourne true si l'extension de l'image 'nom' est .jpg ou .jpeg
484
 */
485
ReleveLg.prototype.verifierFormat = function( cheminTmp ) {
486
	var parts     = cheminTmp.split( '.' ),
487
		extension = parts[ parts.length - 1 ];
488
 
489
	return ( 'jpeg' === extension.toLowerCase() || 'jpg' === extension.toLowerCase() );
490
};
491
 
492
/**
493
 * Check les miniatures déjà téléchargées
494
 * renvoie false si le même nom est rencontré 2 fois
495
 * renvoie true sinon
496
 */
497
ReleveLg.prototype.verifierDuplication = function( cheminTmp ) {
498
	const lthis = this;
499
	var parts        = cheminTmp.split( '\\' ),
500
		nomImage     = parts[ parts.length - 1 ],
501
		thisSrcParts = [],
502
		thisNomImage = '',
503
		nonDupliquee = true;
504
 
505
	$( 'img.miniature-img,img.miniature' ).each( function() {
506
		// vérification avec alt de l'image
507
		if ( lthis.utils.valOk ( $( this ).attr ( 'alt' ), true, nomImage ) ) {
508
			nonDupliquee = false;
509
			return false;// Pas besoin de poursuivre la boucle
510
		} else { // sinon vérifie aussi avec l'adresse (src) de l'image
511
			thisSrcParts = $( this ).attr( 'src' ).split( '/' );
512
			thisNomImage = thisSrcParts[ thisSrcParts.length - 1 ].replace( '_min', '' );
513
			if ( lthis.utils.valOk ( thisNomImage, true, nomImage ) ) {
514
				nonDupliquee = false;
515
				return false;
516
			}
517
		}
518
	});
519
	return nonDupliquee;
520
};
521
 
522
/**
523
 * Efface une miniature (formulaire)
524
 */
525
ReleveLg.prototype.supprimerMiniature = function( miniature ) {
526
	miniature.parents( '.miniature' ).remove();
527
};
528
 
529
// Ajouter Obs ****************************************************************/
530
 
531
/**
532
 * Etape formulaire avec transfert carto
533
 */
534
ReleveLg.prototype.saisirArbres = function() {
535
	const lthis = this;
536
 
537
	if ( this.validerReleve() ) {
538
		$( '#soumettre-releve' )
539
			.addClass( 'disabled' )
540
			.attr( 'aria-disabled', true )
541
			.off( event );
542
		$( '#form-observation' ).find( 'input, textarea' ).prop( 'disabled', true );
543
		$( '#zone-arbres,#geoloc-datas' ).removeClass( 'hidden' );
544
		if ( !this.utils.valOk( $( '#releve-data' ).val() ) ) {
545
			this.releveDatas = this.utils.formaterReleveData({
546
				obs  : {
547
					ce_utilisateur     : this.infosUtilisateur.id,
548
					date_observation   : $( '#releve-date' ).val(),
549
					zone_geo           : $( '#commune-nom' ).val(),
550
					ce_zone_geo        : $( '#commune-insee' ).val(),
551
					pays               : $( '#pays' ).val(),
552
					latitude           : $( '#latitude' ).val(),
553
					longitude          : $( '#longitude' ).val(),
554
					altitude           : $( '#altitude' ).val(),
555
					commentaire        : $( '#commentaires' ).val().trim()
556
				},
557
				obsE : {
558
					rue                : $( '#rue' ).val()
559
				}
560
			});
561
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
562
			this.numArbre = this.releveDatas.length - 1;
563
		} else {
564
			this.releveDatas = $.parseJSON( $( '#releve-data' ).val() );
565
			this.releveDatas[0].date                = $( '#releve-date' ).val();
566
			this.releveDatas[0].commentaires        = $( '#commentaires' ).val().trim();
567
			for ( var i = 1 ; i < this.releveDatas.length; i++ ) {
568
				this.releveDatas[i]['date_rue_commune'] = (
569
					this.releveDatas[0].date +
570
					this.releveDatas[0].rue +
571
					this.releveDatas[0]['commune-nom']
572
				);
573
			}
574
			$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
575
			//charger les images
576
			this.chargerImgEnregistrees();
577
			this.numArbre = $.parseJSON( $( '#releve-data' ).val() ).length - 1;
578
		}
579
 
580
		// transfert carto
3325 idir 581
		$( '#tb-geolocation' ).remove();
3318 idir 582
		$( '#geoloc-arbres' ).append(
583
			'<tb-geolocation-element'+
584
				' id="tb-geolocation-arbres"'+
585
				' layer="osm"'+
586
				' zoom_init="20"'+
587
				' lat_init="' + $( '#latitude' ).val() + '"'+
588
				' lng_init="' + $( '#longitude' ).val() + '"'+
589
				' marker="true"'+
590
				' polyline="false"'+
591
				' polygon="false"'+
592
				' show_lat_lng_elevation_inputs="true"'+
593
				' osm_class_filter=""'+
594
				' elevation_provider="mapquest"'+
595
				' map_quest_api_key="mG6oU5clZHRHrOSnAV0QboFI7ahnGg34"'+
596
			'>'+
597
			'</tb-geolocation-element>'
598
		);
599
		// Empêcher que le module carto ne bind ses events partout
600
		$( '#tb-geolocation-arbres' ).on( 'submit blur click focus mousedown mouseleave mouseup touchend touchstart change', '*', function( event ) {
601
			event.preventDefault();
602
			return false;
603
		});
3325 idir 604
		$( '#tb-geolocation-arbres' ).on( 'location', this.locationArbresHandler.bind(this) );
3318 idir 605
	}
606
};
607
 
608
ReleveLg.prototype.chargerImgEnregistrees = function() {
609
	const releveL = this.releveDatas.length;
610
	var idArbre = 0,
611
		last  = false;
612
 
613
	for ( var i = 1; i < releveL; i++ ) {
614
		idArbre = this.releveDatas[i]['id_observation'];
615
 
616
		var urlImgObs = this.serviceObsImgs + idArbre,
617
			imgDatas  = {
618
				'indice'      : i,
619
				'idArbre'     : idArbre,
620
				'numArbre'    : this.releveDatas[i]['num-arbre'],
621
				'nomRet'      : this.releveDatas[i].taxon.nomRet.replace( /\s/, '_' ),
622
				'releveDatas' : this.releveDatas
623
			};
624
 
625
		if ( ( releveL - 1) === i ) {
626
			last = true;
627
		}
628
		this.chargerImgArbre( urlImgObs, imgDatas, last );
629
	}
630
};
631
 
632
ReleveLg.prototype.chargerImgArbre = function( urlImgObs, imgDatas, last ) {
633
	const lthis   = this;
634
 
635
	$.ajax({
636
		url: urlImgObs,
637
		type: 'GET',
638
		success: function( idsImg, textStatus, jqXHR ) {
639
			if ( lthis.utils.valOk( idsImg ) ) {
640
				var urlImg   = '',
641
					images   = [];
642
 
643
				idsImg = idsImg[parseInt( imgDatas.idArbre )];
644
				$.each( idsImg, function( i, idImg ) {
645
					urlImg = lthis.serviceObsImgUrl.replace( '{id}', idImg );
646
					images[i] = {
647
						nom : imgDatas.nomRet + '_arbre'+ imgDatas.numArbre +'_image' + ( i + 1 ),
648
						src : urlImg,
649
						b64 :[],
650
						id  : idImg
651
					};
652
				});
653
				imgDatas.releveDatas[imgDatas.indice]['miniature-img'] = images;
654
				$( '#releve-data' ).val( JSON.stringify( imgDatas.releveDatas ) );
655
				// dejsonifier releve data
656
				// mettre l'array image dans miniature(s?)-img
657
			} else {
658
				console.log( lthis.utils.msgTraduction( 'erreur-image' ) + ' : ' + lthis.utils.msgTraduction( 'arbre' ) + ' ' + imgDatas.idArbre );
659
			}
660
		},
661
		error: function( jqXHR, textStatus, errorThrown ) {
662
			console.log( lthis.utils.msgTraduction( 'erreur-image' ) );
663
		}
664
	})
665
	.always( function() {
666
		if (last) {
667
			lthis.chargerArbres();
668
		}
669
	});
670
};
671
 
672
/**
673
 * Fonction handler de l'évenement location du module tb-geoloc
674
 */
675
ReleveLg.prototype.locationHandler = function( location ) {
3334 idir 676
	const lthis = this;
3328 idir 677
	var locDatas = location.originalEvent.detail;
3318 idir 678
 
679
	if ( this.utils.valOk( locDatas ) ) {
3325 idir 680
		console.log( locDatas );
3328 idir 681
 
3318 idir 682
		var rue          = ( this.utils.valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
3328 idir 683
		var altitude     = ( this.utils.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
684
		var pays         = ( this.utils.valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR';
685
		var latitude     = '';
686
		var longitude    = '';
3318 idir 687
		var nomCommune   = '';
688
		var	communeInsee = '';
689
 
3328 idir 690
		if ( this.utils.valOk( locDatas.geometry.coordinates ) ) {
691
			if ( 'Point' === locDatas.geometry.type ) {
692
				if ( this.utils.valOk( locDatas.geometry.coordinates[0] ) ) {
693
					longitude = locDatas.geometry.coordinates[0];
694
				}
695
				if ( this.utils.valOk( locDatas.geometry.coordinates[1] ) ) {
696
					latitude = locDatas.geometry.coordinates[1];
697
				}
698
			} else if ( 'LineString' === locDatas.geometry.type ) {// on a besoin que d'un point de la rue
699
				if ( this.utils.valOk( locDatas.geometry.coordinates[0][0] ) ) {
700
					longitude = locDatas.geometry.coordinates[0][0];
701
				}
702
				if ( this.utils.valOk( locDatas.geometry.coordinates[0][1] ) ){
703
					latitude = locDatas.geometry.coordinates[0][1];
704
				}
705
			}
706
		}
3318 idir 707
		if ( this.utils.valOk( locDatas.inseeData ) ) {
708
			nomCommune = locDatas.inseeData.nom;
709
			communeInsee = ( this.utils.valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
710
		} else if ( this.utils.valOk( locDatas.locality ) ) {
711
			nomCommune = locDatas.locality;
3334 idir 712
		} else if ( this.utils.valOk( locDatas.osmCounty ) ) {
3318 idir 713
			nomCommune = locDatas.osmCounty;
714
		}
3325 idir 715
		$( '#rue' ).val( rue );
716
		$( '#latitude' ).val( latitude );
717
		$( '#longitude' ).val( longitude );
718
		$( '#commune-nom' ).val( nomCommune );
719
		$( '#commune-insee' ).val( communeInsee );
720
		$( '#altitude' ).val( altitude );
721
		$( '#pays' ).val( pays );
722
		if ( this.utils.valOk( $( '#rue' ).val() ) && this.utils.valOk( $( '#commune-nom' ).val() ) ) {
3318 idir 723
			$( '#geoloc-error' ).addClass( 'hidden' );
724
		} else {
3334 idir 725
			$( '#geoloc' ).addClass( 'hidden' );
726
			$( '#rue,#commune-nom' ).prop( 'disabled', false );
727
			$( '#geoloc-datas' ).removeClass( 'hidden' );
728
			$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 729
			$( '#geoloc-error' ).removeClass( 'hidden' );
730
			$( '#releve-date' ).removeClass( 'erreur' ).closest( '.control-group' ).removeClass( 'error' ).find( '#error-drc' ).remove();
731
		}
3334 idir 732
		$( '#rue,#commune-nom' ).change( function() {
733
			if ( lthis.utils.valOk( $( '#rue' ).val() ) && lthis.utils.valOk( $( '#commune-nom' ).val() ) ) {
734
				$( '#geoloc-error' ).addClass( 'hidden' );
735
			} else {
736
				$( '#geoloc-error' ).removeClass( 'hidden' );
737
			}
738
		});
3318 idir 739
	} else {
740
		console.log( 'Error location' );
741
	}
742
}
743
 
744
/**
3325 idir 745
 * Fonction handler de l'évenement location du module tb-geoloc étape arbres
746
 */
747
ReleveLg.prototype.locationArbresHandler = function( location ) {
3328 idir 748
	var locDatas = location.originalEvent.detail;
3325 idir 749
 
750
	if ( this.utils.valOk( locDatas ) ) {
751
		console.log( locDatas );
3328 idir 752
 
3325 idir 753
		var rue          = ( this.utils.valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
754
		var altitude     = ( this.utils.valOk( locDatas.elevation ) ) ? locDatas.elevation : '';
3328 idir 755
		var latitude     = '';
756
		var longitude    = '';
3325 idir 757
 
3328 idir 758
		if ( this.utils.valOk( locDatas.geometry.coordinates ) ) {
759
			if ( 'Point' === locDatas.geometry.type ) {
760
				if ( this.utils.valOk( locDatas.geometry.coordinates[0] ) ) {
761
					longitude = locDatas.geometry.coordinates[0];
762
				}
763
				if ( this.utils.valOk( locDatas.geometry.coordinates[1] ) ) {
764
					latitude = locDatas.geometry.coordinates[1];
765
				}
766
			} else if ( 'LineString' === locDatas.geometry.type ) {// on a besoin que d'un point de la rue
767
				if ( this.utils.valOk( locDatas.geometry.coordinates[0][0] ) ) {
768
					longitude = locDatas.geometry.coordinates[0][0];
769
				}
770
				if ( this.utils.valOk( locDatas.geometry.coordinates[0][1] ) ){
771
					latitude = locDatas.geometry.coordinates[0][1];
772
				}
773
			}
774
		}
3325 idir 775
		$( '#rue-arbres' ).val( rue );
776
		$( '#latitude-arbres' ).val( latitude );
777
		$( '#longitude-arbres' ).val( longitude );
778
		$( '#altitude-arbres' ).val( altitude );
779
		if ( this.utils.valOk( $( '#latitude-arbres' ).val() ) && this.utils.valOk( $( '#longitude-arbres' ).val() ) ) {
780
			$( '#geoloc-arbres' ).closest( '.control-group' ).removeClass( 'error' );
781
		} else {
782
			$( '#geoloc-arbres' ).closest( '.control-group' ).addClass( 'error' );
783
		}
784
	} else {
785
		console.log( 'Error location' );
786
	}
787
}
788
 
789
/**
3318 idir 790
 * Ajoute une observation à la liste des obs à transmettre
791
 * (résumé obs)
792
 */
793
ReleveLg.prototype.ajouterObs = function() {
794
	// Fermeture automatique des dialogue de transmission de données
795
	// @WARNING TEST
796
	$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
797
	$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
798
	$( 'html, body' ).stop().animate({
799
		scrollTop: $( '#zone-arbres' ).offset().top
800
	}, 300);
801
 
802
	if ( this.validerArbres() ) {
803
		this.masquerPanneau( '#dialogue-form-invalide' );
804
		this.obsNbre  += 1;
805
		this.numArbre += 1;
806
		$( '.obs-nbre' ).text( this.obsNbre );
807
		$( '.obs-nbre' ).triggerHandler( 'changement' );
808
		// bouton info de cet arbre et affichage numéro du prochain arbre
809
		this.lienArbreInfo( this.numArbre );
810
		$( '#arbre-nb' ).text( this.numArbre + 1 );
811
		//formatage des données
812
		var obsData   = this.formaterFormObsData(),
813
			arbreData = obsData.arbre;
814
 
815
		// Résumé obs et stockage en data de "#list-obs" pour envoi
816
		this.afficherObs( obsData );
817
		this.stockerObsData( obsData );
818
		// Ajout de donnée utiles puis stockage dans input hidden "releve-data"
819
		arbreData['date_rue_commune']  = obsData.releve.date + obsData.releve.rue + obsData.releve['commune-nom'];
820
		arbreData['id_observation']    = 0;
821
		this.releveDatas               = $.parseJSON( $( '#releve-data' ).val() );
822
		this.releveDatas[this.obsNbre] = arbreData;
823
		$( '#releve-data' ).val( JSON.stringify( this.releveDatas ) );
3334 idir 824
		this.modeArbresBasculerActivation( false );
3318 idir 825
		$( '#barre-progression-upload' ).attr( 'aria-valuemax', this.obsNbre );
826
		$( '#barre-progression-upload .sr-only' ).text( '0/' + this.obsNbre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
827
	} else {
828
		this.afficherPanneau( '#dialogue-form-invalide' );
829
	}
830
};
831
 
832
/**
833
 * Formatage des données du formulaire pour stockage et envoi
834
 */
835
ReleveLg.prototype.formaterFormObsData = function() {
836
	var miniatureImg  = [],
837
		faceOmbre     = [],
838
		imgB64        = [],
839
		imgNom        = [],
840
		numNomSel     = $( '#taxon' ).data( 'numNomSel' ),
841
		referentiel   = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx';
842
 
843
	$( '.miniature-img' ).each( function() {
844
		if ( $( this ).hasClass( 'b64' ) ) {
845
			imgB64 = $( this ).attr( 'src' );
846
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
847
			imgB64 = $( this ).data( 'b64' );
848
		}
849
		miniatureImg.push({
850
			'nom' : $( this ).attr( 'alt' ),
851
			'src' : $( this ).attr( 'src' ),
852
			'b64' : imgB64
853
		});
854
	});
855
	$( '#face-ombre input' ).each( function() {
856
		if( $( this ).is( ':checked' ) ) {
857
			faceOmbre.push( $( this ).val() );
858
		}
859
	});
860
	var obsData = {
861
		obsNum : this.obsNbre,
862
		arbre  : {
863
			'num-arbre'            : this.numArbre,
864
			'taxon'                : {
865
				'numNomSel' : numNomSel,
866
				'value'     : $( '#taxon' ).val(),
867
				'nomRet'    : $( '#taxon' ).data( 'nomRet' ),
868
				'numNomRet' : $( '#taxon' ).data( 'numNomRet' ),
869
				'nt'        : $( '#taxon' ).data( 'nt' ),
870
				'famille'   : $( '#taxon' ).data( 'famille' )
871
			},
872
			'referentiel'           : referentiel,
873
			'certitude'             : $( '#certitude' ).val(),
3325 idir 874
			'rue-arbres'            : $( '#rue-arbres' ).val(),
3318 idir 875
			'latitude-arbres'       : $( '#latitude-arbres' ).val(),
876
			'longitude-arbres'      : $( '#longitude-arbres' ).val(),
877
			'altitude-arbres'       : $( '#altitude-arbres' ).val(),
3321 idir 878
			'circonference'         : $( '#circonference' ).val(),
3318 idir 879
			'face-ombre'            : faceOmbre,
880
			'com-arbres'            : $( '#com-arbres' ).val(),
881
			'miniature-img'         : miniatureImg,
882
		},
883
		releve : {
884
			'date'                  : this.utils.fournirDate( $( '#releve-date' ).val() ),
885
			'rue'                   : $( '#rue' ).val(),
886
			'commune-nom'           : $( '#commune-nom' ).val(),
887
			'commentaires'          : $( '#commentaires' ).val(),
888
			'pays'                  : $( '#pays' ).val(),
889
			'commune-insee'         : $( '#commune-insee' ).val(),
890
			'latitude'              : $( '#latitude' ).val(),
891
			'longitude'             : $( '#longitude' ).val(),
892
			'altitude'              : $( '#altitude' ).val(),
893
		}
894
	};
895
	return obsData;
896
};
897
 
898
/**
899
 * Résumé obs
900
 */
901
ReleveLg.prototype.afficherObs = function( datasObs ) {
902
	var obsNum            = datasObs.obsNum,
903
		numArbre          = datasObs.arbre['num-arbre'],
904
		dateObs           = this.utils.fournirDate( datasObs.releve.date ),
905
		numNomSel         = datasObs.arbre.taxon.numNomSel,
906
		taxon             = datasObs.arbre.taxon.value,
907
		certitude         = datasObs.arbre.certitude,
3325 idir 908
		rue               = datasObs.arbre['rue-arbres'],
3318 idir 909
		commune           = datasObs.releve['commune-nom'],
910
		latitudeLongitude = '[' + datasObs.arbre['latitude-arbres'] + ' / ' + datasObs.arbre['longitude-arbres'] + ']',
911
		miniatures        = this.ajouterImgMiniatureAuTransfert( datasObs.arbre['miniature-img'] ),
912
		commentaires      = '';
913
 
914
	if ( this.utils.valOk( datasObs.arbre['com-arbres'] ) ) {
915
		commentaires =
916
			this.utils.msgTraduction( 'commentaires' ) +
917
			' : <span>'+
918
				datasObs.arbre['com-arbres'] +
919
			'</span> ';
920
	}
921
 
922
	var responsivDiff1 = '',
923
		responsivDiff2 = '',
924
		responsivDiff3 = '',
925
		responsivDiff4 = '',
926
		responsivDiff5 = '',
927
		responsivDiff6 = '';
928
 
929
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
930
		/* La largeur minimum de l'affichage est 600 px inclus */
931
		responsivDiff1 = ' droite';
932
		responsivDiff2 = '<div></div>';
933
		responsivDiff3 = '<div class="row">';
934
		responsivDiff4 = ' col-md-4 col-sm-5';
935
		responsivDiff5 = ' class="col-md-7 col-sm-6"';
936
		responsivDiff6 = '</div>';
937
	}
938
	$( '#liste-obs' ).prepend(
939
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
940
			'<div '+
941
				'class="obs-action" '+
942
				'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
943
			'>'+
944
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
945
				'<i class="far fa-trash-alt"></i>'+
946
				'</button>'+
947
				responsivDiff2 +
948
			'</div> '+
949
			responsivDiff3 +
950
				'<div class="thumbnail' + responsivDiff4 + '">'+
951
					miniatures+
952
				'</div>'+
953
				'<div' + responsivDiff5 + '>'+
954
					'<ul class="unstyled">'+
955
						'<li>'+
956
							'<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
957
							' <span class="nom-sci">' + taxon + '</span> '+
958
							' [certitude : ' + certitude + ']'+
959
							' '  + this.utils.msgTraduction( 'lieu-obs' ) +
960
							' ' + rue +
961
							', ' + commune +
962
							latitudeLongitude +
963
							' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
964
							'<span class="date">' + this.utils.fournirDate( dateObs ) + '</span>'+
965
						'</li>'+
966
						'<li>'+
967
							commentaires +
968
						'</li>'+
969
					'</ul>'+
970
				'</div>'+
971
			responsivDiff6+
972
		'</div>'
973
	);
974
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
975
};
976
 
977
/**
978
 * Ajoute une boîte de miniatures avec défilement des images,
979
 * pour une obs de la liste des obs à transmettre
980
 */
981
ReleveLg.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages ) {
982
	const lthis = this;
983
	var html         =
984
			'<div class="defilement-miniatures">'+
985
				'<figure class="centre">'+
986
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
987
				'</figure>'+
988
			'</div>',
989
		miniatures   = '',
990
		centre       = '',
991
		defilVisible = '',
992
		length       = 0;
993
 
994
	if ( this.utils.valOk( chargerImages ) || this.utils.valOk( $( '#miniatures img' ) ) ) {
995
		if ( this.utils.valOk( chargerImages ) ) {
996
			$.each(  chargerImages, function( i, value ) {
997
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
998
 
999
				var css        = ( lthis.utils.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
1000
					src        = value.src,
1001
					alt        = value.nom,
1002
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1003
 
1004
				miniatures += miniature;
1005
			});
1006
			length = chargerImages.length;
1007
 
1008
		} else {
1009
			var premiere     = true;
1010
			$( '#miniatures img' ).each( function() {
1011
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
1012
				premiere = false;
1013
 
1014
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
1015
					src        = $( this ).attr( 'src' ),
1016
					alt        = $( this ).attr( 'alt' ),
1017
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
1018
 
1019
				miniatures += miniature;
1020
			});
1021
			length = $( '#miniatures img' ).length;
1022
		}
1023
		if ( 1 === length ) {
1024
			centre       = 'centre';
1025
			defilVisible = ' defilement-miniatures-cache';
1026
		}
1027
		html             =
1028
			'<div class="defilement-miniatures">'+
1029
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1030
				'<figure class="' + centre + '">'+
1031
					miniatures+
1032
				'</figure>'+
1033
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1034
			'</div>';
1035
	}
1036
 
1037
	return html;
1038
};
1039
 
1040
/**
1041
 * Construit le html à afficher pour le numNom
1042
 */
1043
ReleveLg.prototype.ajouterNumNomSel = function( numNomSel ) {
1044
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1045
 
1046
	if ( !this.utils.valOk( numNomSel ) ) {
1047
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1048
	}
1049
 
1050
	return nn;
1051
};
1052
 
1053
/**
1054
 * Stocke des données d'obs à envoyer à la bdd
1055
 */
1056
ReleveLg.prototype.stockerObsData = function( obsDatas ) {
1057
	const lthis = this;
1058
	var obsNum      = obsDatas.obsNum,
1059
		numNomSel   = obsDatas.arbre.taxon.numNomSel,
1060
		referentiel = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx',
1061
		date        = lthis.utils.fournirDate( obsDatas.releve.date ),
1062
		// si releve dupliqué on ne stocke pas l'image :
1063
		stockerImg  = this.utils.valOk( obsDatas.arbre['miniature-img'] ),
1064
		imgNom      = [],
1065
		imgB64      = [];
1066
 
1067
		if( stockerImg ) {
1068
			$.each( obsDatas.arbre['miniature-img'], function( i, obj ) {
1069
				if( obj.hasOwnProperty( 'id' ) ) {
1070
					stockerImg = false;
1071
				}
1072
				return stockerImg;
1073
			});
1074
		}
1075
		if ( stockerImg ) {
1076
			$.each( obsDatas.arbre['miniature-img'] , function(i, value) {
1077
				if( lthis.utils.valOk( value.nom ) ) {
1078
					imgNom.push( value.nom );
1079
				}
1080
				if( lthis.utils.valOk( value['b64'] ) ) {
1081
					imgB64.push( value['b64'] );
1082
				}
1083
			});
1084
		} else {
1085
			imgNom = lthis.getNomsImgsOriginales();
1086
			imgB64 = lthis.getB64ImgsOriginales();
1087
		}
1088
 
1089
	// Stockage en data des données d'obs à transmettre
1090
	$( '#liste-obs' ).data( 'obsId' + obsNum, {
1091
		'num_nom_sel'        : numNomSel,
1092
		'nom_sel'            : obsDatas.arbre.taxon.value,
1093
		'nom_ret'            : obsDatas.arbre.taxon.nomRet,
1094
		'num_nom_ret'        : obsDatas.arbre.taxon.numNomRet,
1095
		'num_taxon'          : obsDatas.arbre.taxon.nt,
1096
		'famille'            : obsDatas.arbre.taxon.famille,
1097
		'referentiel'        : referentiel,
1098
		'certitude'          : obsDatas.arbre.certitude,
1099
		'date'               : date,
1100
		'notes'              : obsDatas.releve.commentaires.trim(),
1101
		'pays'               : obsDatas.releve.pays,
1102
		'commune_nom'        : obsDatas.releve['commune-nom'],
1103
		'commune_code_insee' : obsDatas.releve['commune-insee'],
1104
		'latitude'           : obsDatas.releve.latitude,
1105
		'longitude'          : obsDatas.releve.longitude,
1106
		'altitude'           : obsDatas.releve.altitude,
1107
		//Ajout des champs images
1108
		'image_nom'          : imgNom,
1109
		'image_b64'          : imgB64,
1110
		// Ajout des champs étendus de l'obs
1111
		'obs_etendue'        : lthis.getObsChpArbres( obsDatas )
1112
	});
1113
};
1114
 
1115
ReleveLg.prototype.getNomsImgsOriginales = function() {
1116
	var noms = new Array();
1117
 
1118
	$( '.miniature-img' ).each( function() {
1119
		noms.push( $( this ).attr( 'alt' ) );
1120
	});
1121
 
1122
	return noms;
1123
};
1124
 
1125
ReleveLg.prototype.getB64ImgsOriginales = function() {
1126
	var b64 = new Array();
1127
 
1128
	$( '.miniature-img' ).each( function() {
1129
		if ( $( this ).hasClass( 'b64' ) ) {
1130
			b64.push( $( this ).attr( 'src' ) );
1131
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1132
			b64.push( $( this ).data( 'b64' ) );
1133
		}
1134
	});
1135
 
1136
	return b64;
1137
};
1138
 
1139
/**
1140
 * Retourne un Array contenant les valeurs des champs
1141
 * dont les données seront transmises dans la table cel-obs-etendues
1142
 */
1143
ReleveLg.prototype.getObsChpArbres = function( datasArbres ) {
1144
	const lthis = this;
1145
 
1146
	var retour = [],
1147
		champs = [
1148
			'rue',
3325 idir 1149
			'rue-arbres',
3318 idir 1150
			'latitude-arbres',
1151
			'longitude-arbres',
1152
			'altitude-arbres',
1153
			'circonference',
1154
			'com-arbres'
1155
		];
1156
 
3325 idir 1157
	var faceOmbre       = '',
3318 idir 1158
		faceOmbreLength = datasArbres.arbre['face-ombre'].length;
1159
 
1160
	$.each( champs, function( i ,value ) {
3325 idir 1161
		cleValeur = ( 0 === i ) ? 'releve' : 'arbre';
3318 idir 1162
 
1163
		if ( lthis.utils.valOk( datasArbres[cleValeur][value] ) ) {
1164
			retour.push({ cle : value, valeur : datasArbres[cleValeur][value] });
1165
		}
1166
	});
1167
	if ( 'string' === typeof datasArbres.arbre['face-ombre'] ) {
1168
		faceOmbre = datasArbres.arbre['face-ombre'];
1169
	} else {
1170
		$.each( datasArbres.arbre['face-ombre'], function( i ,value ) {
1171
			faceOmbre += value
1172
			if ( faceOmbreLength > ( i + 1 ) ) {
1173
				faceOmbre += ';';
1174
			}
1175
		});
1176
	}
1177
	retour.push(
1178
		{ cle : 'face-ombre', valeur : faceOmbre },
1179
		{ cle : 'num_arbre' , valeur : datasArbres.obsNum }
1180
	);
1181
 
1182
	var stockerImg  = this.utils.valOk( datasArbres.arbre['miniature-img'] );
1183
 
1184
	if( stockerImg ) {
1185
		$.each( datasArbres.arbre['miniature-img'], function( i, paramsImg ) {
1186
			if( !paramsImg.hasOwnProperty( 'id' ) ) {
1187
				stockerImg = false;
1188
			}
1189
			return stockerImg;
1190
		});
1191
	}
1192
	if( stockerImg ) {
1193
		retour.push({ cle : 'miniature-img' , valeur : JSON.stringify( datasArbres.arbre['miniature-img'] ) });
1194
	}
1195
 
1196
	return retour;
1197
};
1198
 
1199
/**
1200
 * Efface toutes les miniatures (formulaire)
1201
 */
1202
ReleveLg.prototype.supprimerMiniatures = function() {
1203
	$( '#miniatures' ).empty();
1204
	$( '#miniature-msg' ).empty();
1205
};
1206
 
1207
ReleveLg.prototype.surChangementNbreObs = function() {
1208
	if ( 0 === this.obsNbre ) {
1209
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1210
		// $( '#zone-liste-obs' ).addClass( 'hidden' );
1211
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1212
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1213
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1214
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1215
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1216
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1217
		$( '#bloc-form-arbres' ).addClass( 'hidden' );
1218
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1219
	}
1220
};
1221
 
1222
ReleveLg.prototype.chargerInfosArbre = function( numArbre ) {
1223
	const lthis = this;
1224
	var desactiverForm = ( parseInt( numArbre ) !== ( this.numArbre + 1 ) );
1225
 
1226
	if ( desactiverForm ) {
1227
		var releveDatas = $.parseJSON( $( '#releve-data' ).val() ),
1228
			arbreDatas  = releveDatas[numArbre],
1229
			taxon       = {item:{}},
1230
			imgHtml     = '';
1231
 
1232
		$( '#arbre-nb').text( numArbre );
1233
		taxon.item = arbreDatas.taxon;
1234
		this.surAutocompletionTaxon( {}, taxon );
3320 idir 1235
		$.each( 'certitude', function( i, value ) {
3318 idir 1236
			if( !lthis.utils.valOk( arbreDatas[value] ) ) {
1237
				arbreDatas[value] = '';
1238
			}
1239
			$( '#' + value + ' option' ).each( function() {
1240
				if ( arbreDatas[value] === $( this ).val() ) {
1241
					$( this ).prop( 'selected', true );
1242
				} else {
1243
					$( this ).prop( 'selected', false );
1244
				}
1245
			});
1246
		});
3325 idir 1247
		$( '#rue-arbres' ).val(arbreDatas['rue-arbres']);
3318 idir 1248
		$( '#latitude-arbres' ).val(arbreDatas['latitude-arbres']);
1249
		$( '#longitude-arbres' ).val(arbreDatas['longitude-arbres']);
1250
		$( '#altitude-arbres' ).val(arbreDatas['altitude-arbres']);
1251
		// image
1252
		this.supprimerMiniatures();
1253
		$.each( arbreDatas['miniature-img'], function( i, value ) {
1254
			imgHtml +=
1255
			'<div class="miniature mb-3 mr-3">'+
1256
				'<img class="miniature-img" class="miniature img-rounded" alt="' + value.nom + '" src="' + value.src + '"/>'+
1257
			'</div>';
1258
		});
1259
		$( '#miniatures' ).append( imgHtml );
1260
		$( '#circonference' ).val( arbreDatas.circonference );
1261
		$( '#com-arbres' ).val( arbreDatas['com-arbres'] );
1262
		$( '#face-ombre input' ).each( function() {
1263
			if ( -1 < arbreDatas['face-ombre'].indexOf( $( this ).val() ) ) {
1264
				$( this ).prop( 'checked', true );
1265
			} else {
1266
				$( this ).prop( 'checked', false );
1267
			}
1268
		});
1269
	}
1270
	this.modeArbresBasculerActivation( desactiverForm, numArbre );
1271
};
1272
 
1273
ReleveLg.prototype.modeArbresBasculerActivation = function( desactiver, numArbre = 0 ) {
1274
	$(
1275
		'#taxon,'+
1276
		'#certitude,'+
1277
		'#latitude-arbres,'+
1278
		'#longitude-arbres,'+
1279
		'#rue-arbres,'+
1280
		'#fichier,'+
1281
		'#circonference,'+
1282
		'#com-arbres,'+
1283
		'#ajouter-obs'
1284
	).prop( 'disabled', desactiver );
3320 idir 1285
	$( '#face-ombre' ).find( 'input' ).prop( 'disabled', desactiver );
3318 idir 1286
 
1287
	if ( desactiver ) {
1288
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).addClass( 'hidden' );
1289
		$( '#geoloc-datas-arbres,#retour' ).removeClass( 'hidden' );
1290
	} else {
1291
		// quand on change ou qu'on revient à la normale :
1292
		$( '#geoloc-arbres,#bouton-fichier,#miniature-arbres-info' ).removeClass( 'hidden' );
1293
		$( '#geoloc-datas-arbres,#retour' ).addClass( 'hidden' );
3320 idir 1294
		$( '#certitude option' ).each( function() {
3318 idir 1295
			if ( $( this ).hasClass( 'choisir' ) ) {
1296
				$( this ).prop( 'selected', true );
1297
			} else {
1298
				$( this ).prop( 'selected', false );
1299
			}
1300
		});
1301
		this.supprimerMiniatures();
3320 idir 1302
		$( '#face-ombre' ).find( 'input' ).prop( 'checked', false );
3318 idir 1303
		$(
1304
			'#circonference,'+
1305
			'#com-arbres,'+
1306
			'#rue-arbres,'+
1307
			'#latitude-arbres,'+
1308
			'#longitude-arbres,'+
3320 idir 1309
			'#certitude'
3318 idir 1310
		).val( '' );
3334 idir 1311
		if( 0 < numArbre ) {
1312
			$( '#arbre-nb' ).text( numArbre );
1313
			$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1314
			$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1315
		}
3318 idir 1316
	}
1317
};
1318
 
1319
ReleveLg.prototype.defilerMiniatures = function( element ) {
1320
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1321
 
1322
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1323
	miniatureSelectionne.addClass( 'miniature-cachee' );
1324
 
1325
	var miniatureAffichee     = miniatureSelectionne;
1326
 
1327
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1328
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1329
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1330
		} else {
1331
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1332
		}
1333
	} else {
1334
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1335
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1336
		} else {
1337
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1338
		}
1339
	}
1340
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1341
	miniatureAffichee.removeClass( 'miniature-cachee' );
1342
};
1343
 
1344
ReleveLg.prototype.supprimerObs = function( selector ) {
1345
	var obsId = $( selector ).val();
1346
 
1347
	// Problème avec IE 6 et 7
1348
	if ( 'Supprimer' === obsId ) {
1349
		obsId = $( selector ).attr( 'title' );
1350
	}
1351
	this.supprimerObsParId( obsId );
1352
};
1353
 
1354
/**
1355
 * Supprime l'obs et les data de l'obs
1356
 * et remonte les suivantes d'un cran
1357
 */
1358
ReleveLg.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1359
	if ( !transmission ) {
1360
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1361
		this.releveData.splice( obsId , 1 );
1362
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1363
	}
1364
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1365
	$( '#arbre-nb' ).text( this.numArbre );
1366
 
1367
	this.obsNbre  -= 1;
1368
	this.numArbre -= 1;
1369
	$( '.obs-nbre' ).text( this.obsNbre );
1370
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1371
	$( '.obs' + obsId ).remove();
1372
 
1373
	obsId = parseInt(obsId);
1374
	var listObsData = $( '#liste-obs' ).data(),
1375
		exId        = 0,
1376
		indexObs    = '',
1377
		exIndexObs  = '',
3334 idir 1378
		arbreExId   = 0,
1379
		arbreId     = 0;
3318 idir 1380
 
1381
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1382
		exId       = parseInt(id) + 1;
1383
		indexObs   = 'obsId' + id;
1384
		exIndexObs = 'obsId' + exId;
1385
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1386
		arbreId    = arbreExId - 1;
1387
		$( '#liste-obs' ).removeData( indexObs );
1388
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1389
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1390
		}
1391
		$( '#obs' + exId )
1392
			.attr( 'id', 'obs' + id )
1393
			.removeClass( 'obs' + exId )
1394
			.addClass( 'obs' + id )
1395
			.find( '.supprimer-obs' )
1396
				.attr( 'title', 'Observation n°' + id )
1397
				.val( id );
1398
		$( '#obs-arbre-' + arbreExId )
1399
			.attr( 'id', 'obs-arbre-' + arbreId )
1400
			.attr( 'data-arbre', arbreId )
1401
			.data( 'arbre', arbreId )
1402
			.text( 'Arbre ' + arbreId );
1403
 
1404
		if ( parseInt( id ) !== this.obsNbre ) {
1405
			id = parseInt(id);
1406
		}
1407
	}
1408
};
1409
 
1410
/*
1411
 * Actualise l'id_observation ( id de l'obs en bdd )
1412
 * à partir des données renvoyées par le service après transfert
1413
 */
1414
ReleveLg.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1415
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1416
	this.releveData[obsId ]['id_observation'] = id_observation;
1417
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1418
};
1419
 
1420
ReleveLg.prototype.transmettreObs = function() {
1421
	const lthis = this;
1422
	var observations = $( '#liste-obs' ).data();
1423
 
1424
	if ( this.debug ) {
1425
		console.log( observations );
1426
	}
1427
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1428
		this.afficherPanneau( '#dialogue-zero-obs' );
1429
	} else {
1430
		$( window ).on( 'beforeunload', function( event ) {
1431
			return lthis.utils.msgTraduction( 'rechargement-page' );
1432
		});
1433
		this.nbObsEnCours         = 1;
1434
		this.nbObsTransmises      = 0;
1435
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1436
			return i;
1437
		}).length;
1438
		this.depilerObsPourEnvoi();
1439
	}
1440
 
1441
	return false;
1442
};
1443
 
1444
ReleveLg.prototype.depilerObsPourEnvoi = function() {
1445
	var observations = $( '#liste-obs' ).data();
1446
 
1447
	// la boucle est factice car on utilise un tableau
1448
	// dont on a besoin de n'extraire que le premier élément
1449
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1450
	// TODO: utiliser var.keys quand ça sera plus répandu
1451
	// ou bien utiliser un vrai tableau et pas un objet
1452
	for ( var obsNum in observations ) {
1453
		var obsATransmettre = {
1454
			'projet'  : this.tagProjet,
1455
			'tag-obs' : this.tagObs,
1456
			'tag-img' : this.tagImg
1457
		};
1458
		var utilisateur = {
1459
			id_utilisateur : this.infosUtilisateur.id,
1460
			prenom         : this.infosUtilisateur.prenom,
1461
			nom            : this.infosUtilisateur.nom,
1462
			courriel       : $( '#courriel' ).val()
1463
		};
1464
 
1465
		obsATransmettre['utilisateur'] = utilisateur;
1466
		obsATransmettre[obsNum]        = observations[obsNum];
1467
 
1468
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1469
 
1470
		if( '' !== idObsNumerique ) {
1471
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1472
		}
1473
		break;
1474
	}
1475
};
1476
 
1477
ReleveLg.prototype.envoyerObsAuCel = function( idObs, observation ) {
1478
	const lthis     = this;
1479
	var erreurMsg = '';
1480
 
1481
	$.ajax({
1482
		url        : lthis.serviceSaisieUrl,
1483
		type       : 'POST',
1484
		data       : observation,
1485
		dataType   : 'json',
1486
		beforeSend : function() {
1487
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1488
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1489
			$( '.alert-txt' ).empty();
1490
			$( '.alert-txt .msg-erreur' ).remove();
1491
			$( '.alert-txt .msg-debug' ).remove();
1492
			$( '#chargement' ).removeClass( 'hidden' );
1493
		},
1494
		success    : function( transfertDatas, textStatus, jqXHR ) {
1495
			// actualisation de id_observation dans '#releve-data'
1496
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1497
			// mise à jour du nombre d'obs à transmettre
1498
			// et suppression de l'obs
1499
			lthis.supprimerObsParId( idObs, true );
1500
			lthis.nbObsEnCours++;
1501
			// mise à jour du statut
1502
			lthis.mettreAJourProgression();
1503
			if( 0 < lthis.obsNbre ) {
1504
				// dépilement de la suivante
1505
				lthis.depilerObsPourEnvoi();
1506
			}
1507
		},
1508
		statusCode  : {
1509
			500 : function( jqXHR, textStatus, errorThrown ) {
1510
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1511
				}
1512
		},
1513
		error        : function( jqXHR, textStatus, errorThrown ) {
1514
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1515
			try {
1516
				reponse = jQuery.parseJSON( jqXHR.responseText );
1517
				if ( null !== reponse ) {
1518
					$.each( reponse, function( cle, valeur ) {
1519
						erreurMsg += valeur + '\n';
1520
					});
1521
				}
1522
			} catch( e ) {
1523
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1524
			}
1525
		},
1526
		complete      : function( jqXHR, textStatus ) {
1527
			var debugMsg = extraireEnteteDebug( jqXHR );
1528
 
1529
			if ( '' !== erreurMsg ) {
1530
				if ( lthis.debug ) {
1531
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1532
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1533
				}
1534
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1535
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1536
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1537
 
1538
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1539
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1540
				// window.location.hash = 'obs' + idObs;
1541
 
1542
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1543
					$( '#tpl-transmission-ko' ).clone()
1544
						.find( '.courriel-erreur' )
1545
						.attr( 'href', hrefCourriel )
1546
						.end()
1547
						.html()
1548
				);
1549
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1550
				$( '#chargement' ).addClass( 'hidden' );
1551
				lthis.initialiserBarreProgression;
1552
			} else {
1553
				if ( lthis.debug ) {
1554
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1555
				}
1556
				if( 0 === lthis.obsNbre ) {
1557
					setTimeout( function() {
1558
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1559
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1560
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-lichens' ).removeClass( 'hidden' );
1561
					}, 1500 );
1562
				}
1563
			}
1564
		}
1565
	});
1566
};
1567
 
1568
ReleveLg.prototype.mettreAJourProgression = function() {
1569
	this.nbObsTransmises++;
1570
 
1571
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1572
 
1573
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1574
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1575
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1576
	if( 0 === this.obsNbre ) {
1577
		$( '.progress' ).removeClass( 'active' );
1578
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1579
	}
1580
};
1581
 
1582
ReleveLg.prototype.initialiserBarreProgression = function() {
1583
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1584
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1585
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1586
	$( '.progress' ).addClass( 'active' );
1587
	$( '.progress' ).addClass( 'progress-bar-striped' );
1588
};
1589
 
1590
// Form Validator *************************************************************/
1591
ReleveLg.prototype.configurerFormValidator = function() {
1592
	const lthis = this;
1593
 
1594
	$.validator.addMethod(
1595
		'dateCel',
1596
		function ( value, element ) {
1597
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1598
		},
1599
		lthis.utils.msgTraduction( 'date-incomplete' )
1600
	);
1601
 
1602
	$.validator.addMethod(
1603
		'userEmailOk',
1604
		function ( value, element ) {
1605
			return ( lthis.utils.valOk( value ) );
1606
		},
1607
		''
1608
	);
1609
	$.validator.addMethod(
1610
		'minMaxOk',
1611
		function ( value, element, param ) {
1612
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1613
			return lthis.validerMinMax( element ).cond;
1614
		},
1615
		$.validator.messages.minMaxOk
1616
	);
1617
 
1618
	$.extend( $.validator.defaults, {
1619
		errorElement: 'span',
1620
		errorPlacement: function( error, element ) {
1621
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1622
				error.appendTo( element.closest( '.list' ) );
1623
			} else {
1624
				element.after( error );
1625
			}
1626
		},
1627
		onfocusout: function( element ) {
1628
			if ( $( element ).valid() ) {
1629
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1630
			} else {
1631
				$( element ).closest( '.control-group' ).addClass( 'error' );
1632
			}
1633
		},
1634
		onkeyup : function( element ) {
1635
			if ( $( element ).valid() ) {
1636
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1637
			} else {
1638
				$( element ).closest( '.control-group' ).addClass( 'error' );
1639
			}
1640
		},
1641
		unhighlight: function( element ) {
1642
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1643
		},
1644
		highlight: function( element ) {
1645
			$( element ).closest( '.control-group' ).addClass( 'error' );
1646
		}
1647
	});
1648
};
1649
 
1650
ReleveLg.prototype.validerMinMax = function( element ) {
1651
	var mMCond      = new Boolean(),
1652
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1653
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1654
		messageMnMx = 'La valeur entrée doit être',
1655
		returnMnMx  = { cond : true , message : '' };
1656
 
1657
	if (
1658
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1659
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1660
		) {
1661
 
1662
		if ( element.min && element.max ) {
1663
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1664
			mnMxCond     = ( minCond && maxCond );
1665
		} else if ( element.min ) {
1666
			messageMnMx += ' supérieure à ' + element.min;
1667
			mnMxCond     = minCond;
1668
		} else {
1669
			messageMnMx += ' inférieure à ' + element.max;
1670
			mnMxCond     = maxCond;
1671
		}
1672
		returnMnMx.cond    = mnMxCond;
1673
		returnMnMx.message = messageMnMx;
1674
	}
1675
 
1676
	return returnMnMx;
1677
};
1678
 
1679
/**
1680
 * Valider date/rue/commune par rapport aux relevés précédents
1681
 */
1682
ReleveLg.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1683
	var valide = true;
1684
 
1685
	if (
1686
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1687
		this.utils.valOk( valeurDate ) &&
1688
		this.utils.valOk( valeurRue ) &&
1689
		this.utils.valOk( valeurCmn )
1690
	) {
1691
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1692
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1693
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1694
 
1695
	}
1696
	return valide;
1697
};
1698
 
1699
/**
1700
 * FormValidator pour les champs date/rue/Commune
1701
 */
1702
ReleveLg.prototype.dateRueCommuneFormValidator = function() {
1703
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1704
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1705
	const errorDateRue =
1706
			'<span id="error-drc" class="error">'+
1707
				this.utils.msgTraduction( 'date-rue' )+
1708
			'</span> ';
1709
 
1710
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1711
		$( '#releve-date' )
1712
			.removeClass( 'erreur' )
1713
			.closest( '.control-group' )
1714
				.removeClass( 'error' )
1715
				.find( '#error-drc' )
1716
					.remove();
1717
		if ( geolocValid ) {
1718
			$( '#geoloc' )
1719
			.closest( '.control-group' )
1720
				.removeClass( 'error' );
1721
		}
1722
	} else {
1723
		$( '#releve-date' )
1724
			.addClass( 'erreur' )
1725
			.closest( '.control-group' )
1726
				.addClass( 'error' );
1727
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1728
			$( '#releve-date' ).after( errorDateRue );
1729
		}
1730
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1731
	}
1732
	if ( dateValid ) {
1733
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1734
	}
1735
};
1736
 
1737
ReleveLg.prototype.definirReglesFormValidator = function() {
1738
	const lthis = this;
1739
 
1740
	$( '#form-observation' ).validate({
1741
		rules : {
1742
			latitude : {
1743
				required : true,
1744
				minlength : 1,
1745
				range : [-90, 90]
1746
			},
1747
			longitude : {
1748
				required : true,
1749
				minlength : 1,
1750
				range : [-180, 180]
1751
			}
1752
		}
1753
	});
1754
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1755
		$( this ).valid();
1756
	});
1757
	// validation date/rue/commune au démarage
1758
	this.dateRueCommuneFormValidator();
1759
	// validation date/rue/commune sur event
1760
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1761
	$( '#form-arbre' ).validate({
1762
		rules : {
1763
			taxon : {
1764
				required : true,
1765
				minlength : 1
1766
			},
1767
			certitude : {
1768
				required : true,
1769
				minlength : 1
1770
			},
1771
			'latitude-arbres' : {
1772
				required : true,
1773
				minlength : 1,
1774
				range : [-90, 90]
1775
			},
1776
			'longitude-arbres' : {
1777
				required : true,
1778
				minlength : 1,
1779
				range : [-180, 180]
1780
			}
1781
		}
1782
	});
1783
	$( '#form-arbre-fs' ).validate({
1784
		onkeyup : false,
1785
		onclick : false,
1786
		rules : {
1787
			circonference : {
1788
				required : true,
1789
				minlength : 1//,
1790
				//'minMaxOk' : true
1791
			},
1792
			'face-ombre' : {
1793
				required : true,
1794
				minlength : 1
1795
			}
1796
		}
1797
	});
1798
	$( '#form-observateur' ).validate({
1799
		rules : {
1800
			courriel : {
1801
				required : true,
1802
				minlength : 1,
1803
				email : true,
1804
				'userEmailOk' : true
1805
			},
1806
			mdp : {
1807
				required : true,
1808
				minlength : 1
1809
			}
1810
		}
1811
	});
1812
	$( '#face-ombre input' ).click( function() {
1813
		var oneIsChecked = false;
1814
		$( '#face-ombre input' ).each( function() {
1815
			if ( $( this ).is( ':checked' ) ) {
1816
				oneIsChecked = true;
1817
				return false;
1818
			}
1819
		});
1820
		if ( oneIsChecked ) {
1821
			$( '#face-ombre.control-group' )
1822
				.removeClass( 'error' )
1823
				.find( 'span.error' )
1824
					.addClass( 'hidden' );
1825
		} else {
1826
			$( '#face-ombre.control-group' )
1827
				.addClass( 'error' )
1828
				.find( 'span.error' )
1829
					.removeClass( 'hidden' );
1830
		}
1831
	});
1832
	$( '#connexion,#inscription,#oublie' ).click( function() {
1833
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1834
	});
1835
};
1836
 
1837
/**
1838
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1839
 */
1840
ReleveLg.prototype.validerReleve = function() {
1841
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1842
	const obs         = $( '#form-observation' ).valid();
1843
	const geoloc      = (
1844
		this.utils.valOk( $( '#latitude' ).val() ) &&
1845
		this.utils.valOk( $( '#longitude' ).val() ) &&
1846
		this.utils.valOk( $( '#rue' ).val() ) &&
1847
		this.utils.valOk( $( '#commune-nom' ).val() )
1848
	) ;
1849
	var dateRue = true;
1850
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1851
		dateRue = (
1852
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1853
			this.utils.valOk( $( '#rue' ).val() ) &&
1854
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1855
		);
1856
	}
1857
 
1858
	if ( !obs ) {
1859
		$( 'html, body' ).stop().animate({
1860
			scrollTop: $( '#zone-observation' ).offset().top
1861
		}, 300 );
1862
	}
1863
	// panneau observateur
1864
	if ( observateur ) {
1865
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1866
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1867
	} else {
1868
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1869
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1870
	}
1871
	if ( dateRue && geoloc ) {
1872
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1873
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1874
	} else {
1875
		if (
1876
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1877
			this.utils.valOk( $( '#rue' ).val() ) &&
1878
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1879
		) {
1880
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1881
		}
1882
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1883
	}
1884
	if (
1885
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1886
		!this.utils.valOk( $( '#rue' ).val() ) ||
1887
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1888
	) {
1889
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1890
	}
1891
	if ( geoloc ) {
1892
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1893
		if ( dateRue ) {
3325 idir 1894
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
3318 idir 1895
		}
1896
	} else {
1897
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3325 idir 1898
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 1899
	}
1900
 
3325 idir 1901
	return ( observateur && obs && geoloc && dateRue );
3318 idir 1902
};
1903
 
1904
/**
1905
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1906
 */
1907
ReleveLg.prototype.validerArbres = function( etapeReleve = false ) {
3325 idir 1908
	const validerReleve = this.validerReleve();
3318 idir 1909
	const geoloc      = (
1910
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
3325 idir 1911
		this.utils.valOk( $( '#longitude-arbres' ).val() )
3318 idir 1912
	);
1913
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
3325 idir 1914
	const obs   = ( $( '#form-arbre' ).valid() && $( '#form-arbre-fs' ).valid() );
3318 idir 1915
	if ( geoloc ) {
1916
		this.masquerPanneau( '#dialogue-geoloc-ko' );
3325 idir 1917
		$( '#geoloc-arbres' ).closest( '.control-group' ).removeClass( 'error' );
3318 idir 1918
	} else {
1919
		this.afficherPanneau( '#dialogue-geoloc-ko' );
3325 idir 1920
		$( '#geoloc-arbres' ).closest( '.control-group' ).addClass( 'error' );
3318 idir 1921
	}
1922
 
3325 idir 1923
	return ( validerReleve && obs && geoloc && taxon );
3318 idir 1924
};
1925
 
1926
// Controle des panneaux d'infos **********************************************/
1927
 
1928
ReleveLg.prototype.afficherPanneau = function( selecteur ) {
1929
	$( selecteur )
1930
		.removeClass( 'hidden' )
1931
		.hide()
1932
		.show( 600 )
1933
		.delay( this.dureeMessage )
1934
		.hide( 600 );
1935
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
1936
};
1937
 
1938
ReleveLg.prototype.masquerPanneau = function( selecteur ) {
1939
	$( selecteur ).addClass( 'hidden' );
1940
};
1941
 
1942
ReleveLg.prototype.fermerPanneauAlert = function() {
1943
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
1944
};
1945
 
1946
// lib hors objet --
1947
 
1948
/**
1949
* Stope l'évènement courant quand on clique sur un lien.
1950
* Utile pour Chrome, Safari...
1951
*/
1952
function arreter( event ) {
1953
	if ( event.stopPropagation ) {
1954
		event.stopPropagation();
1955
	}
1956
	if ( event.preventDefault ) {
1957
		event.preventDefault();
1958
	}
1959
 
1960
	return false;
1961
}
1962
 
1963
/**
1964
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1965
 * @param jqXHR
1966
 * @returns {String}
1967
 */
1968
function extraireEnteteDebug( jqXHR ) {
1969
	var msgDebug = '';
1970
 
1971
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
1972
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
1973
		if ( null !== debugInfos ) {
1974
			$.each( debugInfos, function( cle, valeur ) {
1975
				msgDebug += valeur + '\n';
1976
			});
1977
		}
1978
	}
1979
 
1980
	return msgDebug;
1981
}
1982
 
1983
/*
1984
 * jQuery UI Autocomplete HTML Extension
1985
 *
1986
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1987
 * Dual licensed under the MIT or GPL Version 2 licenses.
1988
 *
1989
 * http://github.com/scottgonzalez/jquery-ui-extensions
1990
 *
1991
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1992
 */
1993
( function( $ ) {
1994
	var proto      = $.ui.autocomplete.prototype,
1995
		initSource = proto._initSource;
1996
 
1997
	ReleveLg.prototype.filter = function( array, term ) {
1998
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
1999
 
2000
		return $.grep( array, function( value ) {
2001
 
2002
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2003
		});
2004
	}
2005
	$.extend( proto, {
2006
		_initSource: function() {
2007
			if ( this.options.html && $.isArray( this.options.source ) ) {
2008
				this.source = function( request, response ) {
2009
					response( filter( this.options.source, request.term ) );
2010
				};
2011
			} else {
2012
				initSource.call( this );
2013
			}
2014
		},
2015
		_renderItem: function( ul, item) {
2016
			if ( item.retenu ) {
2017
				item.label = '<strong>' + item.label + '</strong>';
2018
			}
2019
 
2020
			return $( '<li></li>' )
2021
				.data( 'item.autocomplete', item )
2022
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2023
				.appendTo( ul );
2024
		}
2025
	});
2026
})( jQuery );