Subversion Repositories eFlore/Applications.cel

Rev

Rev 3869 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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