Subversion Repositories eFlore/Applications.cel

Rev

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