Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
3844 idir 1
import {WidgetsSaisiesCommun,utils} from './WidgetsSaisiesCommun.js';
2
import {valOk} from './Utils.js';
3
 
3638 delphine 4
/**
5
 * Constructeur WidgetSaisie par défaut
6
 */
3844 idir 7
function WidgetSaisie(  ) {
8
	if  ( valOk(widgetProp) ) {
9
		this.urlWidgets                        = widgetProp.urlWidgets;
10
		this.projet                            = widgetProp.projet;
11
		this.idProjet                          = widgetProp.idProjet;
12
		this.tagsMotsCles                      = widgetProp.tagsMotsCles;
13
		this.mode                              = widgetProp.mode;
14
		this.langue                            = widgetProp.langue;
15
		this.serviceAnnuaireIdUrl              = widgetProp.serviceAnnuaireIdUrl;
16
		this.serviceNomCommuneUrl              = widgetProp.serviceNomCommuneUrl;
17
		this.serviceNomCommuneUrlAlt           = widgetProp.serviceNomCommuneUrlAlt;
18
		this.debug                             = widgetProp.debug;
19
		this.html5                             = widgetProp.html5;
20
		this.serviceSaisieUrl                  = widgetProp.serviceSaisieUrl;
21
		this.serviceObsUrl                     = widgetProp.serviceObsUrl;
22
		this.chargementImageIconeUrl           = widgetProp.chargementImageIconeUrl;
23
		this.pasDePhotoIconeUrl                = widgetProp.pasDePhotoIconeUrl;
24
		this.autocompletionElementsNbre        = widgetProp.autocompletionElementsNbre;
25
		this.serviceAutocompletionNomSciUrl    = widgetProp.serviceAutocompletionNomSciUrl;
26
		this.serviceAutocompletionNomSciUrlTpl = widgetProp.serviceAutocompletionNomSciUrlTpl;
27
		this.dureeMessage                      = widgetProp.dureeMessage;
28
		this.obsMaxNbre                        = widgetProp.obsMaxNbre;
29
		this.tagImg                            = widgetProp.tagImg;
30
		this.tagObs                            = widgetProp.tagObs;
31
		this.obsId                             = widgetProp.obsId;
32
		this.nomSciReferentiel                 = widgetProp.nomSciReferentiel;
33
		this.especeImposee                     = widgetProp.especeImposee;
34
		this.infosEspeceImposee                = widgetProp.infosEspeceImposee;
35
		this.referentielImpose                 = widgetProp.referentielImpose;
36
		this.isTaxonListe                      = widgetProp.isTaxonListe;
3881 delphine 37
		this.photoObligatoire                  = widgetProp.photoObligatoire;
3638 delphine 38
	}
39
	this.urlRacine            = window.location.origin;
40
	this.obsNbre              = 0;
41
	this.nbObsEnCours         = 1;
42
	this.totalObsATransmettre = 0;
43
	this.nbObsTransmises      = 0;
44
	this.observer             = null;
45
	this.isASL                = false;
3844 idir 46
	this.geoloc               = {};
3638 delphine 47
}
48
WidgetSaisie.prototype = new WidgetsSaisiesCommun();
49
 
50
/**
51
 * Initialise le formulaire, les validateurs, les listes de complétion...
52
 */
53
WidgetSaisie.prototype.initForm = function() {
54
	this.initFormConnection();
3844 idir 55
	if ( valOk( this.obsId ) ) {
3638 delphine 56
		this.chargerInfoObs();
57
	}
58
	if( this.isTaxonListe ) {
59
		this.initFormTaxonListe();
60
	} else {
61
		this.ajouterAutocompletionNoms();
62
	}
63
	// au rafraichissement de la page,
64
	// les input date semblent conserver la valeur entrée précedemment
65
	// c'est voulu après la création d'une obs mais pas quand la page est actualisée
66
	// Déjà tenté: onbeforeunload avec un location.reload(true) n'a pas permis de le faire
67
	$( 'input[type=date]' ).each( function () {
3844 idir 68
		( valOk( $( this ).data( 'default' ) ) ) ? $( this ).val( $( this ).data( 'default' ) ) : $( this ).val( '' );
3638 delphine 69
	});
70
	this.configurerFormValidator();
71
	this.definirReglesFormValidator();
72
 
73
	if( this.especeImposee ) {
74
		$( '#taxon' ).attr( 'disabled', 'disabled' );
75
		$( '#taxon-input-groupe' ).attr( 'title', '' );
76
		// Bricolage cracra pour avoir le nom retenu avec auteur (nom_retenu.libelle ne le mentionne pas)
3844 idir 77
		const infosEspeceImposee = $.parseJSON( this.infosEspeceImposee );
78
		let nomRetenuComplet   = infosEspeceImposee.nom_retenu_complet;
79
		const debutAnneRefBiblio = nomRetenuComplet.indexOf( ' [' );
80
 
3638 delphine 81
		if ( -1 !== debutAnneRefBiblio ) {
82
			nomRetenuComplet = nomRetenuComplet.substr( 0, debutAnneRefBiblio );
83
		}
84
		// fin bricolage cracra
3844 idir 85
		const infosAssociee = {
3638 delphine 86
			label : infosEspeceImposee.nom_sci_complet,
87
			value : infosEspeceImposee.nom_sci_complet,
88
			nt : infosEspeceImposee.num_taxonomique,
89
			nomSel : infosEspeceImposee.nom_sci,
90
			nomSelComplet : infosEspeceImposee.nom_sci_complet,
91
			numNomSel : infosEspeceImposee.id,
92
			nomRet : nomRetenuComplet,
93
			numNomRet : infosEspeceImposee['nom_retenu.id'],
94
			famille : infosEspeceImposee.famille,
95
			retenu : ( 'false' === infosEspeceImposee.retenu ) ? false : true
96
		};
97
		$( '#taxon' ).data( infosAssociee );
98
	}
99
};
100
 
101
/**
102
 * Initialise les écouteurs d'événements
103
 */
104
WidgetSaisie.prototype.initEvts = function() {
105
	// identité
106
	this.initEvtsConnection();
107
	// on location, initialisation de la géoloc
108
	this.initEvtsGeoloc();
109
	// Sur téléchargement image
110
	this.initEvtsFichier();
111
 
112
	$( '#referentiel' ).on( 'change', this.surChangementReferentiel.bind( this ) );
113
	// Création / Suppression / Transmission des obs
114
	// Défilement des miniatures dans le résumé obs
115
	this.initEvtsObs();
116
	// Alertes et aides
117
	this.initEvtsAlertes();
118
	// message avant de quitter le formulaire
119
	this.confirmerSortie();
120
};
121
 
122
// Identité Observateur par courriel
123
WidgetSaisie.prototype.requeterIdentiteCourriel = function() {
3844 idir 124
	const lthis = this,
125
		courriel    = $( '#courriel' ).val(),
126
		urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
3638 delphine 127
 
3844 idir 128
	if ( valOk( courriel ) ) {
3638 delphine 129
		$.ajax({
130
			url : urlAnnuaire,
131
			type : 'GET',
132
			success : function( data, textStatus, jqXHR ) {
133
				if ( lthis.debug ) {
134
					console.log( 'SUCCESS: ' + textStatus );
135
				}
3844 idir 136
				if ( valOk( data ) && valOk( data[courriel] ) ) {
137
					const infos = data[courriel];
3638 delphine 138
					lthis.surSuccesCompletionCourriel( infos, courriel );
139
				} else {
140
					lthis.surErreurCompletionCourriel();
141
				}
142
			},
143
			error : function( jqXHR, textStatus, errorThrown ) {
144
				if ( lthis.debug ) {
145
					console.log( 'ERREUR: '+ textStatus );
146
				}
147
				lthis.surErreurCompletionCourriel();
148
			},
149
			complete : function( jqXHR, textStatus ) {
150
				if ( lthis.debug ) {
151
					console.log( 'COMPLETE: '+ textStatus );
152
				}
153
			}
154
		});
155
	}
156
};
157
 
158
// se déclanche quand on choisit "Observation sans inscription" mais que le mail entré est incrit à Tela
159
WidgetSaisie.prototype.surSuccesCompletionCourriel = function( infos, courriel ) {
160
	if ( $( '#utilisateur-connecte' ).hasClass( 'hidden' ) ) {// si quelque chose a foiré après actualisation
3844 idir 161
		if ( !valOk( $( '#warning-identite' ) ) ) {
3638 delphine 162
			$( '#zone-courriel' ).before( '<p id="warning-identite" class="warning"><i class="fas fa-exclamation-triangle"></i> ' + this.msgTraduction( 'courriel-connu' ) + '</p>' );
163
		}
164
		$( '#inscription, #zone-prenom-nom, #zone-courriel-confirmation' ).addClass( 'hidden' );
165
		$( '#prenom, #nom, #courriel_confirmation' ).attr( 'disabled', 'disabled' );
166
		$( '.nav.control-group' ).addClass( 'error' );
167
	}
168
};
169
 
170
// se déclanche quand on choisit "Observation sans inscription" et qu'effectivement le mail n'est pas connu de Tela
171
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
172
	$( '#creation-compte, #zone-prenom-nom, #zone-courriel-confirmation' ).removeClass( 'hidden' );
173
	$( '#warning-identite' ).remove();
174
	$( '.nav.control-group' ).removeClass( 'error' );
175
	$( '#prenom, #nom, #courriel_confirmation' ).val( '' ).removeAttr( 'disabled' );
176
};
177
 
178
WidgetSaisie.prototype.testerLancementRequeteIdentite = function( event ) {
3844 idir 179
	if ( valOk( event.which, true, 13 ) ) {
3638 delphine 180
		this.requeterIdentiteCourriel();
181
		event.preventDefault();
182
		event.stopPropagation();
183
	}
184
};
185
 
186
WidgetSaisie.prototype.reduireVoletIdentite = function() {
187
	if ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ) {
188
		$( '#bouton-connexion, #creation-compte' ).addClass( 'hidden' );
189
		$( '#bienvenue').removeClass( 'hidden' );
190
		$( '#inscription, #zone-courriel' ).addClass( 'hidden' );
3844 idir 191
		if ( valOk( $( '#nom' ).val() ) && valOk( $( '#prenom' ).val() ) ) {
3638 delphine 192
			$( '#zone-prenom-nom' ).addClass( 'hidden' );
193
			$( '#bienvenue-prenom' ).text( ' ' + $( '#prenom' ).val() );
194
			$( '#bienvenue-nom' ).text( ' ' + $( '#nom' ).val() );
195
		} else {
196
			$( '#zone-prenom-nom' ).removeClass( 'hidden' );
197
			$( '#bienvenue-prenom,#bienvenue-nom' ).text( '' );
198
		}
199
	} else {
200
		$( '#bouton-connexion, #creation-compte' ).removeClass( 'hidden' );
201
		$( '#bienvenue').addClass( 'hidden' );
202
	}
203
};
204
 
205
 
206
WidgetSaisie.prototype.formaterNom = function() {
207
	$( '#nom' ).val( $( '#nom' ).val().toUpperCase() );
208
};
209
 
210
WidgetSaisie.prototype.formaterPrenom = function() {
3844 idir 211
	const prenom   = [],
3638 delphine 212
		mots       = $( '#prenom' ).val().split( ' ' ),
213
		motsLength = mots.length;
214
 
3844 idir 215
	for ( let i = 0; i < motsLength; i++ ) {
216
		let mot          = mots[i],
217
			motMajuscule = '';
218
 
3638 delphine 219
		if ( 0 <= mot.indexOf( '-' ) ) {
3844 idir 220
			const prenomCompose    = new Array(),
221
				motsComposes       = mot.split( '-' ),
3638 delphine 222
				motsComposesLength = motsComposes.length;
223
 
3844 idir 224
			for ( let j = 0; j < motsComposesLength; j++ ) {
225
				const motSimple    = motsComposes[j];
226
 
227
				motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
3638 delphine 228
				prenomCompose.push( motMajuscule );
229
			}
230
			prenom.push( prenomCompose.join( '-' ) );
231
		} else {
3844 idir 232
			motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
3638 delphine 233
			prenom.push( motMajuscule );
234
		}
235
	}
236
	$( '#prenom' ).val( prenom.join( ' ' ) );
237
};
238
 
239
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
240
	this.afficherPanneau( '#dialogue-bloquer-copier-coller' );
3844 idir 241
 
3638 delphine 242
	return false;
243
};
244
 
245
// Préchargement des infos-obs ************************************************/
246
WidgetSaisie.prototype.chargerInfoObs = function() {
3844 idir 247
	const lthis = this,
248
		urlObs  = this.serviceObsUrl + '/' + this.obsId;
3638 delphine 249
 
250
	$.ajax({
251
		url: urlObs,
252
		type: 'GET',
253
		success: function( data, textStatus, jqXHR ) {
3844 idir 254
			if ( valOk( data ) ) {
3638 delphine 255
				lthis.prechargerForm( data );
256
			} else {
257
				lthis.surErreurChargementInfosObs.bind( lthis );
258
			}
259
		},
260
		error: function( jqXHR, textStatus, errorThrown ) {
261
			lthis.surErreurChargementInfosObs();
262
		}
263
	});
264
};
265
 
266
// @TODO faire mieux que ça !
267
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
3844 idir 268
	utils.activerModale( this.msgTraduction( 'erreur-chargement' ) );
3638 delphine 269
};
270
 
271
WidgetSaisie.prototype.prechargerForm = function( data ) {
272
	$( '#milieu' ).val( data.milieu );
273
	$( '#commune-nom' ).text( data.zoneGeo );
274
	if( data.hasOwnProperty( 'codeZoneGeo' ) ) {
275
	  // TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
276
	  $( '#commune-insee' ).text( data.codeZoneGeo.replace( 'INSEE-C:', '' ) );
277
	}
278
 
279
	if( data.hasOwnProperty( 'latitude' ) && data.hasOwnProperty( 'longitude' ) ) {
280
		// $cartoRemplacee = $( '#tb-geolocation' ),
281
		// suffixe = '',
282
		// layer = 'osm',
283
		// zoomInit = 18
3844 idir 284
		const typeLocalisation = $( '#top' ).data( 'type-loc' ),
285
			donnesResetCarto   = {
3638 delphine 286
			latitude         : data.latitude,
287
			longitude        : data.longitude,
3844 idir 288
			typeLocalisation : typeLocalisation,
289
			zoom             : 18
3638 delphine 290
		};
291
		this.transfererCarto( donnesResetCarto );
292
	}
293
};
294
 
295
// Ajouter Obs ****************************************************************/
296
/**
297
 * Retourne un Array contenant les valeurs des champs étendus
298
 */
299
WidgetSaisie.prototype.getObsChpSpecifiques = function() {
3844 idir 300
	const lthis = this,
301
		champs    = [],
3638 delphine 302
		$thisForm = $( '#form-supp' ),
303
		elements  =
304
			'input[type=text]:not(.collect-other),'+
305
			'input[type=checkbox]:checked,'+
306
			'input[type=radio]:checked,'+
307
			'input[type=email],'+
308
			'input[type=number],'+
309
			'input[type=range],'+
310
			'input[type=date],'+
311
			'textarea,'+
312
			'.select',
3844 idir 313
		retour    = [];
3638 delphine 314
 
315
	$( elements, $thisForm ).each( function() {
3844 idir 316
		if ( valOk( $( this ).val() ) && ( valOk( $( this ).attr( 'name' ) ) || valOk( $( this ).data( 'name' ) ) ) ) {
317
			const valeur = $( this ).val(),
318
				cle    = ( valOk( $( this ).attr( 'name' ) ) ) ? $( this ).attr( 'name' ) : $( this ).data( 'name' );
3638 delphine 319
			if ( cle in champs ) {
320
				champs[cle] += ';' + valeur;
321
			} else {
322
				champs[cle] = valeur;
323
			}
324
		}
325
	});
3844 idir 326
	for ( let key in champs ) {
3638 delphine 327
		retour.push({ 'cle' : key , 'valeur' : champs[key] });
328
	}
3844 idir 329
	if ( valOk( $( '#coord-lineaire' ).val() ) ) {
3638 delphine 330
		retour.push({ 'cle' : 'coordonnees-rue-ou-lineaire' , 'valeur' : $( '#coord-lineaire' ).val() });
331
	}
332
	return retour;
333
};
334
 
335
WidgetSaisie.prototype.reinitialiserForm = function() {
336
	this.supprimerMiniatures();
337
	if( !this.especeImposee ) {
338
		$( '#taxon' ).val( '' );
339
		$( '#taxon' ).data( 'numNomSel', '' )
340
			.data( 'nomRet','' )
341
			.data( 'numNomRet', '' )
342
			.data( 'nt', '' )
343
			.data( 'famille', '' );
344
		if( this.isTaxonListe ) {
345
			$( '#taxon-liste' ).find( 'option' ).each( function() {
346
				if ( $( this ).hasClass( 'choisir' ) ) {
347
					$( this ).attr( 'selected', true );
348
				} else {
349
					$( this ).attr( 'selected', false );
350
				}
351
			});
352
			$( '#taxon-input-groupe' ).addClass( 'hidden' );
353
			$('#taxon-autre').val('');
354
		}
355
	}
3844 idir 356
	if ( valOk( $( '#form-supp' ) ) ) {
3638 delphine 357
		$( '#form-supp' ).validate().resetForm();
358
	}
359
};
360
 
361
// Géolocalisation *************************************************************/
362
/**
363
 * Fonction handler de l'évenement location du module tb-geoloc
364
 */
365
WidgetSaisie.prototype.locationHandler = function( location ) {
3844 idir 366
	const locDatas = location.originalEvent.detail;
3638 delphine 367
 
3844 idir 368
	if ( valOk( locDatas ) ) {
3638 delphine 369
		console.log( locDatas );
370
 
3844 idir 371
		const geometry = JSON.stringify( locDatas.geometry ),
372
			altitude   = ( valOk( locDatas.elevation ) ) ? locDatas.elevation : '',
3850 idir 373
			pays       = ( valOk( locDatas.osmCountryCode ) ) ? locDatas.osmCountryCode.toUpperCase() : 'FR',
374
			rue        = ( valOk( locDatas.osmRoad ) ) ? locDatas.osmRoad : '';
3844 idir 375
		let latitude      = '',
376
			longitude     = '',
377
			coordLineaire = '',
378
			nomCommune    = '',
379
			communeInsee  = '';
380
 
381
		if ( valOk( locDatas.geometry.coordinates ) &&
382
			valOk( locDatas.centroid.coordinates ) &&
383
			valOk( locDatas.centroid.coordinates[0] ) &&
384
			valOk( locDatas.centroid.coordinates[1] )
385
		) {
3869 delphine 386
			longitude = locDatas.centroid.coordinates[0];
387
			latitude = locDatas.centroid.coordinates[1];
3638 delphine 388
		}
3844 idir 389
		if ( valOk( locDatas.inseeData ) ) {
3638 delphine 390
			nomCommune = locDatas.inseeData.nom;
3844 idir 391
			communeInsee = ( valOk( locDatas.inseeData.code ) ) ? locDatas.inseeData.code : '';
392
		} else if ( valOk( locDatas.locality ) ) {
3638 delphine 393
			nomCommune = locDatas.locality;
3844 idir 394
		} else if ( valOk( locDatas.locality ) ) {
3638 delphine 395
			nomCommune = locDatas.osmCounty;
396
		}
397
		$( '#geometry' ).val( geometry );
398
		$( '#coord-lineaire' ).val( coordLineaire );
399
		$( '#latitude' ).val( latitude );
400
		$( '#longitude' ).val( longitude );
401
		$( '#commune-nom' ).val( nomCommune );
402
		$( '#commune-insee' ).val( communeInsee );
403
		$( '#altitude' ).val( altitude );
404
		$( '#pays' ).val( pays );
3850 idir 405
		$( '#station' ).val( rue );
3853 idir 406
		$( '#latitude, #longitude' ).valid();
3844 idir 407
		if ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) {
3638 delphine 408
			$( '#geoloc' ).closest( '.control-group' ).removeClass( 'error' );
409
		} else {
410
			$( '#geoloc' ).closest( '.control-group' ).addClass( 'error' );
411
		}
412
	} else {
3844 idir 413
		console.warn( 'Error location' );
3638 delphine 414
	}
415
}
416
 
417
// Form Validator *************************************************************/
418
WidgetSaisie.prototype.chpEtendusValidation = function() {
3844 idir 419
	const lthis = this,
420
		$thisForm = $( '#form-supp' ),
3638 delphine 421
		elements  =
422
			'.checkbox,'+
423
			'.radio,'+
424
			'.checkboxes,'+
425
			'.select,'+
426
			'textarea,'+
427
			'input[type=text]:not(.collect-other),'+
428
			'input[type=email],'+
429
			'input[type=number],'+
430
			'input[type=range],'+
431
			'input[type=date]',
432
		speFields = ['checkbox','radio','checkboxes','select'],
433
		spefieldsCount = speFields.length,
434
		chpSuppValidation = {
435
			rules : {},
436
			messages : {},
437
			minmax : []
438
		},
439
		errors = {},
3844 idir 440
		namesListFields = [];
441
	let picked = '';
3638 delphine 442
 
443
	$( elements, $thisForm ).each( function() {
3844 idir 444
		for( let fieldsClass = 0; spefieldsCount > fieldsClass; fieldsClass++ ) {
445
				const dataName = $( this ).data( 'name' );
3638 delphine 446
 
3844 idir 447
			if ( valOk( $( this ).attr( 'required' ) ) && $( this ).hasClass( speFields[fieldsClass] ) && !valOk( chpSuppValidation.rules[ dataName ] ) ) {
3638 delphine 448
				namesListFields.push( dataName );
449
				chpSuppValidation.rules[ dataName ] = { required : true };
3844 idir 450
				if ( valOk( $( '.other', $( this ) ) ) ) {
3638 delphine 451
					picked = ( 'select' === speFields[fieldsClass] ) ? ':selected' : ':checked';
452
					chpSuppValidation.rules[ 'collect-other-' + dataName.replace( '[]', '' ) ] = {
453
						required : '#other-' + dataName.replace( '[]', '' ) + picked,
454
						minlength: 1
455
					};
456
					chpSuppValidation.messages[ 'collect-other-' + dataName.replace( '[]', '' ) ] = false;
457
				}
458
				chpSuppValidation.rules[ dataName ]['listFields'] = true;
459
				chpSuppValidation.messages[ dataName ] = 'Ce champ est requis :\nVeuillez choisir une option, ou entrer une valeur autre valide.';
460
				errors[dataName] = '.' + speFields[fieldsClass];
461
			}
462
		}
3844 idir 463
		if ( valOk( $( this ).attr( 'name' ) ) && valOk ( $( this ).attr( 'required' ) ) && 0 > $.inArray( $( this ).attr( 'name' ) , namesListFields ) ) {
3638 delphine 464
			chpSuppValidation.rules[ $( this ).attr( 'name' ) ] = { required : true, minlength: 1 };
465
			if(
3844 idir 466
				( valOk( $( this ).attr( 'type' ), true, 'number' ) || valOk( $( this ).attr( 'type' ), true, 'range' ) ) &&
467
				( valOk( $( this )[0].min ) || valOk( $( this )[0].max ) )
3638 delphine 468
			) {
469
				chpSuppValidation.rules[ $( this ).attr('name') ]['minMaxOk'] = true;
470
				chpSuppValidation.messages[ $( this ).attr('name') ] = lthis.validerMinMax( $( this )[0] ).message;
471
			}
472
		}
473
	});
3844 idir 474
	if ( valOk( chpSuppValidation.rules ) ) {
3638 delphine 475
		$.each( chpSuppValidation.rules, function( key ) {
3844 idir 476
			if ( !valOk( chpSuppValidation.messages[key] ) ) {
3638 delphine 477
				chpSuppValidation.messages[key] = 'Ce champ est requis :\nVeuillez entrer une valeur valide.';
478
			}
479
		});
480
		if ( 0 < Object.keys( errors ).length ) {
481
			chpSuppValidation['errors'] = errors;
482
		}
483
	}
484
	return chpSuppValidation;
485
};
486
 
487
WidgetSaisie.prototype.validerMinMax = function( element ) {
3844 idir 488
	const minCond  = parseFloat( element.value ) >= parseFloat( element.min ),
489
		maxCond    = parseFloat( element.value ) <= parseFloat( element.max ),
490
		returnMnMx = { cond : true , message : '' };
491
	let mnMxCond    = new Boolean(),
492
		messageMnMx = 'La valeur entrée doit être';
3638 delphine 493
 
494
	if(
3844 idir 495
		( valOk( element.type, true, 'number' ) || valOk( element.type, true, 'range' ) ) &&
496
		( valOk( element.min ) || valOk( element.max ) )
3638 delphine 497
	) {
498
		if ( element.min && element.max ) {
499
			messageMnMx += ' comprise entre ' + element.min + ' et ' + element.max;
500
			mnMxCond     = ( minCond && maxCond );
501
		} else if ( element.min ) {
502
			messageMnMx += ' supérieure à ' + element.min;
503
			mnMxCond     = minCond;
504
		} else {
505
			messageMnMx += ' inférieure à ' + element.max;
506
			mnMxCond     = maxCond;
507
		}
508
		returnMnMx.cond    = mnMxCond;
509
		returnMnMx.message = messageMnMx;
510
	}
511
	return returnMnMx;
512
 
513
};
514
 
515
WidgetSaisie.prototype.definirReglesFormValidator = function() {
3844 idir 516
	const lthis = this,
517
		formSuppValidation = this.chpEtendusValidation();
3638 delphine 518
 
519
	$( '#form-supp' ).validate({
520
		onclick : function( element ) {
521
			if (
522
				(
3844 idir 523
					valOk( element.type, true, 'checkbox' ) ||
524
					valOk( element.type, true, 'radio' )
3638 delphine 525
				) &&
526
				(
3844 idir 527
					!valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':checked' ) ) ||
528
					valOk( $( '.' + $( element ).attr( 'name' ).replace( '[]', '' ) + ':not(.other):checked' ) ) ||
529
					!valOk( $( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ) ) ||
3638 delphine 530
					$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) ||
531
					(
532
						$( '#other-' + $( element ).attr( 'name' ).replace( '[]', '' ) ).is( ':checked' ) &&
533
						$( element ).closest( '.control-group' ).hasClass('error')
534
					)
535
				)
536
			) {
537
				$( element ).valid();
538
				if ( $( element ).valid() ) {
539
					$( element ).closest( '.control-group' ).removeClass( 'error' );
540
					$( element ).next( $( 'span.error' ) ).remove();
541
				} else {
542
					$( element ).closest( '.control-group' ).addClass( 'error' );
543
				}
544
			}
545
			return false;
546
		},
547
		rules : formSuppValidation.rules,
548
		messages : formSuppValidation.messages,
549
		errorPlacement : function( error , element ) {
550
			if ( 0 < Object.keys( formSuppValidation.errors ).length ) {
3844 idir 551
				const errorsKeys = Object.keys( formSuppValidation.errors );
552
				let thisKey    = '',
3638 delphine 553
					errorsFlag = true;
3844 idir 554
 
555
				for ( let i = 0 ; i < errorsKeys.length ; i++ ) {
3638 delphine 556
					thisKey = errorsKeys[i];
557
					if( $( element ).attr( 'name' ) === thisKey ) {
558
						$( formSuppValidation.errors[thisKey] ).append( error );
559
						errorsFlag = false;
560
					}
561
				}
562
				if ( errorsFlag ) {
563
					error.insertAfter( element );
564
				}
565
			} else {
566
				error.insertAfter( element );
567
			}
568
		}
569
	});
570
	$( '#form-supp .select' ).change( function() {
571
		$( this ).valid();
572
	});
573
	$( 'input[type=date]' ).on( 'input', function() {
574
		$( this ).valid();
575
	});
3851 idir 576
	// Validation taxon
577
	// et gestion des messages d'erreur taxon et images en fonction de la certitude
578
	$( '#taxon, #certitude' ).on( 'change', function() {
579
		lthis.validerTaxonRequis( valOk( $( '#taxon' ).val() ) );
3638 delphine 580
	});
581
	// Validation miniatures avec MutationObserver
582
	this.surPresenceAbsenceMiniature();
583
	$( '#form-observation' ).validate({
584
		rules : {
585
			date_releve : {
586
				required : true,
587
				'dateCel' : true
588
			},
589
			latitude : {
590
				required : true,
591
				minlength : 1,
592
				range : [-90, 90]
593
			},
594
			longitude : {
595
				required : true,
596
				minlength : 1,
597
				range : [-180, 180]
598
			}
599
		}
600
	});
601
	$( '#form-observateur' ).validate({
602
		rules : {
603
			courriel : {
604
				required : true,
605
				email : true,
606
				'userEmailOk' : true
607
			},
608
			courriel_confirmation : {
609
				required : true,
610
				equalTo : '#courriel'
611
			}
612
		}
613
	});
614
	$( '#connexion,#inscription,#bouton-anonyme' ).on( 'click', function( event ) {
615
		$( '.nav.control-group' ).removeClass( 'error' );
616
	});
617
};
618
 
3844 idir 619
 
3851 idir 620
WidgetSaisie.prototype.validerCertitudeTaxonImage = function( hasTaxon = false, hasImages = false ) {
3881 delphine 621
	const isCertain = 'certain' === $( '#certitude' ).val();
622
	let isvalide = true ;
623
 
624
	if ( this.photoObligatoire || !isCertain ) {
625
		isvalide = this.validerImageRequise( hasImages );
3851 idir 626
	}
3881 delphine 627
	if ( isCertain ) {
628
		isvalide &= this.validerTaxonRequis( hasTaxon );
629
	}
630
 
631
	return isvalide;
632
 
633
 
3851 idir 634
};
635
 
636
WidgetSaisie.prototype.validerTaxonRequis = function( hasTaxon = false ) {
637
	const taxonEstRequis = 'certain' === $( '#certitude' ).val();
638
 
3881 delphine 639
	if ( !this.photoObligatoire ) {
640
		$( '#photos-conteneur').removeClass( 'error' )
641
			.find( 'span.error' ).hide();
642
	}
3851 idir 643
 
644
	if ( !hasTaxon && taxonEstRequis ) {
645
		this.afficherPanneau( '#dialogue-taxon-or-image' );
646
		$( '#bloc-taxon' ).addClass( 'error' )
647
			.find( 'span.error' ).show();
648
	} else {
3638 delphine 649
		this.masquerPanneau( '#dialogue-taxon-or-image' );
650
		$( '#bloc-taxon' ).removeClass( 'error' )
651
			.find( 'span.error' ).hide();
3851 idir 652
	}
653
 
654
	if ( taxonEstRequis ) {
655
		return hasTaxon;
656
	}
657
};
658
 
659
WidgetSaisie.prototype.validerImageRequise = function( hasImages = false ) {
660
	$( '#bloc-taxon' ).removeClass( 'error' )
661
			.find( 'span.error' ).hide();
662
 
663
	if ( hasImages ) {
664
		this.masquerPanneau( '#dialogue-taxon-or-image' );
3881 delphine 665
		this.masquerPanneau( '#dialogue-image-requise' );
3638 delphine 666
		$( '#fichier' ).parent( 'label.label-file' ).removeClass( 'error' );
667
		$( '#photos-conteneur').removeClass( 'error' ).find( 'span.error' ).hide();
668
	} else {
3881 delphine 669
		if ( this.photoObligatoire ) {
670
			this.afficherPanneau( '#dialogue-image-requise' );
671
		} else {
672
			this.afficherPanneau( '#dialogue-taxon-or-image' );
673
		}
3638 delphine 674
		$( '#fichier' ).parent( 'label.label-file' ).addClass( 'error' );
675
		$( '#photos-conteneur').addClass( 'error' ).find( 'span.error' ).show();
676
	}
3851 idir 677
	return hasImages;
3638 delphine 678
};
679
 
680
WidgetSaisie.prototype.surPresenceAbsenceMiniature = function() {
681
	const lthis = this;
682
	// voir : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
683
	// Selectionne le noeud dont les mutations seront observées
3844 idir 684
	const targetNode = document.getElementById( 'miniatures' );
3638 delphine 685
	// Fonction callback à éxécuter quand une mutation est observée
3844 idir 686
	const callback = mutationsList => {
687
		for( let mutation of mutationsList ) {
3851 idir 688
			lthis.validerCertitudeTaxonImage(
689
				valOk( $( '#taxon' ).val() ),
690
 
691
			);
3638 delphine 692
		}
693
	};
694
	// Créé une instance de l'observateur lié à la fonction de callback
695
	this.observer = new MutationObserver( callback );
696
	// Commence à observer le noeud cible pour les mutations précédemment configurées
697
	this.observer.observe( targetNode, { childList: true } );
698
};
699
 
700
WidgetSaisie.prototype.validerForm = function() {
3844 idir 701
	const observateur = ( $( '#form-observateur' ).valid() && $( '#courriel' ).valid() && $( '#courriel_confirmation' ).valid() ),
702
		obs           = $( '#form-observation' ).valid(),
703
		geoloc        = ( valOk( $( '#latitude' ).val() ) && valOk( $( '#longitude' ).val() ) ) ,
704
		// validation et panneau taxon/images
3851 idir 705
		certitudeTaxonImage  = this.validerCertitudeTaxonImage(
706
			valOk( $( '#taxon' ).val() ),
707
			valOk( $( '#miniatures .miniature' ) )
708
		);
3844 idir 709
	let chpsSupp = true;
3638 delphine 710
 
3844 idir 711
	if ( valOk( $( '#form-supp' ) ) ) {
3638 delphine 712
		chpsSupp = ( function () {
3844 idir 713
			let otherFlag = $( '#form-supp' ).valid();
714
 
715
			if( valOk( $( '.other', $( '#form-supp' ) ) ) ) {
3638 delphine 716
				$( '.other', $( '#form-supp' ) ).each( function() {
3844 idir 717
					const picked = ( $( this ).data( 'element' ) !== 'select' ) ? ':checked' : ':selected';
718
 
719
						if ( $( this ).is( picked ) && valOk( $( this ).val(), true, 'other' ) ) {
3638 delphine 720
							otherFlag = false;
721
						}
722
				});
723
			}
3844 idir 724
 
3638 delphine 725
			return otherFlag;
726
		})();
727
	}
728
	// panneau geoloc
729
	if ( geoloc ) {
730
		this.masquerPanneau( '#dialogue-geoloc-ko' );
731
		$( '#geoloc-datas' ).closest( '.control-group' ).removeClass( 'error' );
732
	} else{
733
		this.afficherPanneau( '#dialogue-geoloc-ko' );
734
		$( '#geoloc-datas' ).closest( '.control-group' ).addClass( 'error' );
735
	}
736
	// panneau observateur
737
	if ( observateur ) {
738
		this.masquerPanneau( '#dialogue-utilisateur-non-identifie' );
739
		$( '.nav.control-group' ).removeClass( 'error' );
740
	} else {
741
		this.afficherPanneau( '#dialogue-utilisateur-non-identifie' );
742
		$( '.nav.control-group' ).addClass( 'error' );
743
	}
3851 idir 744
	return ( observateur && obs && geoloc && certitudeTaxonImage && chpsSupp );
3638 delphine 745
};
746
 
747
// Referentiel ****************************************************************/
748
// N'est pas utilisé en cas de taxon-liste
749
WidgetSaisie.prototype.surChangementReferentiel = function() {
750
	this.nomSciReferentiel = $( '#referentiel' ).val();
751
	//réinitialise taxon.val
752
	$( '#taxon' ).val( '' );
753
	$( '#taxon' ).data( 'numNomSel', '' );
754
};
3844 idir 755
 
756
 
757
$( document ).ready( function() {
758
	const widget = new WidgetSaisie();
759
	widget.init();
760
	// Fonctions de Style et Affichage des éléments "spéciaux"
761
	utils.init();
762
});