Subversion Repositories eFlore/Applications.cel

Rev

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