Subversion Repositories eFlore/Applications.cel

Rev

Rev 3320 | Go to most recent revision | Details | 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(),
851
			'circonference'         : $( '#circonference' ).val(),
852
			'surface-pied'          : $( '#surface-pied' ).val(),
853
			'equipement-pied-arbre' : $( '#equipement-pied-arbre' ).val(),
854
			'tassement'             : $( '#tassement' ).val(),
855
			'dejections'            : $( '#dejections input:checked' ).val(),
856
			'face-ombre'            : faceOmbre,
857
			'com-arbres'            : $( '#com-arbres' ).val(),
858
			'miniature-img'         : miniatureImg,
859
		},
860
		releve : {
861
			'date'                  : this.utils.fournirDate( $( '#releve-date' ).val() ),
862
			'rue'                   : $( '#rue' ).val(),
863
			'commune-nom'           : $( '#commune-nom' ).val(),
864
			'commentaires'          : $( '#commentaires' ).val(),
865
			'pays'                  : $( '#pays' ).val(),
866
			'commune-insee'         : $( '#commune-insee' ).val(),
867
			'latitude'              : $( '#latitude' ).val(),
868
			'longitude'             : $( '#longitude' ).val(),
869
			'altitude'              : $( '#altitude' ).val(),
870
		}
871
	};
872
	return obsData;
873
};
874
 
875
/**
876
 * Résumé obs
877
 */
878
ReleveLg.prototype.afficherObs = function( datasObs ) {
879
	var obsNum            = datasObs.obsNum,
880
		numArbre          = datasObs.arbre['num-arbre'],
881
		dateObs           = this.utils.fournirDate( datasObs.releve.date ),
882
		numNomSel         = datasObs.arbre.taxon.numNomSel,
883
		taxon             = datasObs.arbre.taxon.value,
884
		certitude         = datasObs.arbre.certitude,
885
		rue               = datasObs.releve.rue,
886
		commune           = datasObs.releve['commune-nom'],
887
		latitudeLongitude = '[' + datasObs.arbre['latitude-arbres'] + ' / ' + datasObs.arbre['longitude-arbres'] + ']',
888
		miniatures        = this.ajouterImgMiniatureAuTransfert( datasObs.arbre['miniature-img'] ),
889
		commentaires      = '';
890
 
891
	if ( this.utils.valOk( datasObs.arbre['com-arbres'] ) ) {
892
		commentaires =
893
			this.utils.msgTraduction( 'commentaires' ) +
894
			' : <span>'+
895
				datasObs.arbre['com-arbres'] +
896
			'</span> ';
897
	}
898
 
899
	var responsivDiff1 = '',
900
		responsivDiff2 = '',
901
		responsivDiff3 = '',
902
		responsivDiff4 = '',
903
		responsivDiff5 = '',
904
		responsivDiff6 = '';
905
 
906
	if ( window.matchMedia( '(min-width: 576px)' ).matches ) {
907
		/* La largeur minimum de l'affichage est 600 px inclus */
908
		responsivDiff1 = ' droite';
909
		responsivDiff2 = '<div></div>';
910
		responsivDiff3 = '<div class="row">';
911
		responsivDiff4 = ' col-md-4 col-sm-5';
912
		responsivDiff5 = ' class="col-md-7 col-sm-6"';
913
		responsivDiff6 = '</div>';
914
	}
915
	$( '#liste-obs' ).prepend(
916
		'<div id="obs' + obsNum + '" class="obs obs' + obsNum + ' mb-2">'+
917
			'<div '+
918
				'class="obs-action" '+
919
				'title="' + this.utils.msgTraduction( 'supprimer-observation-liste' ) + '"'+
920
			'>'+
921
				'<button class="btn btn-danger supprimer-obs' + responsivDiff1 + '" value="'+ obsNum + '" title="' + this.utils.msgTraduction( 'obs-numero' ) + obsNum + '">'+
922
				'<i class="far fa-trash-alt"></i>'+
923
				'</button>'+
924
				responsivDiff2 +
925
			'</div> '+
926
			responsivDiff3 +
927
				'<div class="thumbnail' + responsivDiff4 + '">'+
928
					miniatures+
929
				'</div>'+
930
				'<div' + responsivDiff5 + '>'+
931
					'<ul class="unstyled">'+
932
						'<li>'+
933
							'<span id="obs-arbre-' + numArbre + '" class="badge num-obs-arbre" data-arbre="' + numArbre + '">Arbre ' + numArbre + '</span>' +
934
							' <span class="nom-sci">' + taxon + '</span> '+
935
							' [certitude : ' + certitude + ']'+
936
							' '  + this.utils.msgTraduction( 'lieu-obs' ) +
937
							' ' + rue +
938
							', ' + commune +
939
							latitudeLongitude +
940
							' ' + this.utils.msgTraduction( 'obs-le' ) + ' ' +
941
							'<span class="date">' + this.utils.fournirDate( dateObs ) + '</span>'+
942
						'</li>'+
943
						'<li>'+
944
							commentaires +
945
						'</li>'+
946
					'</ul>'+
947
				'</div>'+
948
			responsivDiff6+
949
		'</div>'
950
	);
951
	$( '#zone-liste-obs' ).removeClass( 'hidden' );
952
};
953
 
954
/**
955
 * Ajoute une boîte de miniatures avec défilement des images,
956
 * pour une obs de la liste des obs à transmettre
957
 */
958
ReleveLg.prototype.ajouterImgMiniatureAuTransfert = function( chargerImages ) {
959
	const lthis = this;
960
	var html         =
961
			'<div class="defilement-miniatures">'+
962
				'<figure class="centre">'+
963
					'<img class="miniature align-middle" alt="Aucune photo" src="' + this.pasDePhotoIconeUrl + '" width="80%" />'+
964
				'</figure>'+
965
			'</div>',
966
		miniatures   = '',
967
		centre       = '',
968
		defilVisible = '',
969
		length       = 0;
970
 
971
	if ( this.utils.valOk( chargerImages ) || this.utils.valOk( $( '#miniatures img' ) ) ) {
972
		if ( this.utils.valOk( chargerImages ) ) {
973
			$.each(  chargerImages, function( i, value ) {
974
				var imgVisible = ( 0 < i ) ? 'miniature-cachee' : 'miniature-selectionnee';
975
 
976
				var css        = ( lthis.utils.valOk( value['b64'] ) ) ? 'miniature b64' : 'miniature',
977
					src        = value.src,
978
					alt        = value.nom,
979
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
980
 
981
				miniatures += miniature;
982
			});
983
			length = chargerImages.length;
984
 
985
		} else {
986
			var premiere     = true;
987
			$( '#miniatures img' ).each( function() {
988
				var imgVisible = ( premiere ) ? 'miniature-selectionnee' : 'miniature-cachee';
989
				premiere = false;
990
 
991
				var css        = ( $( this ).hasClass( 'b64' ) ) ? 'miniature b64' : 'miniature',
992
					src        = $( this ).attr( 'src' ),
993
					alt        = $( this ).attr( 'alt' ),
994
					miniature  = '<img class="' + css + ' ' + imgVisible + ' align-middle"  alt="' + alt + '"src="' + src + '" width="80%" />';
995
 
996
				miniatures += miniature;
997
			});
998
			length = $( '#miniatures img' ).length;
999
		}
1000
		if ( 1 === length ) {
1001
			centre       = 'centre';
1002
			defilVisible = ' defilement-miniatures-cache';
1003
		}
1004
		html             =
1005
			'<div class="defilement-miniatures">'+
1006
				'<a href="#" class="defilement-miniatures-gauche mr-1' + defilVisible + '"><i class="fas fa-chevron-circle-left"></i></a>'+
1007
				'<figure class="' + centre + '">'+
1008
					miniatures+
1009
				'</figure>'+
1010
				'<a href="#" class="defilement-miniatures-droite ml-1' + defilVisible + '"><i class="fas fa-chevron-circle-right"></i></a>'+
1011
			'</div>';
1012
	}
1013
 
1014
	return html;
1015
};
1016
 
1017
/**
1018
 * Construit le html à afficher pour le numNom
1019
 */
1020
ReleveLg.prototype.ajouterNumNomSel = function( numNomSel ) {
1021
	var nn = '<span class="nn">[nn' + numNomSel + ']</span>';
1022
 
1023
	if ( !this.utils.valOk( numNomSel ) ) {
1024
		nn = '<span class="alert-error">[' + this.utils.msgTraduction( 'non-lie-au-ref' ) + ']</span>';
1025
	}
1026
 
1027
	return nn;
1028
};
1029
 
1030
/**
1031
 * Stocke des données d'obs à envoyer à la bdd
1032
 */
1033
ReleveLg.prototype.stockerObsData = function( obsDatas ) {
1034
	const lthis = this;
1035
	var obsNum      = obsDatas.obsNum,
1036
		numNomSel   = obsDatas.arbre.taxon.numNomSel,
1037
		referentiel = ( !this.utils.valOk( numNomSel ) ) ? 'autre' : 'bdtfx',
1038
		date        = lthis.utils.fournirDate( obsDatas.releve.date ),
1039
		// si releve dupliqué on ne stocke pas l'image :
1040
		stockerImg  = this.utils.valOk( obsDatas.arbre['miniature-img'] ),
1041
		imgNom      = [],
1042
		imgB64      = [];
1043
 
1044
		if( stockerImg ) {
1045
			$.each( obsDatas.arbre['miniature-img'], function( i, obj ) {
1046
				if( obj.hasOwnProperty( 'id' ) ) {
1047
					stockerImg = false;
1048
				}
1049
				return stockerImg;
1050
			});
1051
		}
1052
		if ( stockerImg ) {
1053
			$.each( obsDatas.arbre['miniature-img'] , function(i, value) {
1054
				if( lthis.utils.valOk( value.nom ) ) {
1055
					imgNom.push( value.nom );
1056
				}
1057
				if( lthis.utils.valOk( value['b64'] ) ) {
1058
					imgB64.push( value['b64'] );
1059
				}
1060
			});
1061
		} else {
1062
			imgNom = lthis.getNomsImgsOriginales();
1063
			imgB64 = lthis.getB64ImgsOriginales();
1064
		}
1065
 
1066
	// Stockage en data des données d'obs à transmettre
1067
	$( '#liste-obs' ).data( 'obsId' + obsNum, {
1068
		'num_nom_sel'        : numNomSel,
1069
		'nom_sel'            : obsDatas.arbre.taxon.value,
1070
		'nom_ret'            : obsDatas.arbre.taxon.nomRet,
1071
		'num_nom_ret'        : obsDatas.arbre.taxon.numNomRet,
1072
		'num_taxon'          : obsDatas.arbre.taxon.nt,
1073
		'famille'            : obsDatas.arbre.taxon.famille,
1074
		'referentiel'        : referentiel,
1075
		'certitude'          : obsDatas.arbre.certitude,
1076
		'date'               : date,
1077
		'notes'              : obsDatas.releve.commentaires.trim(),
1078
		'pays'               : obsDatas.releve.pays,
1079
		'commune_nom'        : obsDatas.releve['commune-nom'],
1080
		'commune_code_insee' : obsDatas.releve['commune-insee'],
1081
		'latitude'           : obsDatas.releve.latitude,
1082
		'longitude'          : obsDatas.releve.longitude,
1083
		'altitude'           : obsDatas.releve.altitude,
1084
		//Ajout des champs images
1085
		'image_nom'          : imgNom,
1086
		'image_b64'          : imgB64,
1087
		// Ajout des champs étendus de l'obs
1088
		'obs_etendue'        : lthis.getObsChpArbres( obsDatas )
1089
	});
1090
};
1091
 
1092
ReleveLg.prototype.getNomsImgsOriginales = function() {
1093
	var noms = new Array();
1094
 
1095
	$( '.miniature-img' ).each( function() {
1096
		noms.push( $( this ).attr( 'alt' ) );
1097
	});
1098
 
1099
	return noms;
1100
};
1101
 
1102
ReleveLg.prototype.getB64ImgsOriginales = function() {
1103
	var b64 = new Array();
1104
 
1105
	$( '.miniature-img' ).each( function() {
1106
		if ( $( this ).hasClass( 'b64' ) ) {
1107
			b64.push( $( this ).attr( 'src' ) );
1108
		} else if ( $( this ).hasClass( 'b64-canvas' ) ) {
1109
			b64.push( $( this ).data( 'b64' ) );
1110
		}
1111
	});
1112
 
1113
	return b64;
1114
};
1115
 
1116
/**
1117
 * Retourne un Array contenant les valeurs des champs
1118
 * dont les données seront transmises dans la table cel-obs-etendues
1119
 */
1120
ReleveLg.prototype.getObsChpArbres = function( datasArbres ) {
1121
	const lthis = this;
1122
 
1123
	var retour = [],
1124
		champs = [
1125
			'rue',
1126
			'latitude-arbres',
1127
			'longitude-arbres',
1128
			'altitude-arbres',
1129
			'circonference',
1130
			'surface-pied',
1131
			'equipement-pied-arbre',
1132
			'tassement',
1133
			'dejections',
1134
			'com-arbres'
1135
		];
1136
 
1137
	var cleValeur       = '',
1138
		faceOmbre       = '',
1139
		faceOmbreLength = datasArbres.arbre['face-ombre'].length;
1140
 
1141
	$.each( champs, function( i ,value ) {
1142
		cleValeur = ( i === 0 ) ? 'releve' : 'arbre';
1143
 
1144
		if ( lthis.utils.valOk( datasArbres[cleValeur][value] ) ) {
1145
			retour.push({ cle : value, valeur : datasArbres[cleValeur][value] });
1146
		}
1147
	});
1148
	if ( 'string' === typeof datasArbres.arbre['face-ombre'] ) {
1149
		faceOmbre = datasArbres.arbre['face-ombre'];
1150
	} else {
1151
		$.each( datasArbres.arbre['face-ombre'], function( i ,value ) {
1152
			faceOmbre += value
1153
			if ( faceOmbreLength > ( i + 1 ) ) {
1154
				faceOmbre += ';';
1155
			}
1156
		});
1157
	}
1158
	retour.push(
1159
		{ cle : 'face-ombre', valeur : faceOmbre },
1160
		{ cle : 'num_arbre' , valeur : datasArbres.obsNum }
1161
	);
1162
 
1163
	var stockerImg  = this.utils.valOk( datasArbres.arbre['miniature-img'] );
1164
 
1165
	if( stockerImg ) {
1166
		$.each( datasArbres.arbre['miniature-img'], function( i, paramsImg ) {
1167
			if( !paramsImg.hasOwnProperty( 'id' ) ) {
1168
				stockerImg = false;
1169
			}
1170
			return stockerImg;
1171
		});
1172
	}
1173
	if( stockerImg ) {
1174
		retour.push({ cle : 'miniature-img' , valeur : JSON.stringify( datasArbres.arbre['miniature-img'] ) });
1175
	}
1176
 
1177
	return retour;
1178
};
1179
 
1180
/**
1181
 * Efface toutes les miniatures (formulaire)
1182
 */
1183
ReleveLg.prototype.supprimerMiniatures = function() {
1184
	$( '#miniatures' ).empty();
1185
	$( '#miniature-msg' ).empty();
1186
};
1187
 
1188
ReleveLg.prototype.surChangementNbreObs = function() {
1189
	if ( 0 === this.obsNbre ) {
1190
		$( '#transmettre-obs' ).attr( 'disabled', 'disabled' );
1191
		// $( '#zone-liste-obs' ).addClass( 'hidden' );
1192
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1193
	} else if ( 0 < this.obsNbre && this.obsNbre < this.obsMaxNbre ) {
1194
		$( '#ajouter-obs,#transmettre-obs' ).removeAttr( 'disabled' );
1195
		$( '#bloc-form-arbres' ).removeClass( 'hidden' );
1196
	} else if ( this.obsNbre >= this.obsMaxNbre ) {
1197
		$( '#ajouter-obs' ).attr( 'disabled', 'disabled' );
1198
		$( '#bloc-form-arbres' ).addClass( 'hidden' );
1199
		this.afficherPanneau( '#dialogue-bloquer-creer-obs' );
1200
	}
1201
};
1202
 
1203
ReleveLg.prototype.chargerInfosArbre = function( numArbre ) {
1204
	const lthis = this;
1205
	var desactiverForm = ( parseInt( numArbre ) !== ( this.numArbre + 1 ) );
1206
 
1207
	if ( desactiverForm ) {
1208
		var releveDatas = $.parseJSON( $( '#releve-data' ).val() ),
1209
			arbreDatas  = releveDatas[numArbre],
1210
			taxon       = {item:{}},
1211
			imgHtml     = '';
1212
 
1213
		$( '#arbre-nb').text( numArbre );
1214
 
1215
		taxon.item = arbreDatas.taxon;
1216
		this.surAutocompletionTaxon( {}, taxon );
1217
 
1218
		const SELECTS = ['certitude','equipement-pied-arbre','tassement'];
1219
 
1220
		$.each( SELECTS, function( i, value ) {
1221
			if( !lthis.utils.valOk( arbreDatas[value] ) ) {
1222
				arbreDatas[value] = '';
1223
			}
1224
			if ( $( this ).hasClass( 'other' ) && lthis.utils.valOk( $( this ).val() ) ) {
1225
				$( this ).text( $( this ).val() );
1226
			}
1227
			$( '#' + value + ' option' ).each( function() {
1228
				if ( arbreDatas[value] === $( this ).val() ) {
1229
					$( this ).prop( 'selected', true );
1230
				} else {
1231
					$( this ).prop( 'selected', false );
1232
				}
1233
			});
1234
		});
1235
		$( '#rue-arbres' ).val(releveDatas[0]['rue']);
1236
		$( '#latitude-arbres' ).val(arbreDatas['latitude-arbres']);
1237
		$( '#longitude-arbres' ).val(arbreDatas['longitude-arbres']);
1238
		$( '#commune-nom-arbres' ).val(releveDatas[0]['commune-nom']);
1239
		$( '#commune-insee-arbres' ).val(releveDatas[0]['commune-insee']);
1240
		$( '#altitude-arbres' ).val(arbreDatas['altitude-arbres']);
1241
		$( '#pays-arbres' ).val(releveDatas[0]['pays']);
1242
		// image
1243
		this.supprimerMiniatures();
1244
		$.each( arbreDatas['miniature-img'], function( i, value ) {
1245
			imgHtml +=
1246
			'<div class="miniature mb-3 mr-3">'+
1247
				'<img class="miniature-img" class="miniature img-rounded" alt="' + value.nom + '" src="' + value.src + '"/>'+
1248
			'</div>';
1249
		});
1250
		$( '#miniatures' ).append( imgHtml );
1251
		$( '#circonference' ).val( arbreDatas.circonference );
1252
		$( '#surface-pied' ).val( arbreDatas['surface-pied'] );
1253
		$( '#com-arbres' ).val( arbreDatas['com-arbres'] );
1254
		if ( undefined != arbreDatas.dejections ) {
1255
			$( '#dejections-oui' ).prop( 'checked', arbreDatas.dejections );
1256
			$( '#dejections-non' ).prop( 'checked', !arbreDatas.dejections );
1257
		}
1258
		$( '#face-ombre input' ).each( function() {
1259
			if ( -1 < arbreDatas['face-ombre'].indexOf( $( this ).val() ) ) {
1260
				$( this ).prop( 'checked', true );
1261
			} else {
1262
				$( this ).prop( 'checked', false );
1263
			}
1264
		});
1265
	}
1266
 
1267
	this.modeArbresBasculerActivation( desactiverForm, numArbre );
1268
};
1269
 
1270
ReleveLg.prototype.modeArbresBasculerActivation = function( desactiver, numArbre = 0 ) {
1271
	$(
1272
		'#taxon,'+
1273
		'#certitude,'+
1274
		'#equipement-pied-arbre,'+
1275
		'#tassement,'+
1276
		'#latitude-arbres,'+
1277
		'#longitude-arbres,'+
1278
		'#rue-arbres,'+
1279
		'#fichier,'+
1280
		'#circonference,'+
1281
		'#surface-pied,'+
1282
		'#com-arbres,'+
1283
		'#ajouter-obs'
1284
	).prop( 'disabled', desactiver );
1285
	$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'disabled', desactiver );
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' );
1294
		// retour aux valeurs par defaut
1295
		$( '#equipement-pied-arbre .other' ).text( 'Autre' ).val( 'other' );
1296
		// $( '#equipement-pied-arbre .other' ).val( 'other' );
1297
		$(
1298
			'#certitude option,'+
1299
			'#equipement-pied-arbre option,'+
1300
			'#tassement option'
1301
		).each( function() {
1302
			if ( $( this ).hasClass( 'choisir' ) ) {
1303
				$( this ).prop( 'selected', true );
1304
			} else {
1305
				$( this ).prop( 'selected', false );
1306
			}
1307
		});
1308
		$( '#taxon' ).data( 'numNomSel', '' )
1309
			.data( 'nomRet','' )
1310
			.data( 'numNomRet', '' )
1311
			.data( 'nt', '' )
1312
			.data( 'famille', '' );
1313
		this.supprimerMiniatures();
1314
		$( '#dejections,#face-ombre' ).find( 'input' ).prop( 'checked', false );
1315
		$(
1316
			'#taxon,'+
1317
			'#circonference,'+
1318
			'#surface-pied,'+
1319
			'#com-arbres,'+
1320
			'#rue-arbres,'+
1321
			'#latitude-arbres,'+
1322
			'#longitude-arbres,'+
1323
			'#certitude,'+
1324
			'#equipement-pied-arbre,'+
1325
			'#tassement'
1326
		).val( '' );
1327
		$( '#arbre-nb' ).text( numArbre );
1328
		$( '#arbre-info-lien-' + numArbre ).addClass( 'disabled' );
1329
		$( '.arbre-info' ).not( '#arbre-info-lien-' + numArbre ).removeClass( 'disabled' );
1330
	}
1331
};
1332
 
1333
ReleveLg.prototype.defilerMiniatures = function( element ) {
1334
	var miniatureSelectionne  = element.siblings( 'figure' ).find( 'img.miniature-selectionnee' );
1335
 
1336
	miniatureSelectionne.removeClass( 'miniature-selectionnee' );
1337
	miniatureSelectionne.addClass( 'miniature-cachee' );
1338
 
1339
	var miniatureAffichee     = miniatureSelectionne;
1340
 
1341
	if( element.hasClass( 'defilement-miniatures-gauche' ) ) {
1342
		if( 0 !== miniatureSelectionne.prev( '.miniature' ).length ) {
1343
			miniatureAffichee = miniatureSelectionne.prev( '.miniature' );
1344
		} else {
1345
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).last();
1346
		}
1347
	} else {
1348
		if( 0 !== miniatureSelectionne.next('.miniature').length ) {
1349
			miniatureAffichee = miniatureSelectionne.next( '.miniature' );
1350
		} else {
1351
			miniatureAffichee = miniatureSelectionne.siblings( '.miniature' ).first();
1352
		}
1353
	}
1354
	miniatureAffichee.addClass( 'miniature-selectionnee' );
1355
	miniatureAffichee.removeClass( 'miniature-cachee' );
1356
};
1357
 
1358
ReleveLg.prototype.supprimerObs = function( selector ) {
1359
	var obsId = $( selector ).val();
1360
 
1361
	// Problème avec IE 6 et 7
1362
	if ( 'Supprimer' === obsId ) {
1363
		obsId = $( selector ).attr( 'title' );
1364
	}
1365
	this.supprimerObsParId( obsId );
1366
};
1367
 
1368
/**
1369
 * Supprime l'obs et les data de l'obs
1370
 * et remonte les suivantes d'un cran
1371
 */
1372
ReleveLg.prototype.supprimerObsParId = function( obsId, transmission = false ) {
1373
	if ( !transmission ) {
1374
		this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1375
		this.releveData.splice( obsId , 1 );
1376
		$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1377
	}
1378
	$( '#arbre-info-' + ( this.numArbre ) ).remove();
1379
	$( '#arbre-nb' ).text( this.numArbre );
1380
 
1381
	this.obsNbre  -= 1;
1382
	this.numArbre -= 1;
1383
	$( '.obs-nbre' ).text( this.obsNbre );
1384
	$( '.obs-nbre' ).triggerHandler( 'changement' );
1385
	$( '.obs' + obsId ).remove();
1386
 
1387
	obsId = parseInt(obsId);
1388
	var listObsData = $( '#liste-obs' ).data(),
1389
		exId        = 0,
1390
		indexObs    = '',
1391
		exIndexObs  = '',
1392
		arbreExId   = 0;
1393
 
1394
	for ( var id = obsId; id <= ( this.obsNbre + 1 ); id++ ) {
1395
		exId       = parseInt(id) + 1;
1396
		indexObs   = 'obsId' + id;
1397
		exIndexObs = 'obsId' + exId;
1398
		arbreExId  = parseInt( $( '#obs-arbre-' + exId ).data( 'arbre' ) );
1399
		arbreId    = arbreExId - 1;
1400
		$( '#liste-obs' ).removeData( indexObs );
1401
		if ( this.utils.valOk( listObsData[ exIndexObs ] ) ) {
1402
			$( '#liste-obs' ).data( indexObs, listObsData[ exIndexObs ] );
1403
		}
1404
		$( '#obs' + exId )
1405
			.attr( 'id', 'obs' + id )
1406
			.removeClass( 'obs' + exId )
1407
			.addClass( 'obs' + id )
1408
			.find( '.supprimer-obs' )
1409
				.attr( 'title', 'Observation n°' + id )
1410
				.val( id );
1411
		$( '#obs-arbre-' + arbreExId )
1412
			.attr( 'id', 'obs-arbre-' + arbreId )
1413
			.attr( 'data-arbre', arbreId )
1414
			.data( 'arbre', arbreId )
1415
			.text( 'Arbre ' + arbreId );
1416
 
1417
		if ( parseInt( id ) !== this.obsNbre ) {
1418
			id = parseInt(id);
1419
		}
1420
	}
1421
};
1422
 
1423
/*
1424
 * Actualise l'id_observation ( id de l'obs en bdd )
1425
 * à partir des données renvoyées par le service après transfert
1426
 */
1427
ReleveLg.prototype.actualiserReleveDataIdObs = function( obsId, id_observation ) {
1428
	this.releveData  = $.parseJSON( $( '#releve-data' ).val() );
1429
	this.releveData[obsId ]['id_observation'] = id_observation;
1430
	$( '#releve-data' ).val( JSON.stringify( this.releveData ) );
1431
};
1432
 
1433
ReleveLg.prototype.transmettreObs = function() {
1434
	const lthis = this;
1435
	var observations = $( '#liste-obs' ).data();
1436
 
1437
	if ( this.debug ) {
1438
		console.log( observations );
1439
	}
1440
	if ( !this.utils.valOk( typeof observations, true, 'object' ) ) {
1441
		this.afficherPanneau( '#dialogue-zero-obs' );
1442
	} else {
1443
		$( window ).on( 'beforeunload', function( event ) {
1444
			return lthis.utils.msgTraduction( 'rechargement-page' );
1445
		});
1446
		this.nbObsEnCours         = 1;
1447
		this.nbObsTransmises      = 0;
1448
		this.totalObsATransmettre = $.map( observations, function( n, i ) {
1449
			return i;
1450
		}).length;
1451
		this.depilerObsPourEnvoi();
1452
	}
1453
 
1454
	return false;
1455
};
1456
 
1457
ReleveLg.prototype.depilerObsPourEnvoi = function() {
1458
	var observations = $( '#liste-obs' ).data();
1459
 
1460
	// la boucle est factice car on utilise un tableau
1461
	// dont on a besoin de n'extraire que le premier élément
1462
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1463
	// TODO: utiliser var.keys quand ça sera plus répandu
1464
	// ou bien utiliser un vrai tableau et pas un objet
1465
	for ( var obsNum in observations ) {
1466
		var obsATransmettre = {
1467
			'projet'  : this.tagProjet,
1468
			'tag-obs' : this.tagObs,
1469
			'tag-img' : this.tagImg
1470
		};
1471
		var utilisateur = {
1472
			id_utilisateur : this.infosUtilisateur.id,
1473
			prenom         : this.infosUtilisateur.prenom,
1474
			nom            : this.infosUtilisateur.nom,
1475
			courriel       : $( '#courriel' ).val()
1476
		};
1477
 
1478
		obsATransmettre['utilisateur'] = utilisateur;
1479
		obsATransmettre[obsNum]        = observations[obsNum];
1480
 
1481
		var idObsNumerique = obsNum.replace( 'obsId', '' );
1482
 
1483
		if( '' !== idObsNumerique ) {
1484
			this.envoyerObsAuCel( idObsNumerique, obsATransmettre );
1485
		}
1486
		break;
1487
	}
1488
};
1489
 
1490
ReleveLg.prototype.envoyerObsAuCel = function( idObs, observation ) {
1491
	const lthis     = this;
1492
	var erreurMsg = '';
1493
 
1494
	$.ajax({
1495
		url        : lthis.serviceSaisieUrl,
1496
		type       : 'POST',
1497
		data       : observation,
1498
		dataType   : 'json',
1499
		beforeSend : function() {
1500
			$( '#dialogue-obs-transaction-ko' ).addClass( 'hidden' );
1501
			$( '#dialogue-obs-transaction-ok' ).addClass( 'hidden' );
1502
			$( '.alert-txt' ).empty();
1503
			$( '.alert-txt .msg-erreur' ).remove();
1504
			$( '.alert-txt .msg-debug' ).remove();
1505
			$( '#chargement' ).removeClass( 'hidden' );
1506
		},
1507
		success    : function( transfertDatas, textStatus, jqXHR ) {
1508
			// actualisation de id_observation dans '#releve-data'
1509
			lthis.actualiserReleveDataIdObs( idObs, transfertDatas.id );
1510
			// mise à jour du nombre d'obs à transmettre
1511
			// et suppression de l'obs
1512
			lthis.supprimerObsParId( idObs, true );
1513
			lthis.nbObsEnCours++;
1514
			// mise à jour du statut
1515
			lthis.mettreAJourProgression();
1516
			if( 0 < lthis.obsNbre ) {
1517
				// dépilement de la suivante
1518
				lthis.depilerObsPourEnvoi();
1519
			}
1520
		},
1521
		statusCode  : {
1522
			500 : function( jqXHR, textStatus, errorThrown ) {
1523
				erreurMsg += lthis.utils.msgTraduction( 'erreur' ) + ' 500 :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1524
				}
1525
		},
1526
		error        : function( jqXHR, textStatus, errorThrown ) {
1527
			erreurMsg += lthis.utils.msgTraduction( 'erreur-ajax' ) + ' :\ntype : ' + textStatus + ' ' + errorThrown + '\n';
1528
			try {
1529
				reponse = jQuery.parseJSON( jqXHR.responseText );
1530
				if ( null !== reponse ) {
1531
					$.each( reponse, function( cle, valeur ) {
1532
						erreurMsg += valeur + '\n';
1533
					});
1534
				}
1535
			} catch( e ) {
1536
				erreurMsg += lthis.utils.msgTraduction( 'erreur-inconnue' ) + ' : ' + jqXHR.responseText;
1537
			}
1538
		},
1539
		complete      : function( jqXHR, textStatus ) {
1540
			var debugMsg = extraireEnteteDebug( jqXHR );
1541
 
1542
			if ( '' !== erreurMsg ) {
1543
				if ( lthis.debug ) {
1544
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-erreur">' + erreurMsg + '</pre>' );
1545
					$( '#dialogue-obs-transaction-ko .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1546
				}
1547
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1548
					'subject=Dysfonctionnement du widget de saisie ' + lthis.tagProjet+
1549
					'&body=' + erreurMsg + '%0D%0ADébogage :%0D%0A' + debugMsg;
1550
 
1551
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1552
				$( '#obs' + idObs + ' div div' ).addClass( 'obs-erreur' );
1553
				// window.location.hash = 'obs' + idObs;
1554
 
1555
				$( '#dialogue-obs-transaction-ko .alert-txt' ).append(
1556
					$( '#tpl-transmission-ko' ).clone()
1557
						.find( '.courriel-erreur' )
1558
						.attr( 'href', hrefCourriel )
1559
						.end()
1560
						.html()
1561
				);
1562
				$( '#dialogue-obs-transaction-ko' ).removeClass( 'hidden' );
1563
				$( '#chargement' ).addClass( 'hidden' );
1564
				lthis.initialiserBarreProgression;
1565
			} else {
1566
				if ( lthis.debug ) {
1567
					$( '#dialogue-obs-transaction-ok .alert-txt' ).append( '<pre class="msg-debug">Débogage : ' + debugMsg + '</pre>' );
1568
				}
1569
				if( 0 === lthis.obsNbre ) {
1570
					setTimeout( function() {
1571
						$( '#chargement,#bloc-arbres-gauche,#bloc-controle-liste-obs' ).addClass( 'hidden' );
1572
						$( '#dialogue-obs-transaction-ok .alert-txt' ).append( $( '#tpl-transmission-ok' ).clone().html() );
1573
						$( '#dialogue-obs-transaction-ok,#bouton-saisir-lichens' ).removeClass( 'hidden' );
1574
					}, 1500 );
1575
				}
1576
			}
1577
		}
1578
	});
1579
};
1580
 
1581
ReleveLg.prototype.mettreAJourProgression = function() {
1582
	this.nbObsTransmises++;
1583
 
1584
	var pct = ( this.nbObsTransmises / this.totalObsATransmettre ) * 100;
1585
 
1586
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', this.nbObsTransmises );
1587
	$( '#barre-progression-upload' ).css( 'width', pct + '%' );
1588
	$( '#barre-progression-upload .sr-only' ).text( this.nbObsTransmises + '/' + this.totalObsATransmettre + ' ' + this.utils.msgTraduction( 'observations-transmises' ) );
1589
	if( 0 === this.obsNbre ) {
1590
		$( '.progress' ).removeClass( 'active' );
1591
		$( '.progress' ).removeClass( 'progress-bar-striped' );
1592
	}
1593
};
1594
 
1595
ReleveLg.prototype.initialiserBarreProgression = function() {
1596
	$( '#barre-progression-upload' ).attr( 'aria-valuenow', 0 );
1597
	$( '#barre-progression-upload' ).css( 'width', '0%' );
1598
	$( '#barre-progression-upload .sr-only' ).text( '0/0 ' + this.utils.msgTraduction( 'observations-transmises' ) );
1599
	$( '.progress' ).addClass( 'active' );
1600
	$( '.progress' ).addClass( 'progress-bar-striped' );
1601
};
1602
 
1603
// Form Validator *************************************************************/
1604
ReleveLg.prototype.configurerFormValidator = function() {
1605
	const lthis = this;
1606
 
1607
	$.validator.addMethod(
1608
		'dateCel',
1609
		function ( value, element ) {
1610
			return ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( value ) );
1611
		},
1612
		lthis.utils.msgTraduction( 'date-incomplete' )
1613
	);
1614
 
1615
	$.validator.addMethod(
1616
		'userEmailOk',
1617
		function ( value, element ) {
1618
			return ( lthis.utils.valOk( value ) );
1619
		},
1620
		''
1621
	);
1622
	$.validator.addMethod(
1623
		'minMaxOk',
1624
		function ( value, element, param ) {
1625
			$.validator.messages.minMaxOk = lthis.validerMinMax( element ).message;
1626
			return lthis.validerMinMax( element ).cond;
1627
		},
1628
		$.validator.messages.minMaxOk
1629
	);
1630
	$.validator.addMethod(
1631
		'listFields',
1632
		function ( value, element ) {
1633
			return ( lthis.utils.valOk( value ) );
1634
		},
1635
		''
1636
	);
1637
 
1638
	$.extend( $.validator.defaults, {
1639
		errorElement: 'span',
1640
		errorPlacement: function( error, element ) {
1641
			if ( 'checkbox' === element.attr( 'type' ) || 'radio' === element.attr( 'type' ) ) {
1642
				error.appendTo( element.closest( '.list' ) );
1643
			} else {
1644
				element.after( error );
1645
			}
1646
		},
1647
		onfocusout: function( element ) {
1648
			if ( $( element ).valid() ) {
1649
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1650
			} else {
1651
				$( element ).closest( '.control-group' ).addClass( 'error' );
1652
			}
1653
		},
1654
		onkeyup : function( element ) {
1655
			if ( $( element ).valid() ) {
1656
				$( element ).closest( '.control-group' ).removeClass( 'error' );
1657
			} else {
1658
				$( element ).closest( '.control-group' ).addClass( 'error' );
1659
			}
1660
		},
1661
		unhighlight: function( element ) {
1662
			$( element ).closest( '.control-group' ).removeClass( 'error' );
1663
		},
1664
		highlight: function( element ) {
1665
			$( element ).closest( '.control-group' ).addClass( 'error' );
1666
		}
1667
	});
1668
};
1669
 
1670
ReleveLg.prototype.validerMinMax = function( element ) {
1671
	var mMCond      = new Boolean(),
1672
		minCond     = parseFloat( element.value ) >= parseFloat( element.min ),
1673
		maxCond     = parseFloat( element.value ) <= parseFloat( element.max ),
1674
		messageMnMx = 'La valeur entrée doit être',
1675
		returnMnMx  = { cond : true , message : '' };
1676
 
1677
	if (
1678
			( this.utils.valOk( element.type, true, 'number' ) || this.utils.valOk( element.type, true, 'range' ) ) &&
1679
			( this.utils.valOk( element.min ) || this.utils.valOk( element.max ) )
1680
		) {
1681
 
1682
		if ( element.min && element.max ) {
1683
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
1684
			mnMxCond     = ( minCond && maxCond );
1685
		} else if ( element.min ) {
1686
			messageMnMx += ' supérieure à ' + element.min;
1687
			mnMxCond     = minCond;
1688
		} else {
1689
			messageMnMx += ' inférieure à ' + element.max;
1690
			mnMxCond     = maxCond;
1691
		}
1692
		returnMnMx.cond    = mnMxCond;
1693
		returnMnMx.message = messageMnMx;
1694
	}
1695
 
1696
	return returnMnMx;
1697
};
1698
 
1699
/**
1700
 * Valider date/rue/commune par rapport aux relevés précédents
1701
 */
1702
ReleveLg.prototype.validerDateRueCommune = function( valeurDate, valeurRue, valeurCmn ) {
1703
	var valide = true;
1704
 
1705
	if (
1706
		this.utils.valOk( $( '#dates-rues-communes' ).val() ) &&
1707
		this.utils.valOk( valeurDate ) &&
1708
		this.utils.valOk( valeurRue ) &&
1709
		this.utils.valOk( valeurCmn )
1710
	) {
1711
		var valsEltDRC = $.parseJSON( $( '#dates-rues-communes' ).val() ),
1712
			valeurDRC = valeurDate + valeurRue + valeurCmn;
1713
		valide = ( -1 === valsEltDRC.indexOf( valeurDRC ) );
1714
 
1715
	}
1716
	return valide;
1717
};
1718
 
1719
/**
1720
 * FormValidator pour les champs date/rue/Commune
1721
 */
1722
ReleveLg.prototype.dateRueCommuneFormValidator = function() {
1723
	var dateValid    = ( /^(?:[0-9]{4}-[0-9]{2}-[0-9]{2})|(?:[0-9]{2}\/[0-9]{2}\/[0-9]{4})$/.test( $( '#releve-date' ).val() ) ),
1724
		geolocValid  = ( this.utils.valOk( $( '#commune-nom' ).val() ) && this.utils.valOk( $( '#rue' ).val() ) );
1725
	const errorDateRue =
1726
			'<span id="error-drc" class="error">'+
1727
				this.utils.msgTraduction( 'date-rue' )+
1728
			'</span> ';
1729
 
1730
	if( this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val()  ) ) {
1731
		$( '#releve-date' )
1732
			.removeClass( 'erreur' )
1733
			.closest( '.control-group' )
1734
				.removeClass( 'error' )
1735
				.find( '#error-drc' )
1736
					.remove();
1737
		if ( geolocValid ) {
1738
			$( '#geoloc' )
1739
			.closest( '.control-group' )
1740
				.removeClass( 'error' );
1741
		}
1742
		$( '#geoloc #error-drc' ).remove();
1743
	} else {
1744
		$( '#releve-date' )
1745
			.addClass( 'erreur' )
1746
			.closest( '.control-group' )
1747
				.addClass( 'error' );
1748
		if ( !this.utils.valOk( $( '#releve-date' ).closest( '.control-group' ).find( '#error-drc' ) ) ) {
1749
			$( '#releve-date' ).after( errorDateRue );
1750
		}
1751
		$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
1752
		if ( !this.utils.valOk( $( '#geoloc' ).find( '#error-drc' ) ) ) {
1753
			$( '#geoloc' ).prepend( errorDateRue );
1754
		}
1755
	}
1756
	if ( dateValid ) {
1757
		$( '#releve-date' ).closest( '.control-group span.error' ).not( '#error-drc' ).remove();
1758
	}
1759
};
1760
 
1761
ReleveLg.prototype.definirReglesFormValidator = function() {
1762
	const lthis = this;
1763
 
1764
	$( '#form-observation' ).validate({
1765
		rules : {
1766
			latitude : {
1767
				required : true,
1768
				minlength : 1,
1769
				range : [-90, 90]
1770
			},
1771
			longitude : {
1772
				required : true,
1773
				minlength : 1,
1774
				range : [-180, 180]
1775
			}
1776
		}
1777
	});
1778
	$( 'input[type=date]' ).not( '#releve-date' ).on( 'input', function() {
1779
		$( this ).valid();
1780
	});
1781
	// validation date/rue/commune au démarage
1782
	this.dateRueCommuneFormValidator();
1783
	// validation date/rue/commune sur event
1784
	$( '#releve-date,#rue,#commune-nom' ).on( 'change input focusout', this.dateRueCommuneFormValidator.bind( this ) );
1785
	$( '#form-arbre' ).validate({
1786
		rules : {
1787
			taxon : {
1788
				required : true,
1789
				minlength : 1
1790
			},
1791
			certitude : {
1792
				required : true,
1793
				minlength : 1
1794
			},
1795
			'latitude-arbres' : {
1796
				required : true,
1797
				minlength : 1,
1798
				range : [-90, 90]
1799
			},
1800
			'longitude-arbres' : {
1801
				required : true,
1802
				minlength : 1,
1803
				range : [-180, 180]
1804
			},
1805
			'rue-arbres' : {
1806
				required : true,
1807
				minlength : 1
1808
			}
1809
		}
1810
	});
1811
	$( '#form-arbre-fs' ).validate({
1812
		onkeyup : false,
1813
		onclick : false,
1814
		rules : {
1815
			circonference : {
1816
				required : true,
1817
				minlength : 1//,
1818
				//'minMaxOk' : true
1819
			},
1820
			'surface-pied' : {
1821
				required : true,
1822
				minlength : 1,
1823
				'minMaxOk' : true
1824
			},
1825
			'equipement-pied-arbre' : {
1826
				required : true,
1827
				minlength : 1
1828
			},
1829
			'face-ombre' : {
1830
				required : true,
1831
				minlength : 1
1832
			}
1833
		}
1834
	});
1835
	$( '#equipement-pied-arbre' ).change( function() {
1836
		if ( lthis.utils.valOk( $( this ).val(), false, 'other' ) ) {
1837
			$( this )
1838
				.closest( '.control-group' )
1839
					.removeClass( 'error' )
1840
					.find( 'span.error' )
1841
						.addClass( 'hidden' );
1842
		}
1843
	});
1844
	$( '#form-observateur' ).validate({
1845
		rules : {
1846
			courriel : {
1847
				required : true,
1848
				minlength : 1,
1849
				email : true,
1850
				'userEmailOk' : true
1851
			},
1852
			mdp : {
1853
				required : true,
1854
				minlength : 1
1855
			}
1856
		}
1857
	});
1858
	$( '#face-ombre input' ).click( function() {
1859
		var oneIsChecked = false;
1860
		$( '#face-ombre input' ).each( function() {
1861
			if ( $( this ).is( ':checked' ) ) {
1862
				oneIsChecked = true;
1863
				return false;
1864
			}
1865
		});
1866
		if ( oneIsChecked ) {
1867
			$( '#face-ombre.control-group' )
1868
				.removeClass( 'error' )
1869
				.find( 'span.error' )
1870
					.addClass( 'hidden' );
1871
		} else {
1872
			$( '#face-ombre.control-group' )
1873
				.addClass( 'error' )
1874
				.find( 'span.error' )
1875
					.removeClass( 'hidden' );
1876
		}
1877
	});
1878
	$( '#connexion,#inscription,#oublie' ).click( function() {
1879
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1880
	});
1881
};
1882
 
1883
/**
1884
 * Valide le formulaire Relevé (= étape 1) au click sur un bouton "enregistrer"
1885
 */
1886
ReleveLg.prototype.validerReleve = function() {
1887
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1888
	const obs         = $( '#form-observation' ).valid();
1889
	const geoloc      = (
1890
		this.utils.valOk( $( '#latitude' ).val() ) &&
1891
		this.utils.valOk( $( '#longitude' ).val() ) &&
1892
		this.utils.valOk( $( '#rue' ).val() ) &&
1893
		this.utils.valOk( $( '#commune-nom' ).val() )
1894
	) ;
1895
	var dateRue = true;
1896
	if ( this.utils.valOk( $( '#dates-rues-communes' ).val() ) ) {
1897
		dateRue = (
1898
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1899
			this.utils.valOk( $( '#rue' ).val() ) &&
1900
			this.validerDateRueCommune( $( '#releve-date' ).val(), $( '#rue' ).val(), $( '#commune-nom' ).val() )
1901
		);
1902
	}
1903
	const validerReleve = ( observateur && obs && geoloc && dateRue );
1904
 
1905
	if ( !obs ) {
1906
		$( 'html, body' ).stop().animate({
1907
			scrollTop: $( '#zone-observation' ).offset().top
1908
		}, 300 );
1909
	}
1910
	// panneau observateur
1911
	if ( observateur ) {
1912
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1913
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1914
	} else {
1915
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1916
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1917
	}
1918
	if ( dateRue && geoloc ) {
1919
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1920
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
1921
	} else {
1922
		if (
1923
			this.utils.valOk( $( '#releve-date' ).val() ) &&
1924
			this.utils.valOk( $( '#rue' ).val() ) &&
1925
			this.utils.valOk( $( '#dates-rues-communes' ).val() )
1926
		) {
1927
			this.afficherPanneau( '#dialogue-date-rue-ko' );
1928
		}
1929
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
1930
	}
1931
	if (
1932
		!this.utils.valOk( $( '#releve-date' ).val() ) ||
1933
		!this.utils.valOk( $( '#rue' ).val() ) ||
1934
		!this.utils.valOk( $( '#dates-rues-communes' ).val() )
1935
	) {
1936
		this.masquerPanneau( '#dialogue-date-rue-ko' );
1937
	}
1938
	if ( geoloc ) {
1939
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1940
		if ( dateRue ) {
1941
			$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
1942
		}
1943
	} else {
1944
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1945
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
1946
	}
1947
 
1948
	return validerReleve;
1949
};
1950
 
1951
/**
1952
 * Valide le formulaire Arbres (= étape 2) au click sur un bouton "suivant"
1953
 */
1954
ReleveLg.prototype.validerArbres = function( etapeReleve = false ) {
1955
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() )
1956
	const geoloc      = (
1957
		this.utils.valOk( $( '#latitude-arbres' ).val() ) &&
1958
		this.utils.valOk( $( '#longitude-arbres' ).val() ) &&
1959
		this.utils.valOk( $( '#rue-arbres' ).val() ) &&
1960
		this.utils.valOk( $( '#commune-nom-arbres' ).val() )
1961
	);
1962
	const piedArbre = this.utils.valOk( $( '#equipement-pied-arbre' ).val(), false, 'other' );
1963
	const taxon = this.utils.valOk( $( '#taxon' ).val() );
1964
	const obs   = (
1965
		$( '#form-observation' ).valid() &&
1966
		$( '#form-arbre' ).valid() &&
1967
		$( '#form-arbre-fs' ).valid() &&
1968
		piedArbre
1969
	);
1970
 
1971
	if ( piedArbre ) {
1972
		$( '#equipement-pied-arbre' )
1973
			.closest( '.control-group' )
1974
				.removeClass( 'error' )
1975
				.find( 'span.error' )
1976
					.addClass( 'hidden' );
1977
	} else {
1978
		$( '#equipement-pied-arbre' )
1979
			.closest( '.control-group' )
1980
				.addClass( 'error' )
1981
				.find( 'span.error' )
1982
					.removeClass( 'hidden' );
1983
	}
1984
	if ( geoloc ) {
1985
		this.masquerPanneau( '#dialogue-geoloc-ko' );
1986
		$( '.geoloc' ).closest( '.control-group' ).removeClass( 'error' );
1987
	} else {
1988
		this.afficherPanneau( '#dialogue-geoloc-ko' );
1989
		$( '.geoloc' ).closest( '.control-group' ).addClass( 'error' );
1990
	}
1991
	// panneau observateur
1992
	if ( observateur ) {
1993
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
1994
		$( '#tb-observateur .control-group' ).removeClass( 'error' );
1995
	} else {
1996
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
1997
		$( '#tb-observateur .control-group' ).addClass( 'error' );
1998
	}
1999
 
2000
	return ( observateur && obs && geoloc && taxon );
2001
};
2002
 
2003
// Controle des panneaux d'infos **********************************************/
2004
 
2005
ReleveLg.prototype.afficherPanneau = function( selecteur ) {
2006
	$( selecteur )
2007
		.removeClass( 'hidden' )
2008
		.hide()
2009
		.show( 600 )
2010
		.delay( this.dureeMessage )
2011
		.hide( 600 );
2012
	$( 'html, body' ).stop().animate({scrollTop: $( selecteur ).offset().top}, 300);
2013
};
2014
 
2015
ReleveLg.prototype.masquerPanneau = function( selecteur ) {
2016
	$( selecteur ).addClass( 'hidden' );
2017
};
2018
 
2019
ReleveLg.prototype.fermerPanneauAlert = function() {
2020
	$( this ).parentsUntil( '.zone-alerte', '.alert' ).addClass( 'hidden' );
2021
};
2022
 
2023
// lib hors objet --
2024
 
2025
/**
2026
* Stope l'évènement courant quand on clique sur un lien.
2027
* Utile pour Chrome, Safari...
2028
*/
2029
function arreter( event ) {
2030
	if ( event.stopPropagation ) {
2031
		event.stopPropagation();
2032
	}
2033
	if ( event.preventDefault ) {
2034
		event.preventDefault();
2035
	}
2036
 
2037
	return false;
2038
}
2039
 
2040
/**
2041
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
2042
 * @param jqXHR
2043
 * @returns {String}
2044
 */
2045
function extraireEnteteDebug( jqXHR ) {
2046
	var msgDebug = '';
2047
 
2048
	if ( '' !== jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) ) {
2049
		var debugInfos = jQuery.parseJSON( jqXHR.getResponseHeader( 'X-DebugJrest-Data' ) );
2050
		if ( null !== debugInfos ) {
2051
			$.each( debugInfos, function( cle, valeur ) {
2052
				msgDebug += valeur + '\n';
2053
			});
2054
		}
2055
	}
2056
 
2057
	return msgDebug;
2058
}
2059
 
2060
/*
2061
 * jQuery UI Autocomplete HTML Extension
2062
 *
2063
 * Copyright 2010, Scott González (http://scottgonzalez.com)
2064
 * Dual licensed under the MIT or GPL Version 2 licenses.
2065
 *
2066
 * http://github.com/scottgonzalez/jquery-ui-extensions
2067
 *
2068
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
2069
 */
2070
( function( $ ) {
2071
	var proto      = $.ui.autocomplete.prototype,
2072
		initSource = proto._initSource;
2073
 
2074
	ReleveLg.prototype.filter = function( array, term ) {
2075
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), 'i' );
2076
 
2077
		return $.grep( array, function( value ) {
2078
 
2079
			return matcher.test( $( '<div>' ).html( value.label || value.value || value ).text() );
2080
		});
2081
	}
2082
	$.extend( proto, {
2083
		_initSource: function() {
2084
			if ( this.options.html && $.isArray( this.options.source ) ) {
2085
				this.source = function( request, response ) {
2086
					response( filter( this.options.source, request.term ) );
2087
				};
2088
			} else {
2089
				initSource.call( this );
2090
			}
2091
		},
2092
		_renderItem: function( ul, item) {
2093
			if ( item.retenu ) {
2094
				item.label = '<strong>' + item.label + '</strong>';
2095
			}
2096
 
2097
			return $( '<li></li>' )
2098
				.data( 'item.autocomplete', item )
2099
				.append( $( '<a></a>' )[ ( this.options.html ) ? 'html' : 'text' ]( item.label ) )
2100
				.appendTo( ul );
2101
		}
2102
	});
2103
})( jQuery );