Subversion Repositories eFlore/Applications.cel

Rev

Rev 3324 | Go to most recent revision | Details | Last modification | View Log | RSS feed

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