Subversion Repositories eFlore/Applications.cel

Rev

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

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