Subversion Repositories eFlore/Applications.cel

Rev

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

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