Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 2701 Rev 2706
1
/**
1
/**
2
 * Constructeur WidgetSaisie par défaut
2
 * Constructeur WidgetSaisie par défaut
3
 */
3
 */
4
function WidgetSaisie() {
4
function WidgetSaisie() {
5
	this.obsNbre = 0;
5
	this.obsNbre = 0;
6
	this.nbObsEnCours = 1;
6
	this.nbObsEnCours = 1;
7
	this.totalObsATransmettre = 0;
7
	this.totalObsATransmettre = 0;
8
	this.nbObsTransmises = 0;
8
	this.nbObsTransmises = 0;
9
	this.map = null;
9
	this.map = null;
10
	this.marker = null;
10
	this.marker = null;
11
	this.latLng = null;
11
	this.latLng = null;
12
	this.geocoder = null;
12
	this.geocoder = null;
13
	this.debug = null;
13
	this.debug = null;
14
	this.html5 = null;
14
	this.html5 = null;
15
	this.tagProjet = null;
15
	this.tagProjet = null;
16
	this.tagImg = null;
16
	this.tagImg = null;
17
	this.tagObs = null;
17
	this.tagObs = null;
18
	this.separationTagImg = null;
18
	this.separationTagImg = null;
19
	this.separationTagObs = null;
19
	this.separationTagObs = null;
20
	this.obsId = null;
20
	this.obsId = null;
21
	this.serviceSaisieUrl = null;
21
	this.serviceSaisieUrl = null;
22
	this.serviceObsUrl = null;
22
	this.serviceObsUrl = null;
23
	this.nomSciReferentiel = null;
23
	this.nomSciReferentiel = null;
24
	this.especeImposee = null;
24
	this.especeImposee = null;
25
	this.infosEspeceImposee = null;
25
	this.infosEspeceImposee = null;
26
	this.autocompletionElementsNbre = null;
26
	this.autocompletionElementsNbre = null;
27
	this.referentielImpose = null;
27
	this.referentielImpose = null;
28
	this.serviceAutocompletionNomSciUrl = null;
28
	this.serviceAutocompletionNomSciUrl = null;
29
	this.serviceAutocompletionNomSciUrlTpl = null;
29
	this.serviceAutocompletionNomSciUrlTpl = null;
30
	this.obsMaxNbre = null;
30
	this.obsMaxNbre = null;
31
	this.dureeMessage = null;
31
	this.dureeMessage = null;
32
	this.serviceAnnuaireIdUrl = null;
32
	this.serviceAnnuaireIdUrl = null;
33
	this.serviceNomCommuneUrl = null;
33
	this.serviceNomCommuneUrl = null;
34
	this.serviceNomCommuneUrlAlt = null;
34
	this.serviceNomCommuneUrlAlt = null;
35
	this.googleMapMarqueurUrl = null;
35
	this.googleMapMarqueurUrl = null;
36
	this.chargementIconeUrl = null;
36
	this.chargementIconeUrl = null;
37
	this.chargementImageIconeUrl = null;
37
	this.chargementImageIconeUrl = null;
38
	this.calendrierIconeUrl = null;
38
	this.calendrierIconeUrl = null;
39
	this.pasDePhotoIconeUrl = null;
39
	this.pasDePhotoIconeUrl = null;
40
}
40
}
41
 
41
 
42
/**
42
/**
43
 * Initialisation du widget
43
 * Initialisation du widget
44
 */
44
 */
45
WidgetSaisie.prototype.init = function() {
45
WidgetSaisie.prototype.init = function() {
46
	this.initCarto();
46
	this.initCarto();
47
	this.initForm();
47
	this.initForm();
48
	this.initEvts();
48
	this.initEvts();
49
};
49
};
50
 
50
 
51
/**
51
/**
52
 * Initialise la cartographie
52
 * Initialise la cartographie
53
 */
53
 */
54
WidgetSaisie.prototype.initCarto = function() {
54
WidgetSaisie.prototype.initCarto = function() {
55
	this.initialiserGoogleMap();
55
	this.initialiserGoogleMap();
56
	this.initialiserAutocompleteCommune();
56
	this.initialiserAutocompleteCommune();
57
}
57
}
58
 
58
 
59
/**
59
/**
60
 * Initialise le formulaire, les validateurs, les listes de complétion...
60
 * Initialise le formulaire, les validateurs, les listes de complétion...
61
 */
61
 */
62
WidgetSaisie.prototype.initForm = function() {
62
WidgetSaisie.prototype.initForm = function() {
63
	if (this.obsId != '') {
63
	if (this.obsId != '') {
64
		this.chargerInfoObs();
64
		this.chargerInfoObs();
65
	}
65
	}
66
 
66
 
67
	this.configurerDatePicker();
67
	this.configurerDatePicker();
68
	this.ajouterAutocompletionNoms();
68
	this.ajouterAutocompletionNoms();
69
	this.configurerFormValidator();
69
	this.configurerFormValidator();
70
	this.definirReglesFormValidator();
70
	this.definirReglesFormValidator();
71
 
71
 
72
	if(this.especeImposee) {
72
	if(this.especeImposee) {
73
		$("#taxon").attr("disabled", "disabled");
73
		$("#taxon").attr("disabled", "disabled");
74
		$("#taxon-input-groupe").attr("title","");
74
		$("#taxon-input-groupe").attr("title","");
75
		var infosAssociee = {
75
		var infosAssociee = {
76
			label : this.infosEspeceImposee.nom_sci_complet,
76
			label : this.infosEspeceImposee.nom_sci_complet,
77
			value : this.infosEspeceImposee.nom_sci_complet,
77
			value : this.infosEspeceImposee.nom_sci_complet,
78
			nt : this.infosEspeceImposee.num_taxonomique,
78
			nt : this.infosEspeceImposee.num_taxonomique,
79
			nomSel : this.infosEspeceImposee.nom_sci,
79
			nomSel : this.infosEspeceImposee.nom_sci,
80
			nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
80
			nomSelComplet : this.infosEspeceImposee.nom_sci_complet,
81
			numNomSel : this.infosEspeceImposee.id,
81
			numNomSel : this.infosEspeceImposee.id,
82
			nomRet : this.infosEspeceImposee["nom_retenu.libelle"],
82
			nomRet : this.infosEspeceImposee["nom_retenu.libelle"],
83
			numNomRet : this.infosEspeceImposee["nom_retenu.id"],
83
			numNomRet : this.infosEspeceImposee["nom_retenu.id"],
84
			famille : this.infosEspeceImposee.famille,
84
			famille : this.infosEspeceImposee.famille,
85
			retenu : (this.infosEspeceImposee.retenu == 'false') ? false : true
85
			retenu : (this.infosEspeceImposee.retenu == 'false') ? false : true
86
		};
86
		};
87
		$("#taxon").data(infosAssociee);
87
		$("#taxon").data(infosAssociee);
88
	}
88
	}
89
}
89
}
90
 
90
 
91
/**
91
/**
92
 * Initialise les écouteurs d'événements
92
 * Initialise les écouteurs d'événements
93
 */
93
 */
94
WidgetSaisie.prototype.initEvts = function() {
94
WidgetSaisie.prototype.initEvts = function() {
95
	var lthis = this;
95
	var lthis = this;
96
	$('body').on('click', '.effacer-miniature', function() {
96
	$('body').on('click', '.effacer-miniature', function() {
97
		$(this).parent().remove();
97
		$(this).parent().remove();
98
	});
98
	});
99
	$("#fichier").bind('change', function (e) {
99
	$("#fichier").bind('change', function (e) {
100
		arreter(e);
100
		arreter(e);
101
		var options = {
101
		var options = {
102
			success: lthis.afficherMiniature.bind(lthis), // post-submit callback
102
			success: lthis.afficherMiniature.bind(lthis), // post-submit callback
103
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
103
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
104
			resetForm: true // reset the form after successful submit
104
			resetForm: true // reset the form after successful submit
105
		};
105
		};
106
		$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+this.chargementImageIconeUrl+'"/>');
106
		$("#miniature").append('<img id="miniature-chargement" class="miniature" alt="chargement" src="'+this.chargementImageIconeUrl+'"/>');
107
		$("#ajouter-obs").attr('disabled', 'disabled');
107
		$("#ajouter-obs").attr('disabled', 'disabled');
108
		if(lthis.verifierFormat($("#fichier").val())) {
108
		if(lthis.verifierFormat($("#fichier").val())) {
109
			$("#form-upload").ajaxSubmit(options);
109
			$("#form-upload").ajaxSubmit(options);
110
		} else {
110
		} else {
111
			$('#form-upload')[0].reset();
111
			$('#form-upload')[0].reset();
112
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$("#fichier").attr("accept"));
112
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+	$("#fichier").attr("accept"));
113
		}
113
		}
114
		return false;
114
		return false;
115
	});
115
	});
116
	// identité
116
	// identité
117
	$("#courriel").on('blur', this.requeterIdentite.bind(this));
117
	$("#courriel").on('blur', this.requeterIdentite.bind(this));
118
	$("#courriel").on('keypress', this.testerLancementRequeteIdentite.bind(this));
118
	$("#courriel").on('keypress', this.testerLancementRequeteIdentite.bind(this));
119
	$(".alert .close").on('click', this.fermerPanneauAlert);
119
	$(".alert .close").on('click', this.fermerPanneauAlert);
120
	$("[rel=tooltip]").tooltip('enable');
120
	$("[rel=tooltip]").tooltip('enable');
121
	$("#btn-aide").on('click', this.basculerAffichageAide);
121
	$("#btn-aide").on('click', this.basculerAffichageAide);
122
	$("#prenom").on("change", this.formaterPrenom.bind(this));
122
	$("#prenom").on("change", this.formaterPrenom.bind(this));
123
	$("#nom").on("change", this.formaterNom.bind(this));
123
	$("#nom").on("change", this.formaterNom.bind(this));
124
 
124
 
125
	$("#courriel_confirmation").on('paste', this.bloquerCopierCollerCourriel.bind(this));
125
	$("#courriel_confirmation").on('paste', this.bloquerCopierCollerCourriel.bind(this));
126
	$("a.afficher-coord").on('click', this.basculerAffichageCoord.bind(this));
126
	$("a.afficher-coord").on('click', this.basculerAffichageCoord.bind(this));
127
	$("#ajouter-obs").on('click', this.ajouterObs.bind(this));
127
	$("#ajouter-obs").on('click', this.ajouterObs.bind(this));
128
	$(".obs-nbre").on('changement', this.surChangementNbreObs.bind(this));
128
	$(".obs-nbre").on('changement', this.surChangementNbreObs.bind(this));
129
	$("body").on('click', ".supprimer-obs", function() {
129
	$("body").on('click', ".supprimer-obs", function() {
130
		var that = this,
130
		var that = this,
131
			suppObs = lthis.supprimerObs.bind(lthis);
131
			suppObs = lthis.supprimerObs.bind(lthis);
132
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
132
		// bricolage pour avoir les deux contextes en même temps (objet et elt. du DOM)
133
		suppObs(that);
133
		suppObs(that);
134
	});
134
	});
135
	$("#transmettre-obs").on('click', this.transmettreObs.bind(this));
135
	$("#transmettre-obs").on('click', this.transmettreObs.bind(this));
136
	$("#referentiel").on('change', this.surChangementReferentiel.bind(this));
136
	$("#referentiel").on('change', this.surChangementReferentiel.bind(this));
137
 
137
 
138
	$("body").on('click', ".defilement-miniatures-gauche", function(event) {
138
	$("body").on('click', ".defilement-miniatures-gauche", function(event) {
139
		event.preventDefault();
139
		event.preventDefault();
140
		lthis.defilerMiniatures($(this));
140
		lthis.defilerMiniatures($(this));
141
	});
141
	});
142
	$("body").on('click', ".defilement-miniatures-droite", function(event) {
142
	$("body").on('click', ".defilement-miniatures-droite", function(event) {
143
		event.preventDefault();
143
		event.preventDefault();
144
		lthis.defilerMiniatures($(this));
144
		lthis.defilerMiniatures($(this));
145
	});
145
	});
146
 
146
 
147
	// fermeture fenêtre
147
	// fermeture fenêtre
148
	if (this.debug == false) {
148
	if (this.debug == false) {
149
		$(window).on('beforeunload', function(event) {
149
		$(window).on('beforeunload', function(event) {
150
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
150
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
151
		});
151
		});
152
	}
152
	}
153
}
153
}
154
 
154
 
155
/**
155
/**
156
 * Retourne true si l'extension de l'image "nom" est .jpg ou .jpeg
156
 * Retourne true si l'extension de l'image "nom" est .jpg ou .jpeg
157
 */
157
 */
158
WidgetSaisie.prototype.verifierFormat = function(nom) {
158
WidgetSaisie.prototype.verifierFormat = function(nom) {
159
	var parts = nom.split('.');
159
	var parts = nom.split('.');
160
	extension = parts[parts.length - 1];
160
	extension = parts[parts.length - 1];
161
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
161
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
162
};
162
};
163
 
163
 
164
/**
164
/**
165
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
165
 * Affiche la miniature d'une image temporaire (formulaire) qu'on a ajoutée à l'obs
166
 */
166
 */
167
WidgetSaisie.prototype.afficherMiniature = function(reponse) {
167
WidgetSaisie.prototype.afficherMiniature = function(reponse) {
168
	if (this.debug) {
168
	if (this.debug) {
169
		var debogage = $("debogage", reponse).text();
169
		var debogage = $("debogage", reponse).text();
170
		//console.log("Débogage upload : "+debogage);
170
		//console.log("Débogage upload : "+debogage);
171
	}
171
	}
172
	var message = $("message", reponse).text();
172
	var message = $("message", reponse).text();
173
	if (message != '') {
173
	if (message != '') {
174
		$("#miniature-msg").append(message);
174
		$("#miniature-msg").append(message);
175
	} else {
175
	} else {
176
		$("#miniatures").append(this.creerWidgetMiniature(reponse));
176
		$("#miniatures").append(this.creerWidgetMiniature(reponse));
177
	}
177
	}
178
	$('#ajouter-obs').removeAttr('disabled');
178
	$('#ajouter-obs').removeAttr('disabled');
179
};
179
};
180
 
180
 
181
/**
181
/**
182
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
182
 * Crée la miniature d'une image temporaire (formulaire), avec le bouton pour l'effacer
183
 */
183
 */
184
WidgetSaisie.prototype.creerWidgetMiniature = function(reponse) {
184
WidgetSaisie.prototype.creerWidgetMiniature = function(reponse) {
185
	var miniatureUrl = $("miniature-url", reponse).text();
185
	var miniatureUrl = $("miniature-url", reponse).text();
186
	var imgNom = $("image-nom", reponse).text();
186
	var imgNom = $("image-nom", reponse).text();
187
	var html =
187
	var html =
188
		'<div class="miniature">'+
188
		'<div class="miniature">'+
189
			'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
189
			'<img class="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
190
			'<button class="effacer-miniature" type="button">Effacer</button>'+
190
			'<button class="effacer-miniature" type="button">Effacer</button>'+
191
		'</div>'
191
		'</div>'
192
	return html;
192
	return html;
193
};
193
};
194
 
194
 
195
/**
195
/**
196
 * Efface toutes les miniatures (formulaire)
196
 * Efface toutes les miniatures (formulaire)
197
 */
197
 */
198
WidgetSaisie.prototype.supprimerMiniatures = function() {
198
WidgetSaisie.prototype.supprimerMiniatures = function() {
199
	$("#miniatures").empty();
199
	$("#miniatures").empty();
200
	$("#miniature-msg").empty();
200
	$("#miniature-msg").empty();
201
};
201
};
202
 
202
 
203
/**
203
/**
204
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
204
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
205
 */
205
 */
206
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
206
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
207
	var geocoderOptions = {
207
	var geocoderOptions = {
208
	},
208
	},
209
	addressSuffix = '',
209
	addressSuffix = '',
210
	lthis = this;
210
	lthis = this;
211
 
211
 
212
	switch(this.nomSciReferentiel) {
212
	switch(this.nomSciReferentiel) {
213
		case 'isfan':
213
		case 'isfan':
214
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
214
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
215
			// Ça marche moyen...
215
			// Ça marche moyen...
216
			geocoderOptions.bounds = new google.maps.LatLngBounds(
216
			geocoderOptions.bounds = new google.maps.LatLngBounds(
217
				new google.maps.LatLng(20.756114, -22.023927),
217
				new google.maps.LatLng(20.756114, -22.023927),
218
				new google.maps.LatLng(38.065392, 33.78662)
218
				new google.maps.LatLng(38.065392, 33.78662)
219
			);
219
			);
220
			break;
220
			break;
221
		case 'apd':
221
		case 'apd':
222
			geocoderOptions.bounds = new google.maps.LatLngBounds(
222
			geocoderOptions.bounds = new google.maps.LatLngBounds(
223
					new google.maps.LatLng(-6.708254, -26.154786),
223
					new google.maps.LatLng(-6.708254, -26.154786),
224
					new google.maps.LatLng(27.488781, 30.490722)
224
					new google.maps.LatLng(27.488781, 30.490722)
225
				);
225
				);
226
			break;
226
			break;
227
		case 'bdtfx':
227
		case 'bdtfx':
228
		case 'bdtxa':
228
		case 'bdtxa':
229
			geocoderOptions.region = 'fr';
229
			geocoderOptions.region = 'fr';
230
			addressSuffix = ', France';
230
			addressSuffix = ', France';
231
	}
231
	}
232
 
232
 
233
	$("#carte-recherche").autocomplete({
233
	$("#carte-recherche").autocomplete({
234
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
234
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
235
		source: function(request, response) {
235
		source: function(request, response) {
236
			geocoderOptions.address = request.term + addressSuffix;
236
			geocoderOptions.address = request.term + addressSuffix;
237
			console.log('Geocoder options', geocoderOptions);
237
			console.log('Geocoder options', geocoderOptions);
238
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
238
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
239
				if (status == google.maps.GeocoderStatus.OK) {
239
				if (status == google.maps.GeocoderStatus.OK) {
240
					response($.map(results, function(item) {
240
					response($.map(results, function(item) {
241
						var retour = {
241
						var retour = {
242
							label: item.formatted_address,
242
							label: item.formatted_address,
243
							value: item.formatted_address,
243
							value: item.formatted_address,
244
							latitude: item.geometry.location.lat(),
244
							latitude: item.geometry.location.lat(),
245
							longitude: item.geometry.location.lng()
245
							longitude: item.geometry.location.lng()
246
						};
246
						};
247
						return retour;
247
						return retour;
248
					}));
248
					}));
249
				} else {
249
				} else {
250
					lthis.afficherErreurGoogleMap(status);
250
					lthis.afficherErreurGoogleMap(status);
251
				}
251
				}
252
			});
252
			});
253
		},
253
		},
254
		// Cette partie est executee a la selection d'une adresse
254
		// Cette partie est executee a la selection d'une adresse
255
		select: function(event, ui) {
255
		select: function(event, ui) {
256
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
256
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
257
			lthis.deplacerMarker(latLng);
257
			lthis.deplacerMarker(latLng);
258
		}
258
		}
259
	});
259
	});
260
 
260
 
261
	// Autocompletion du champ adresse
261
	// Autocompletion du champ adresse
262
	$("#carte-recherche").on('focus', function() {
262
	$("#carte-recherche").on('focus', function() {
263
		$(this).select();
263
		$(this).select();
264
	});
264
	});
265
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
265
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
266
		event.preventDefault();
266
		event.preventDefault();
267
	});
267
	});
268
	$("#carte-recherche").keypress(function(e) {
268
	$("#carte-recherche").keypress(function(e) {
269
		if (e.which == 13) {
269
		if (e.which == 13) {
270
			e.preventDefault();
270
			e.preventDefault();
271
		}
271
		}
272
	});
272
	});
273
};
273
};
274
 
274
 
275
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
275
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
276
	if (this.debug) {
276
	if (this.debug) {
277
		$('#dialogue-google-map .contenu').empty().append(
277
		$('#dialogue-google-map .contenu').empty().append(
278
			'<pre class="msg-erreur">'+
278
			'<pre class="msg-erreur">'+
279
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
279
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
280
			'</pre>');
280
			'</pre>');
281
		this.afficherPanneau('#dialogue-google-map');
281
		this.afficherPanneau('#dialogue-google-map');
282
	}
282
	}
283
};
283
};
284
 
284
 
285
WidgetSaisie.prototype.surDeplacementMarker = function() {
285
WidgetSaisie.prototype.surDeplacementMarker = function() {
286
	this.trouverCommune(this.marker.getPosition());
286
	this.trouverCommune(this.marker.getPosition());
287
	this.mettreAJourMarkerPosition(this.marker.getPosition());
287
	this.mettreAJourMarkerPosition(this.marker.getPosition());
288
};
288
};
289
 
289
 
290
WidgetSaisie.prototype.surClickDansCarte = function(event) {
290
WidgetSaisie.prototype.surClickDansCarte = function(event) {
291
	this.deplacerMarker(event.latLng);
291
	this.deplacerMarker(event.latLng);
292
};
292
};
293
 
293
 
294
/**
294
/**
295
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
295
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
296
 */
296
 */
297
WidgetSaisie.prototype.geolocaliser = function() {
297
WidgetSaisie.prototype.geolocaliser = function() {
298
	var latitude = $('#latitude').val();
298
	var latitude = $('#latitude').val();
299
	var longitude = $('#longitude').val();
299
	var longitude = $('#longitude').val();
300
	this.latLng = new google.maps.LatLng(latitude, longitude);
300
	this.latLng = new google.maps.LatLng(latitude, longitude);
301
	this.deplacerMarker(this.latLng);
301
	this.deplacerMarker(this.latLng);
302
};
302
};
303
 
303
 
304
WidgetSaisie.prototype.initialiserGoogleMap = function() {
304
WidgetSaisie.prototype.initialiserGoogleMap = function() {
305
	var latLng,
305
	var latLng,
306
		zoomDefaut;
306
		zoomDefaut;
307
	// Carte @TODO mettre ça dans la config
307
	// Carte @TODO mettre ça dans la config
308
	if(this.nomSciReferentiel == 'bdtre') {
308
	if(this.nomSciReferentiel == 'bdtre') {
309
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
309
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
310
		zoomDefaut = 7;
310
		zoomDefaut = 7;
311
	} else if(this.nomSciReferentiel == 'lbf') {
311
	} else if(this.nomSciReferentiel == 'lbf') {
312
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
312
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
313
		zoomDefaut = 7;
313
		zoomDefaut = 7;
314
	} else if(this.nomSciReferentiel == 'bdtxa') {
314
	} else if(this.nomSciReferentiel == 'bdtxa') {
315
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
315
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
316
		zoomDefaut = 8;
316
		zoomDefaut = 8;
317
	} else if(this.nomSciReferentiel == 'isfan') {
317
	} else if(this.nomSciReferentiel == 'isfan') {
318
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
318
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
319
		zoomDefaut = 4;
319
		zoomDefaut = 4;
320
	} else if(this.nomSciReferentiel == 'apd') {
320
	} else if(this.nomSciReferentiel == 'apd') {
321
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
321
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
322
		zoomDefaut = 4;
322
		zoomDefaut = 4;
323
	} else {
323
	} else {
324
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
324
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
325
		zoomDefaut = 5;
325
		zoomDefaut = 5;
326
	}
326
	}
327
 
327
 
328
	var options = {
328
	var options = {
329
		zoom: zoomDefaut,
329
		zoom: zoomDefaut,
330
		center: latLng,
330
		center: latLng,
331
		mapTypeId: google.maps.MapTypeId.HYBRID,
331
		mapTypeId: google.maps.MapTypeId.HYBRID,
332
		mapTypeControlOptions: {
332
		mapTypeControlOptions: {
333
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
333
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
334
	};
334
	};
335
 
335
 
336
	// Ajout de la couche OSM à la carte
336
	// Ajout de la couche OSM à la carte
337
	osmMapType = new google.maps.ImageMapType({
337
	osmMapType = new google.maps.ImageMapType({
338
		getTileUrl: function(coord, zoom) {
338
		getTileUrl: function(coord, zoom) {
339
			return "http://tile.openstreetmap.org/" +
339
			return "http://tile.openstreetmap.org/" +
340
			zoom + "/" + coord.x + "/" + coord.y + ".png";
340
			zoom + "/" + coord.x + "/" + coord.y + ".png";
341
		},
341
		},
342
		tileSize: new google.maps.Size(256, 256),
342
		tileSize: new google.maps.Size(256, 256),
343
		isPng: true,
343
		isPng: true,
344
		alt: 'OpenStreetMap',
344
		alt: 'OpenStreetMap',
345
		name: 'OSM',
345
		name: 'OSM',
346
		maxZoom: 19
346
		maxZoom: 19
347
	});
347
	});
348
 
348
 
349
	// Création de la carte Google
349
	// Création de la carte Google
350
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
350
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
351
	this.map.mapTypes.set('OSM', osmMapType);
351
	this.map.mapTypes.set('OSM', osmMapType);
352
 
352
 
353
	// Création du Geocoder
353
	// Création du Geocoder
354
	this.geocoder = new google.maps.Geocoder();
354
	this.geocoder = new google.maps.Geocoder();
355
 
355
 
356
	// Marqueur google draggable
356
	// Marqueur google draggable
357
	this.marker = new google.maps.Marker({
357
	this.marker = new google.maps.Marker({
358
		map: this.map,
358
		map: this.map,
359
		draggable: true,
359
		draggable: true,
360
		title: 'Ma station',
360
		title: 'Ma station',
361
		icon: this.googleMapMarqueurUrl,
361
		icon: this.googleMapMarqueurUrl,
362
		position: latLng
362
		position: latLng
363
	});
363
	});
364
 
364
 
365
	this.initialiserMarker(latLng);
365
	this.initialiserMarker(latLng);
366
 
366
 
367
	// Tentative de geocalisation
367
	// Tentative de geocalisation
368
	if (navigator.geolocation) {
368
	if (navigator.geolocation) {
369
		navigator.geolocation.getCurrentPosition(function(position) {
369
		navigator.geolocation.getCurrentPosition(function(position) {
370
			var latitude = position.coords.latitude;
370
			var latitude = position.coords.latitude;
371
			var longitude = position.coords.longitude;
371
			var longitude = position.coords.longitude;
372
			this.latLng = new google.maps.LatLng(latitude, longitude);
372
			this.latLng = new google.maps.LatLng(latitude, longitude);
373
			this.deplacerMarker(this.latLng);
373
			this.deplacerMarker(this.latLng);
374
		});
374
		});
375
	}
375
	}
376
 
376
 
377
	// intéraction carte
377
	// intéraction carte
378
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
378
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
379
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
379
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
380
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
380
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
381
};
381
};
382
 
382
 
383
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
383
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
384
	if (this.marker != undefined) {
384
	if (this.marker != undefined) {
385
		this.marker.setPosition(latLng);
385
		this.marker.setPosition(latLng);
386
		this.map.setCenter(latLng);
386
		this.map.setCenter(latLng);
387
	}
387
	}
388
};
388
};
389
 
389
 
390
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
390
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
391
	if (this.marker != undefined) {
391
	if (this.marker != undefined) {
392
		this.marker.setPosition(latLng);
392
		this.marker.setPosition(latLng);
393
		this.map.setCenter(latLng);
393
		this.map.setCenter(latLng);
394
		this.mettreAJourMarkerPosition(latLng);
394
		this.mettreAJourMarkerPosition(latLng);
395
		this.trouverCommune(latLng);
395
		this.trouverCommune(latLng);
396
	}
396
	}
397
};
397
};
398
 
398
 
399
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
399
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
400
	var lat = latLng.lat().toFixed(5);
400
	var lat = latLng.lat().toFixed(5);
401
	var lng = latLng.lng().toFixed(5);
401
	var lng = latLng.lng().toFixed(5);
402
	this.remplirChampLatitude(lat);
402
	this.remplirChampLatitude(lat);
403
	this.remplirChampLongitude(lng);
403
	this.remplirChampLongitude(lng);
404
};
404
};
405
 
405
 
406
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
406
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
407
	var lat = Math.round(latDecimale * 100000) / 100000;
407
	var lat = Math.round(latDecimale * 100000) / 100000;
408
	$('#latitude').val(lat);
408
	$('#latitude').val(lat);
409
};
409
};
410
 
410
 
411
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
411
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
412
	var lng = Math.round(lngDecimale * 100000) / 100000;
412
	var lng = Math.round(lngDecimale * 100000) / 100000;
413
	$('#longitude').val(lng);
413
	$('#longitude').val(lng);
414
};
414
};
415
 
415
 
416
WidgetSaisie.prototype.trouverCommune = function(pos) {
416
WidgetSaisie.prototype.trouverCommune = function(pos) {
417
	var lthis = this;
417
	var lthis = this;
418
	$(function() {
418
	$(function() {
419
 
419
 
420
		var url_service = lthis.serviceNomCommuneUrl;
420
		var url_service = lthis.serviceNomCommuneUrl;
421
 
421
 
422
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
422
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
423
		$.ajax({
423
		$.ajax({
424
			url : urlNomCommuneFormatee,
424
			url : urlNomCommuneFormatee,
425
			type : "GET",
425
			type : "GET",
426
			dataType : "jsonp",
426
			dataType : "jsonp",
427
			beforeSend : function() {
427
			beforeSend : function() {
428
				$(".commune-info").empty();
428
				$(".commune-info").empty();
429
				$("#dialogue-erreur .alert-txt").empty();
429
				$("#dialogue-erreur .alert-txt").empty();
430
			},
430
			},
431
			success : function(data, textStatus, jqXHR) {
431
			success : function(data, textStatus, jqXHR) {
432
				$(".commune-info").empty();
432
				$(".commune-info").empty();
433
				$("#commune-nom").append(data.nom);
433
				$("#commune-nom").append(data.nom);
434
				$("#commune-code-insee").append(data.codeINSEE);
434
				$("#commune-code-insee").append(data.codeINSEE);
435
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
435
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
436
			},
436
			},
437
			statusCode : {
437
			statusCode : {
438
			    500 : function(jqXHR, textStatus, errorThrown) {
438
			    500 : function(jqXHR, textStatus, errorThrown) {
439
					if (this.debug) {
439
					if (this.debug) {
440
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
440
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
441
						reponse = jQuery.parseJSON(jqXHR.responseText);
441
						reponse = jQuery.parseJSON(jqXHR.responseText);
442
						var erreurMsg = "";
442
						var erreurMsg = "";
443
						if (reponse != null) {
443
						if (reponse != null) {
444
							$.each(reponse, function (cle, valeur) {
444
							$.each(reponse, function (cle, valeur) {
445
								erreurMsg += valeur + "<br />";
445
								erreurMsg += valeur + "<br />";
446
							});
446
							});
447
						}
447
						}
448
 
448
 
449
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
449
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
450
					}
450
					}
451
			    }
451
			    }
452
			},
452
			},
453
			error : function(jqXHR, textStatus, errorThrown) {
453
			error : function(jqXHR, textStatus, errorThrown) {
454
				if (this.debug) {
454
				if (this.debug) {
455
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
455
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
456
					reponse = jQuery.parseJSON(jqXHR.responseText);
456
					reponse = jQuery.parseJSON(jqXHR.responseText);
457
					var erreurMsg = "";
457
					var erreurMsg = "";
458
					if (reponse != null) {
458
					if (reponse != null) {
459
						$.each(reponse, function (cle, valeur) {
459
						$.each(reponse, function (cle, valeur) {
460
							erreurMsg += valeur + "<br />";
460
							erreurMsg += valeur + "<br />";
461
						});
461
						});
462
					}
462
					}
463
 
463
 
464
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
464
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
465
				}
465
				}
466
			},
466
			},
467
			complete : function(jqXHR, textStatus) {
467
			complete : function(jqXHR, textStatus) {
468
				var debugMsg = extraireEnteteDebug(jqXHR);
468
				var debugMsg = extraireEnteteDebug(jqXHR);
469
				if (debugMsg != '') {
469
				if (debugMsg != '') {
470
					if (this.debug) {
470
					if (this.debug) {
471
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
471
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
472
					}
472
					}
473
				}
473
				}
474
				if ($("#dialogue-erreur .msg").length > 0) {
474
				if ($("#dialogue-erreur .msg").length > 0) {
475
					$("#dialogue-erreur").show();
475
					$("#dialogue-erreur").show();
476
				}
476
				}
477
			}
477
			}
478
		});
478
		});
479
	});
479
	});
480
};
480
};
481
 
481
 
482
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
482
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
483
	if (event.which == 13) {
483
	if (event.which == 13) {
484
		this.requeterIdentite();
484
		this.requeterIdentite();
485
		this.event.preventDefault();
485
		this.event.preventDefault();
486
		this.event.stopPropagation();
486
		this.event.stopPropagation();
487
	}
487
	}
488
};
488
};
489
 
489
 
490
WidgetSaisie.prototype.requeterIdentite = function() {
490
WidgetSaisie.prototype.requeterIdentite = function() {
491
	var lthis = this;
491
	var lthis = this;
492
	var courriel = $("#courriel").val();
492
	var courriel = $("#courriel").val();
493
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
493
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
494
	$.ajax({
494
	$.ajax({
495
		url : urlAnnuaire,
495
		url : urlAnnuaire,
496
		type : "GET",
496
		type : "GET",
497
		success : function(data, textStatus, jqXHR) {
497
		success : function(data, textStatus, jqXHR) {
498
			//console.log('SUCCESS:'+textStatus);
498
			//console.log('SUCCESS:'+textStatus);
499
			if (data != undefined && data[courriel] != undefined) {
499
			if (data != undefined && data[courriel] != undefined) {
500
				var infos = data[courriel];
500
				var infos = data[courriel];
501
				$("#id_utilisateur").val(infos.id);
501
				$("#id_utilisateur").val(infos.id);
502
				$("#prenom").val(infos.prenom);
502
				$("#prenom").val(infos.prenom);
503
				$("#nom").val(infos.nom);
503
				$("#nom").val(infos.nom);
504
				$("#courriel_confirmation").val(courriel);
504
				$("#courriel_confirmation").val(courriel);
505
				$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
505
				$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
506
				$("#date").focus();
506
				$("#date").focus();
507
				lthis.masquerPanneau("#dialogue-courriel-introuvable");
507
				lthis.masquerPanneau("#dialogue-courriel-introuvable");
508
			} else {
508
			} else {
509
				lthis.surErreurCompletionCourriel();
509
				lthis.surErreurCompletionCourriel();
510
			}
510
			}
511
		},
511
		},
512
		error : function(jqXHR, textStatus, errorThrown) {
512
		error : function(jqXHR, textStatus, errorThrown) {
513
			//console.log('ERREUR :'+textStatus);
513
			//console.log('ERREUR :'+textStatus);
514
			lthis.surErreurCompletionCourriel();
514
			lthis.surErreurCompletionCourriel();
515
		},
515
		},
516
		complete : function(jqXHR, textStatus) {
516
		complete : function(jqXHR, textStatus) {
517
			//console.log('COMPLETE :'+textStatus);
517
			//console.log('COMPLETE :'+textStatus);
518
			// @TODO harmoniser class="hidden" VS style="display:none;"
518
			// @TODO harmoniser class="hidden" VS style="display:none;"
519
			$("#zone-prenom-nom").removeClass("hidden").show();
519
			$("#zone-prenom-nom").removeClass("hidden").show();
520
			$("#zone-courriel-confirmation").removeClass("hidden").show();
520
			$("#zone-courriel-confirmation").removeClass("hidden").show();
521
			
521
			
522
		}
522
		}
523
	});
523
	});
524
};
524
};
525
 
525
 
526
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
526
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
527
	$("#prenom, #nom, #courriel_confirmation").val('');
527
	$("#prenom, #nom, #courriel_confirmation").val('');
528
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
528
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
529
	this.afficherPanneau("#dialogue-courriel-introuvable");
529
	this.afficherPanneau("#dialogue-courriel-introuvable");
530
};
530
};
531
//+---------------------------------------------------------------------------------------------------------+
531
//+---------------------------------------------------------------------------------------------------------+
532
//FORMULAIRE
532
//FORMULAIRE
533
 
533
 
534
WidgetSaisie.prototype.chargerInfoObs = function() {
534
WidgetSaisie.prototype.chargerInfoObs = function() {
535
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
535
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
536
	$.ajax({
536
	$.ajax({
537
		url: urlObs,
537
		url: urlObs,
538
		type: 'GET',
538
		type: 'GET',
539
		success: function(data, textStatus, jqXHR) {
539
		success: function(data, textStatus, jqXHR) {
540
			if (data != undefined && data != "") {
540
			if (data != undefined && data != "") {
541
				this.prechargerForm(data);
541
				this.prechargerForm(data);
542
			}
542
			}
543
			// TODO: voir s'il est pertinent d'indiquer quelque chose en cas d'erreur ou d'obs
543
			// TODO: voir s'il est pertinent d'indiquer quelque chose en cas d'erreur ou d'obs
544
			// inexistante
544
			// inexistante
545
		},
545
		},
546
		error: function(jqXHR, textStatus, errorThrown) {
546
		error: function(jqXHR, textStatus, errorThrown) {
547
			// TODO: cf TODO ci-dessus
547
			// TODO: cf TODO ci-dessus
548
		}
548
		}
549
	});
549
	});
550
};
550
};
551
 
551
 
552
WidgetSaisie.prototype.prechargerForm = function(data) {
552
WidgetSaisie.prototype.prechargerForm = function(data) {
553
 
553
 
554
	$("#milieu").val(data.milieu);
554
	$("#milieu").val(data.milieu);
555
 
555
 
556
	$("#carte-recherche").val(data.zoneGeo);
556
	$("#carte-recherche").val(data.zoneGeo);
557
	$("#commune-nom").text(data.zoneGeo);
557
	$("#commune-nom").text(data.zoneGeo);
558
 
558
 
559
	if(data.hasOwnProperty("codeZoneGeo")) {
559
	if(data.hasOwnProperty("codeZoneGeo")) {
560
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
560
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
561
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
561
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
562
	}
562
	}
563
 
563
 
564
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
564
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
565
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
565
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
566
		this.mettreAJourMarkerPosition(latLng);
566
		this.mettreAJourMarkerPosition(latLng);
567
		this.marker.setPosition(latLng);
567
		this.marker.setPosition(latLng);
568
		this.map.setCenter(latLng);
568
		this.map.setCenter(latLng);
569
		this.map.setZoom(16);
569
		this.map.setZoom(16);
570
	}
570
	}
571
};
571
};
572
 
572
 
573
WidgetSaisie.prototype.configurerFormValidator = function() {
573
WidgetSaisie.prototype.configurerFormValidator = function() {
574
	$.validator.addMethod(
574
	$.validator.addMethod(
575
		"dateCel",
575
		"dateCel",
576
		function (value, element) {
576
		function (value, element) {
577
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
577
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
578
		},
578
		},
579
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
579
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
580
	$.extend($.validator.defaults, {
580
	$.extend($.validator.defaults, {
581
		errorClass: "control-group error",
581
		errorClass: "control-group error",
582
		validClass: "control-group success",
582
		validClass: "control-group success",
583
		errorElement: "span",
583
		errorElement: "span",
584
		highlight: function(element, errorClass, validClass) {
584
		highlight: function(element, errorClass, validClass) {
585
			if (element.type === 'radio') {
585
			if (element.type === 'radio') {
586
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
586
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
587
			} else {
587
			} else {
588
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
588
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
589
			}
589
			}
590
		},
590
		},
591
		unhighlight: function(element, errorClass, validClass) {
591
		unhighlight: function(element, errorClass, validClass) {
592
			if (element.type === 'radio') {
592
			if (element.type === 'radio') {
593
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
593
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
594
			} else {
594
			} else {
595
				if ($(element).attr('id') == 'taxon') {
595
				if ($(element).attr('id') == 'taxon') {
596
					if ($("#taxon").val() != '') {
596
					if ($("#taxon").val() != '') {
597
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
597
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
598
						if ($("#taxon").data("value") != $("#taxon").val()) {
598
						if ($("#taxon").data("value") != $("#taxon").val()) {
599
							$("#taxon").data("numNomSel","");
599
							$("#taxon").data("numNomSel","");
600
							$("#taxon").data("nomRet","");
600
							$("#taxon").data("nomRet","");
601
							$("#taxon").data("numNomRet","");
601
							$("#taxon").data("numNomRet","");
602
							$("#taxon").data("nt","");
602
							$("#taxon").data("nt","");
603
							$("#taxon").data("famille","");
603
							$("#taxon").data("famille","");
604
						}
604
						}
605
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
605
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
606
						$(element).next(" span.help-inline").remove();
606
						$(element).next(" span.help-inline").remove();
607
					}
607
					}
608
				} else {
608
				} else {
609
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
609
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
610
					$(element).next(" span.help-inline").remove();
610
					$(element).next(" span.help-inline").remove();
611
				}
611
				}
612
			}
612
			}
613
		}
613
		}
614
	});
614
	});
615
};
615
};
616
 
616
 
617
WidgetSaisie.prototype.definirReglesFormValidator = function() {
617
WidgetSaisie.prototype.definirReglesFormValidator = function() {
618
	$("#form-observateur").validate({
618
	$("#form-observateur").validate({
619
		rules: {
619
		rules: {
620
			courriel : {
620
			courriel : {
621
				required : true,
621
				required : true,
622
				email : true},
622
				email : true},
623
			courriel_confirmation : {
623
			courriel_confirmation : {
624
				required : true,
624
				required : true,
625
				equalTo: "#courriel"}
625
				equalTo: "#courriel"}
626
		}
626
		}
627
	});
627
	});
628
	$("#form-station").validate({
628
	$("#form-station").validate({
629
		rules: {
629
		rules: {
630
			latitude : {
630
			latitude : {
631
				range: [-90, 90]},
631
				range: [-90, 90]},
632
			longitude : {
632
			longitude : {
633
				range: [-180, 180]}
633
				range: [-180, 180]}
634
		}
634
		}
635
	});
635
	});
636
	$("#form-obs").validate({
636
	$("#form-obs").validate({
637
		rules: {
637
		rules: {
638
			date : "dateCel",
638
			date : "dateCel",
639
			taxon : "required"
639
			taxon : "required"
640
		}
640
		}
641
	});
641
	});
642
};
642
};
643
 
643
 
644
WidgetSaisie.prototype.configurerDatePicker = function() {
644
WidgetSaisie.prototype.configurerDatePicker = function() {
645
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
645
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
646
	$("#date").datepicker({
646
	$("#date").datepicker({
647
		dateFormat: "dd/mm/yy",
647
		dateFormat: "dd/mm/yy",
648
		maxDate: new Date,
648
		maxDate: new Date,
649
		showOn: "button",
649
		showOn: "button",
650
		buttonImageOnly: true,
650
		buttonImageOnly: true,
651
		buttonImage: this.calendrierIconeUrl,
651
		buttonImage: this.calendrierIconeUrl,
652
		buttonText: "Afficher le calendrier pour saisir la date.",
652
		buttonText: "Afficher le calendrier pour saisir la date.",
653
		showButtonPanel: true
653
		showButtonPanel: true
654
	});
654
	});
655
	$("img.ui-datepicker-trigger").appendTo("#date-icone");
655
	$("img.ui-datepicker-trigger").appendTo("#date-icone");
656
};
656
};
657
 
657
 
658
WidgetSaisie.prototype.fermerPanneauAlert = function() {
658
WidgetSaisie.prototype.fermerPanneauAlert = function() {
659
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
659
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
660
};
660
};
661
 
661
 
662
WidgetSaisie.prototype.formaterNom = function() {
662
WidgetSaisie.prototype.formaterNom = function() {
663
	$(this).val($(this).val().toUpperCase());
663
	$(this).val($(this).val().toUpperCase());
664
};
664
};
665
 
665
 
666
WidgetSaisie.prototype.formaterPrenom = function() {
666
WidgetSaisie.prototype.formaterPrenom = function() {
667
	var prenom = new Array();
667
	var prenom = new Array();
668
	var mots = $(this).val().split(' ');
668
	var mots = $(this).val().split(' ');
669
	for (var i = 0; i < mots.length; i++) {
669
	for (var i = 0; i < mots.length; i++) {
670
		var mot = mots[i];
670
		var mot = mots[i];
671
		if (mot.indexOf('-') >= 0) {
671
		if (mot.indexOf('-') >= 0) {
672
			var prenomCompose = new Array();
672
			var prenomCompose = new Array();
673
			var motsComposes = mot.split('-');
673
			var motsComposes = mot.split('-');
674
		    for (var j = 0; j < motsComposes.length; j++) {
674
		    for (var j = 0; j < motsComposes.length; j++) {
675
		    	var motSimple = motsComposes[j];
675
		    	var motSimple = motsComposes[j];
676
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
676
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
677
		    	prenomCompose.push(motMajuscule);
677
		    	prenomCompose.push(motMajuscule);
678
		    }
678
		    }
679
		    prenom.push(prenomCompose.join('-'));
679
		    prenom.push(prenomCompose.join('-'));
680
		} else {
680
		} else {
681
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
681
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
682
			prenom.push(motMajuscule);
682
			prenom.push(motMajuscule);
683
		}
683
		}
684
	}
684
	}
685
	$(this).val(prenom.join(' '));
685
	$(this).val(prenom.join(' '));
686
};
686
};
687
 
687
 
688
WidgetSaisie.prototype.basculerAffichageAide = function()  {
688
WidgetSaisie.prototype.basculerAffichageAide = function()  {
689
	if ($(this).hasClass('btn-warning')) {
689
	if ($(this).hasClass('btn-warning')) {
690
		$("[rel=tooltip]").tooltip('enable');
690
		$("[rel=tooltip]").tooltip('enable');
691
		$(this).removeClass('btn-warning').addClass('btn-success');
691
		$(this).removeClass('btn-warning').addClass('btn-success');
692
		$('#btn-aide-txt', this).text("Désactiver l'aide");
692
		$('#btn-aide-txt', this).text("Désactiver l'aide");
693
	} else {
693
	} else {
694
		$("[rel=tooltip]").tooltip('disable');
694
		$("[rel=tooltip]").tooltip('disable');
695
		$(this).removeClass('btn-success').addClass('btn-warning');
695
		$(this).removeClass('btn-success').addClass('btn-warning');
696
		$('#btn-aide-txt', this).text("Activer l'aide");
696
		$('#btn-aide-txt', this).text("Activer l'aide");
697
	}
697
	}
698
};
698
};
699
 
699
 
700
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
700
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
701
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
701
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
702
	return false;
702
	return false;
703
};
703
};
704
 
704
 
705
WidgetSaisie.prototype.basculerAffichageCoord = function() {
705
WidgetSaisie.prototype.basculerAffichageCoord = function() {
706
	$("a.afficher-coord").toggle();
706
	$("a.afficher-coord").toggle();
707
	$("#coordonnees-geo").toggle('slow');
707
	$("#coordonnees-geo").toggle('slow');
708
	//valeur false pour que le lien ne soit pas suivi
708
	//valeur false pour que le lien ne soit pas suivi
709
	return false;
709
	return false;
710
};
710
};
711
 
711
 
712
/**
712
/**
713
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
713
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
714
 */
714
 */
715
WidgetSaisie.prototype.ajouterObs = function() {
715
WidgetSaisie.prototype.ajouterObs = function() {
716
	if (this.validerFormulaire() == true) {
716
	if (this.validerFormulaire() == true) {
717
		this.obsNbre = this.obsNbre + 1;
717
		this.obsNbre = this.obsNbre + 1;
718
		$(".obs-nbre").text(this.obsNbre);
718
		$(".obs-nbre").text(this.obsNbre);
719
		$(".obs-nbre").triggerHandler('changement');
719
		$(".obs-nbre").triggerHandler('changement');
720
		this.afficherObs();
720
		this.afficherObs();
721
		this.stockerObsData();
721
		this.stockerObsData();
722
		this.supprimerMiniatures();
722
		this.supprimerMiniatures();
723
		if(! this.especeImposee) {
723
		if(! this.especeImposee) {
724
			$("#taxon").val("");
724
			$("#taxon").val("");
725
			$("#taxon").data("numNomSel",undefined);
725
			$("#taxon").data("numNomSel",undefined);
726
		}
726
		}
727
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
727
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
728
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
728
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
729
	} else {
729
	} else {
730
		this.afficherPanneau('#dialogue-form-invalide');
730
		this.afficherPanneau('#dialogue-form-invalide');
731
	}
731
	}
732
};
732
};
733
 
733
 
734
/**
734
/**
735
 * Affiche une observation dans la liste des observations à transmettre
735
 * Affiche une observation dans la liste des observations à transmettre
736
 */
736
 */
737
WidgetSaisie.prototype.afficherObs = function() {
737
WidgetSaisie.prototype.afficherObs = function() {
738
	$("#liste-obs").prepend(
738
	$("#liste-obs").prepend(
739
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
739
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
740
			'<div class="span12">'+
740
			'<div class="span12">'+
741
				'<div class="well">'+
741
				'<div class="well">'+
742
					'<div class="obs-action pull-right" rel="tooltip" data-placement="bottom" '+
742
					'<div class="obs-action pull-right" rel="tooltip" data-placement="bottom" '+
743
						'title="Supprimer cette observation de la liste à transmettre">'+
743
						'title="Supprimer cette observation de la liste à transmettre">'+
744
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
744
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
745
							'<i class="icon-trash icon-white"></i>'+
745
							'<i class="icon-trash icon-white"></i>'+
746
						'</button>'+
746
						'</button>'+
747
					'</div> '+
747
					'</div> '+
748
					'<div class="row-fluid">'+
748
					'<div class="row-fluid">'+
749
						'<div class="thumbnail span2">'+
749
						'<div class="thumbnail span2">'+
750
						this.ajouterImgMiniatureAuTransfert()+
750
						this.ajouterImgMiniatureAuTransfert()+
751
						'</div>'+
751
						'</div>'+
752
						'<div class="span9">'+
752
						'<div class="span9">'+
753
							'<ul class="unstyled">'+
753
							'<ul class="unstyled">'+
754
								'<li>'+
754
								'<li>'+
755
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
755
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
756
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
756
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
757
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
757
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
758
									' observé à '+
758
									' observé à '+
759
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
759
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
760
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
760
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
761
									' le '+
761
									' le '+
762
									'<span class="date">'+$("#date").val()+'</span>'+
762
									'<span class="date">'+$("#date").val()+'</span>'+
763
								'</li>'+
763
								'</li>'+
764
								'<li>'+
764
								'<li>'+
765
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
765
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
766
									'<span>Station :</span> '+$('#station').val()+' '+
766
									'<span>Station :</span> '+$('#station').val()+' '+
767
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
767
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
768
								'</li>'+
768
								'</li>'+
769
								'<li>'+
769
								'<li>'+
770
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
770
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
771
								'</li>'+
771
								'</li>'+
772
							'</ul>'+
772
							'</ul>'+
773
						'</div>'+
773
						'</div>'+
774
					'</div>'+
774
					'</div>'+
775
				'</div>'+
775
				'</div>'+
776
			'</div>'+
776
			'</div>'+
777
		'</div>');
777
		'</div>');
778
};
778
};
779
 
779
 
780
WidgetSaisie.prototype.stockerObsData = function() {
780
WidgetSaisie.prototype.stockerObsData = function() {
781
	var lthis = this;
781
	var lthis = this;
782
	$("#liste-obs").data('obsId'+this.obsNbre, {
782
	$("#liste-obs").data('obsId'+this.obsNbre, {
783
		'date' : $("#date").val(),
783
		'date' : $("#date").val(),
784
		'notes' : $("#notes").val(),
784
		'notes' : $("#notes").val(),
785
 
785
 
786
		'nom_sel' : $("#taxon").val(),
786
		'nom_sel' : $("#taxon").val(),
787
		'num_nom_sel' : $("#taxon").data("numNomSel"),
787
		'num_nom_sel' : $("#taxon").data("numNomSel"),
788
		'nom_ret' : $("#taxon").data("nomRet"),
788
		'nom_ret' : $("#taxon").data("nomRet"),
789
		'num_nom_ret' : $("#taxon").data("numNomRet"),
789
		'num_nom_ret' : $("#taxon").data("numNomRet"),
790
		'num_taxon' : $("#taxon").data("nt"),
790
		'num_taxon' : $("#taxon").data("nt"),
791
		'famille' : $("#taxon").data("famille"),
791
		'famille' : $("#taxon").data("famille"),
792
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
792
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
793
 
793
 
794
		'latitude' : $("#latitude").val(),
794
		'latitude' : $("#latitude").val(),
795
		'longitude' : $("#longitude").val(),
795
		'longitude' : $("#longitude").val(),
796
		'commune_nom' : $("#commune-nom").text(),
796
		'commune_nom' : $("#commune-nom").text(),
797
		'commune_code_insee' : $("#commune-code-insee").text(),
797
		'commune_code_insee' : $("#commune-code-insee").text(),
798
		'lieudit' : $("#lieudit").val(),
798
		'lieudit' : $("#lieudit").val(),
799
		'station' : $("#station").val(),
799
		'station' : $("#station").val(),
800
		'milieu' : $("#milieu").val(),
800
		'milieu' : $("#milieu").val(),
801
 
801
 
802
		//Ajout des champs images
802
		//Ajout des champs images
803
		'image_nom' : lthis.getNomsImgsOriginales(),
803
		'image_nom' : lthis.getNomsImgsOriginales(),
804
		'image_b64' : lthis.getB64ImgsOriginales()
804
		'image_b64' : lthis.getB64ImgsOriginales()
805
	});
805
	});
806
};
806
};
807
 
807
 
808
WidgetSaisie.prototype.surChangementReferentiel = function() {
808
WidgetSaisie.prototype.surChangementReferentiel = function() {
809
	this.nomSciReferentiel = $('#referentiel').val();
809
	this.nomSciReferentiel = $('#referentiel').val();
810
	$('#taxon').val('');
810
	$('#taxon').val('');
811
	this.initialiserAutocompleteCommune();
811
	this.initialiserAutocompleteCommune();
812
	this.initialiserGoogleMap();
812
	this.initialiserGoogleMap();
813
};
813
};
814
 
814
 
815
WidgetSaisie.prototype.surChangementNbreObs = function() {
815
WidgetSaisie.prototype.surChangementNbreObs = function() {
816
	if (this.obsNbre == 0) {
816
	if (this.obsNbre == 0) {
817
		$("#transmettre-obs").attr('disabled', 'disabled');
817
		$("#transmettre-obs").attr('disabled', 'disabled');
818
		$("#ajouter-obs").removeAttr('disabled');
818
		$("#ajouter-obs").removeAttr('disabled');
819
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
819
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
820
		$("#transmettre-obs").removeAttr('disabled');
820
		$("#transmettre-obs").removeAttr('disabled');
821
		$("#ajouter-obs").removeAttr('disabled');
821
		$("#ajouter-obs").removeAttr('disabled');
822
	} else if (this.obsNbre >= this.obsMaxNbre) {
822
	} else if (this.obsNbre >= this.obsMaxNbre) {
823
		$("#ajouter-obs").attr('disabled', 'disabled');
823
		$("#ajouter-obs").attr('disabled', 'disabled');
824
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
824
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
825
	}
825
	}
826
};
826
};
827
 
827
 
828
WidgetSaisie.prototype.transmettreObs = function() {
828
WidgetSaisie.prototype.transmettreObs = function() {
829
	var observations = $("#liste-obs").data();
829
	var observations = $("#liste-obs").data();
830
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
830
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
831
		this.afficherPanneau("#dialogue-zero-obs");
831
		this.afficherPanneau("#dialogue-zero-obs");
832
	} else {
832
	} else {
833
		this.nbObsEnCours = 1;
833
		this.nbObsEnCours = 1;
834
		this.nbObsTransmises = 0;
834
		this.nbObsTransmises = 0;
835
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
835
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
836
		this.depilerObsPourEnvoi();
836
		this.depilerObsPourEnvoi();
837
	}
837
	}
838
	return false;
838
	return false;
839
};
839
};
840
 
840
 
841
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
841
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
842
	var observations = $("#liste-obs").data();
842
	var observations = $("#liste-obs").data();
843
	// la boucle est factice car on utilise un tableau
843
	// la boucle est factice car on utilise un tableau
844
	// dont on a besoin de n'extraire que le premier élément
844
	// dont on a besoin de n'extraire que le premier élément
845
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
845
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
846
	// TODO: utiliser var.keys quand ça sera plus répandu
846
	// TODO: utiliser var.keys quand ça sera plus répandu
847
	// ou bien utiliser un vrai tableau et pas un objet
847
	// ou bien utiliser un vrai tableau et pas un objet
848
	for (var obsNum in observations) {
848
	for (var obsNum in observations) {
849
		var obsATransmettre = {
849
		var obsATransmettre = {
850
			'projet' : this.tagProjet,
850
			'projet' : this.tagProjet,
851
			'tag-obs' : this.tagObs,
851
			'tag-obs' : this.tagObs,
852
			'tag-img' : this.tagImg
852
			'tag-img' : this.tagImg
853
		};
853
		};
854
		var utilisateur = {
854
		var utilisateur = {
855
			id_utilisateur : $("#id_utilisateur").val(),
855
			id_utilisateur : $("#id_utilisateur").val(),
856
			prenom : $("#prenom").val(),
856
			prenom : $("#prenom").val(),
857
			nom : $("#nom").val(),
857
			nom : $("#nom").val(),
858
			courriel : $("#courriel").val()
858
			courriel : $("#courriel").val()
859
		};
859
		};
860
		obsATransmettre['utilisateur'] = utilisateur;
860
		obsATransmettre['utilisateur'] = utilisateur;
861
		obsATransmettre[obsNum] = observations[obsNum];
861
		obsATransmettre[obsNum] = observations[obsNum];
862
		var idObsNumerique = obsNum.replace('obsId', '');
862
		var idObsNumerique = obsNum.replace('obsId', '');
863
		if(idObsNumerique != "") {
863
		if(idObsNumerique != "") {
864
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
864
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
865
		}
865
		}
866
 
866
 
867
		break;
867
		break;
868
	}
868
	}
869
	$('#zone-liste-obs').addClass("hidden");
-
 
870
};
869
};
871
 
870
 
872
WidgetSaisie.prototype.mettreAJourProgression = function() {
871
WidgetSaisie.prototype.mettreAJourProgression = function() {
873
	this.nbObsTransmises++;
872
	this.nbObsTransmises++;
874
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
873
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
875
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
874
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
876
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
875
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
877
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
876
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
878
 
877
 
879
	if(this.obsNbre == 0) {
878
	if(this.obsNbre == 0) {
880
		$('.progress').removeClass('active');
879
		$('.progress').removeClass('active');
881
		$('.progress').removeClass('progress-striped');
880
		$('.progress').removeClass('progress-striped');
882
	}
881
	}
883
};
882
};
884
 
883
 
885
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
884
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
886
	var lthis = this;
885
	var lthis = this;
887
	var erreurMsg = "";
886
	var erreurMsg = "";
888
	$.ajax({
887
	$.ajax({
889
		url : lthis.serviceSaisieUrl,
888
		url : lthis.serviceSaisieUrl,
890
		type : "POST",
889
		type : "POST",
891
		data : observation,
890
		data : observation,
892
		dataType : "json",
891
		dataType : "json",
893
		beforeSend : function() {
892
		beforeSend : function() {
894
			$("#dialogue-obs-transaction-ko").hide();
893
			$("#dialogue-obs-transaction-ko").hide();
895
			$("#dialogue-obs-transaction-ok").hide();
894
			$("#dialogue-obs-transaction-ok").hide();
896
			$('.alert-txt').empty();
895
			$('.alert-txt').empty();
897
			$("#chargement").show();
896
			$("#chargement").show();
898
		},
897
		},
899
		success : function(data, textStatus, jqXHR) {
898
		success : function(data, textStatus, jqXHR) {
900
			// mise à jour du nombre d'obs à transmettre
899
			// mise à jour du nombre d'obs à transmettre
901
			// et suppression de l'obs
900
			// et suppression de l'obs
902
			lthis.supprimerObsParId(idObs);
901
			lthis.supprimerObsParId(idObs);
903
			lthis.nbObsEnCours++;
902
			lthis.nbObsEnCours++;
904
			// mise à jour du statut
903
			// mise à jour du statut
905
			lthis.mettreAJourProgression();
904
			lthis.mettreAJourProgression();
906
			if(lthis.obsNbre > 0) {
905
			if(lthis.obsNbre > 0) {
907
				// dépilement de la suivante
906
				// dépilement de la suivante
908
				lthis.depilerObsPourEnvoi();
907
				lthis.depilerObsPourEnvoi();
909
			}
908
			}
910
		},
909
		},
911
		statusCode : {
910
		statusCode : {
912
			500 : function(jqXHR, textStatus, errorThrown) {
911
			500 : function(jqXHR, textStatus, errorThrown) {
913
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
912
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
914
		    }
913
		    }
915
		},
914
		},
916
		error : function(jqXHR, textStatus, errorThrown) {
915
		error : function(jqXHR, textStatus, errorThrown) {
917
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
916
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
918
			try {
917
			try {
919
				reponse = jQuery.parseJSON(jqXHR.responseText);
918
				reponse = jQuery.parseJSON(jqXHR.responseText);
920
				if (reponse != null) {
919
				if (reponse != null) {
921
					$.each(reponse, function (cle, valeur) {
920
					$.each(reponse, function (cle, valeur) {
922
						erreurMsg += valeur + "\n";
921
						erreurMsg += valeur + "\n";
923
					});
922
					});
924
				}
923
				}
925
			} catch(e) {
924
			} catch(e) {
926
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
925
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
927
			}
926
			}
928
		},
927
		},
929
		complete : function(jqXHR, textStatus) {
928
		complete : function(jqXHR, textStatus) {
930
			var debugMsg = extraireEnteteDebug(jqXHR);
929
			var debugMsg = extraireEnteteDebug(jqXHR);
931
 
930
 
932
			if (erreurMsg != '') {
931
			if (erreurMsg != '') {
933
				if (this.debug) {
932
				if (this.debug) {
934
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
933
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
935
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
934
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
936
				}
935
				}
937
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
936
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
938
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
937
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
939
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
938
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
940
 
939
 
941
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
940
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
942
				$('#obs'+idObs+' div div').addClass('obs-erreur');
941
				$('#obs'+idObs+' div div').addClass('obs-erreur');
943
				window.location.hash = "obs"+idObs;
942
				window.location.hash = "obs"+idObs;
944
 
943
 
945
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
944
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
946
					.find('.courriel-erreur')
945
					.find('.courriel-erreur')
947
					.attr('href', hrefCourriel)
946
					.attr('href', hrefCourriel)
948
					.end()
947
					.end()
949
					.html());
948
					.html());
950
				$("#dialogue-obs-transaction-ko").show();
949
				$("#dialogue-obs-transaction-ko").show();
951
				$("#chargement").hide();
950
				$("#chargement").hide();
952
				lthis.initialiserBarreProgression();
951
				lthis.initialiserBarreProgression();
953
			} else {
952
			} else {
954
				if (lthis.debug) {
953
				if (lthis.debug) {
955
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
954
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
956
				}
955
				}
957
				if(lthis.obsNbre == 0) {
956
				if(lthis.obsNbre == 0) {
958
					setTimeout(function() {
957
					setTimeout(function() {
959
						$("#chargement").hide();
958
						$("#chargement").hide();
960
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
959
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
961
						$("#dialogue-obs-transaction-ok").show();
960
						$("#dialogue-obs-transaction-ok").show();
962
						window.location.hash = "dialogue-obs-transaction-ok";
961
						window.location.hash = "dialogue-obs-transaction-ok";
963
						lthis.initialiserObs();
962
						lthis.initialiserObs();
964
					}, 1500);
963
					}, 1500);
965
 
964
 
966
				}
965
				}
967
			}
966
			}
968
		}
967
		}
969
	});
968
	});
970
};
969
};
971
 
970
 
972
WidgetSaisie.prototype.validerFormulaire = function() {
971
WidgetSaisie.prototype.validerFormulaire = function() {
973
	$observateur = $("#form-observateur").valid();
972
	$observateur = $("#form-observateur").valid();
974
	$station = $("#form-station").valid();
973
	$station = $("#form-station").valid();
975
	$obs = $("#form-obs").valid();
974
	$obs = $("#form-obs").valid();
976
	return ($observateur == true && $station == true && $obs == true) ? true : false;
975
	return ($observateur == true && $station == true && $obs == true) ? true : false;
977
};
976
};
978
 
977
 
979
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
978
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
980
	var noms = new Array();
979
	var noms = new Array();
981
	$(".miniature-img").each(function() {
980
	$(".miniature-img").each(function() {
982
		noms.push($(this).attr('alt'));
981
		noms.push($(this).attr('alt'));
983
	});
982
	});
984
	return noms;
983
	return noms;
985
};
984
};
986
 
985
 
987
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
986
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
988
	var b64 = new Array();
987
	var b64 = new Array();
989
	$(".miniature-img").each(function() {
988
	$(".miniature-img").each(function() {
990
		if ($(this).hasClass('b64')) {
989
		if ($(this).hasClass('b64')) {
991
			b64.push($(this).attr('src'));
990
			b64.push($(this).attr('src'));
992
		} else if ($(this).hasClass('b64-canvas')) {
991
		} else if ($(this).hasClass('b64-canvas')) {
993
			b64.push($(this).data('b64'));
992
			b64.push($(this).data('b64'));
994
		}
993
		}
995
	});
994
	});
996
 
995
 
997
	return b64;
996
	return b64;
998
};
997
};
999
 
998
 
1000
WidgetSaisie.prototype.supprimerObs = function(selector) {
999
WidgetSaisie.prototype.supprimerObs = function(selector) {
1001
	var obsId = $(selector).val();
1000
	var obsId = $(selector).val();
1002
	// Problème avec IE 6 et 7
1001
	// Problème avec IE 6 et 7
1003
	if (obsId == "Supprimer") {
1002
	if (obsId == "Supprimer") {
1004
		obsId = $(selector).attr("title");
1003
		obsId = $(selector).attr("title");
1005
	}
1004
	}
1006
	this.supprimerObsParId(obsId);
1005
	this.supprimerObsParId(obsId);
1007
};
1006
};
1008
 
1007
 
1009
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1008
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1010
	this.obsNbre = this.obsNbre - 1;
1009
	this.obsNbre = this.obsNbre - 1;
1011
	$(".obs-nbre").text(this.obsNbre);
1010
	$(".obs-nbre").text(this.obsNbre);
1012
	$(".obs-nbre").triggerHandler('changement');
1011
	$(".obs-nbre").triggerHandler('changement');
1013
	$('.obs'+obsId).remove();
1012
	$('.obs'+obsId).remove();
1014
	$("#liste-obs").removeData('obsId'+obsId);
1013
	$("#liste-obs").removeData('obsId'+obsId);
1015
};
1014
};
1016
 
1015
 
1017
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1016
WidgetSaisie.prototype.initialiserBarreProgression = function() {
1018
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1017
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1019
	$('#barre-progression-upload').attr('style', "width: 0%");
1018
	$('#barre-progression-upload').attr('style', "width: 0%");
1020
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1019
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1021
	$('.progress').addClass('active');
1020
	$('.progress').addClass('active');
1022
	$('.progress').addClass('progress-striped');
1021
	$('.progress').addClass('progress-striped');
1023
};
1022
};
1024
 
1023
 
1025
WidgetSaisie.prototype.initialiserObs = function() {
1024
WidgetSaisie.prototype.initialiserObs = function() {
1026
	this.obsNbre = 0;
1025
	this.obsNbre = 0;
1027
	this.nbObsTransmises = 0;
1026
	this.nbObsTransmises = 0;
1028
	this.nbObsEnCours = 0;
1027
	this.nbObsEnCours = 0;
1029
	this.totalObsATransmettre = 0;
1028
	this.totalObsATransmettre = 0;
1030
	this.initialiserBarreProgression();
1029
	this.initialiserBarreProgression();
1031
	$(".obs-nbre").text(this.obsNbre);
1030
	$(".obs-nbre").text(this.obsNbre);
1032
	$(".obs-nbre").triggerHandler('changement');
1031
	$(".obs-nbre").triggerHandler('changement');
1033
	$("#liste-obs").removeData();
1032
	$("#liste-obs").removeData();
1034
	$('.obs').remove();
1033
	$('.obs').remove();
1035
	$("#dialogue-bloquer-creer-obs").hide();
1034
	$("#dialogue-bloquer-creer-obs").hide();
1036
};
1035
};
1037
 
1036
 
1038
/**
1037
/**
1039
 * Ajoute une boîte de miniatures avec défilement des images,
1038
 * Ajoute une boîte de miniatures avec défilement des images,
1040
 * pour une obs de la liste des obs à transmettre
1039
 * pour une obs de la liste des obs à transmettre
1041
 */
1040
 */
1042
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1041
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1043
	var html = '',
1042
	var html = '',
1044
		miniatures = '',
1043
		miniatures = '',
1045
		premiere = true;
1044
		premiere = true;
1046
	if ($("#miniatures img").length >= 1) {
1045
	if ($("#miniatures img").length >= 1) {
1047
		$("#miniatures img").each(function() {
1046
		$("#miniatures img").each(function() {
1048
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1047
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1049
			premiere = false;
1048
			premiere = false;
1050
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1049
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1051
				src = $(this).attr("src"),
1050
				src = $(this).attr("src"),
1052
				alt = $(this).attr("alt"),
1051
				alt = $(this).attr("alt"),
1053
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1052
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1054
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1053
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1055
			miniatures += miniature;
1054
			miniatures += miniature;
1056
		});
1055
		});
1057
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
1056
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
1058
		var html =
1057
		var html =
1059
			'<div class="defilement-miniatures">'+
1058
			'<div class="defilement-miniatures">'+
1060
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1059
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1061
				miniatures+
1060
				miniatures+
1062
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1061
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1063
			'</div>';
1062
			'</div>';
1064
	} else {
1063
	} else {
1065
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1064
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1066
	}
1065
	}
1067
	return html;
1066
	return html;
1068
};
1067
};
1069
 
1068
 
1070
WidgetSaisie.prototype.defilerMiniatures = function(element) {
1069
WidgetSaisie.prototype.defilerMiniatures = function(element) {
1071
 
1070
 
1072
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1071
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1073
	miniatureSelectionne.removeClass('miniature-selectionnee');
1072
	miniatureSelectionne.removeClass('miniature-selectionnee');
1074
	miniatureSelectionne.addClass('miniature-cachee');
1073
	miniatureSelectionne.addClass('miniature-cachee');
1075
	var miniatureAffichee = miniatureSelectionne;
1074
	var miniatureAffichee = miniatureSelectionne;
1076
 
1075
 
1077
	if(element.hasClass('defilement-miniatures-gauche')) {
1076
	if(element.hasClass('defilement-miniatures-gauche')) {
1078
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1077
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1079
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1078
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1080
		} else {
1079
		} else {
1081
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1080
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1082
		}
1081
		}
1083
	} else {
1082
	} else {
1084
		if(miniatureSelectionne.next('.miniature').length != 0) {
1083
		if(miniatureSelectionne.next('.miniature').length != 0) {
1085
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1084
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1086
		} else {
1085
		} else {
1087
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1086
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1088
		}
1087
		}
1089
	}
1088
	}
1090
	//console.log(miniatureAffichee);
1089
	//console.log(miniatureAffichee);
1091
	miniatureAffichee.addClass('miniature-selectionnee');
1090
	miniatureAffichee.addClass('miniature-selectionnee');
1092
	miniatureAffichee.removeClass('miniature-cachee');
1091
	miniatureAffichee.removeClass('miniature-cachee');
1093
};
1092
};
1094
 
1093
 
1095
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1094
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1096
	var nn = '';
1095
	var nn = '';
1097
	if ($("#taxon").data("numNomSel") == undefined) {
1096
	if ($("#taxon").data("numNomSel") == undefined) {
1098
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1097
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1099
	} else {
1098
	} else {
1100
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1099
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1101
	}
1100
	}
1102
	return nn;
1101
	return nn;
1103
};
1102
};
1104
 
1103
 
1105
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1104
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1106
	var lthis = this;
1105
	var lthis = this;
1107
	$('#taxon').autocomplete({
1106
	$('#taxon').autocomplete({
1108
		source: function(requete, add){
1107
		source: function(requete, add){
1109
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1108
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1110
			requete = "";
1109
			requete = "";
1111
			if($("#referentiel").val() != "autre") {
1110
			if($("#referentiel").val() != "autre") {
1112
				var url = lthis.getUrlAutocompletionNomsSci();
1111
				var url = lthis.getUrlAutocompletionNomsSci();
1113
				$.getJSON(url, requete, function(data) {
1112
				$.getJSON(url, requete, function(data) {
1114
					var suggestions = lthis.traiterRetourNomsSci(data);
1113
					var suggestions = lthis.traiterRetourNomsSci(data);
1115
					add(suggestions);
1114
					add(suggestions);
1116
	            });
1115
	            });
1117
			}
1116
			}
1118
        },
1117
        },
1119
        html: true
1118
        html: true
1120
	});
1119
	});
1121
 
1120
 
1122
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1121
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1123
		$("#taxon").data(ui.item);
1122
		$("#taxon").data(ui.item);
1124
		if (ui.item.retenu == true) {
1123
		if (ui.item.retenu == true) {
1125
			$("#taxon").addClass('ns-retenu');
1124
			$("#taxon").addClass('ns-retenu');
1126
		} else {
1125
		} else {
1127
			$("#taxon").removeClass('ns-retenu');
1126
			$("#taxon").removeClass('ns-retenu');
1128
		}
1127
		}
1129
	});
1128
	});
1130
};
1129
};
1131
 
1130
 
1132
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1131
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1133
	var mots = $('#taxon').val();
1132
	var mots = $('#taxon').val();
1134
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1133
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1135
	url = url.replace('{masque}', mots);
1134
	url = url.replace('{masque}', mots);
1136
	return url;
1135
	return url;
1137
};
1136
};
1138
 
1137
 
1139
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
1138
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
1140
	var suggestions = [];
1139
	var suggestions = [];
1141
	if (data.resultat != undefined) {
1140
	if (data.resultat != undefined) {
1142
		$.each(data.resultat, function(i, val) {
1141
		$.each(data.resultat, function(i, val) {
1143
			val.nn = i;
1142
			val.nn = i;
1144
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1143
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1145
				nomRet : '', numNomRet : '', famille : '', retenu : false
1144
				nomRet : '', numNomRet : '', famille : '', retenu : false
1146
			};
1145
			};
1147
			if (suggestions.length >= this.autocompletionElementsNbre) {
1146
			if (suggestions.length >= this.autocompletionElementsNbre) {
1148
				nom.label = "...";
1147
				nom.label = "...";
1149
				nom.value = $('#taxon').val();
1148
				nom.value = $('#taxon').val();
1150
				suggestions.push(nom);
1149
				suggestions.push(nom);
1151
				return false;
1150
				return false;
1152
			} else {
1151
			} else {
1153
				nom.label = val.nom_sci_complet;
1152
				nom.label = val.nom_sci_complet;
1154
				nom.value = val.nom_sci_complet;
1153
				nom.value = val.nom_sci_complet;
1155
				nom.nt = val.num_taxonomique;
1154
				nom.nt = val.num_taxonomique;
1156
				nom.nomSel = val.nom_sci;
1155
				nom.nomSel = val.nom_sci;
1157
				nom.nomSelComplet = val.nom_sci_complet;
1156
				nom.nomSelComplet = val.nom_sci_complet;
1158
				nom.numNomSel = val.nn;
1157
				nom.numNomSel = val.nn;
1159
				nom.nomRet = val.nom_retenu_complet;
1158
				nom.nomRet = val.nom_retenu_complet;
1160
				nom.numNomRet = val["nom_retenu.id"];
1159
				nom.numNomRet = val["nom_retenu.id"];
1161
				nom.famille = val.famille;
1160
				nom.famille = val.famille;
1162
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1161
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1163
				// en tout cas c'est harmonisé avec le CeL
1162
				// en tout cas c'est harmonisé avec le CeL
1164
				nom.retenu = (val.retenu == 'true') ? true : false;
1163
				nom.retenu = (val.retenu == 'true') ? true : false;
1165
 
1164
 
1166
				suggestions.push(nom);
1165
				suggestions.push(nom);
1167
			}
1166
			}
1168
		});
1167
		});
1169
	}
1168
	}
1170
 
1169
 
1171
	return suggestions;
1170
	return suggestions;
1172
};
1171
};
1173
 
1172
 
1174
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1173
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1175
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
1174
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
1176
};
1175
};
1177
 
1176
 
1178
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1177
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1179
	$(selecteur).hide();
1178
	$(selecteur).hide();
1180
};
1179
};
1181
 
1180
 
1182
// lib hors objet --
1181
// lib hors objet --
1183
 
1182
 
1184
/**
1183
/**
1185
* Stope l'évènement courant quand on clique sur un lien.
1184
* Stope l'évènement courant quand on clique sur un lien.
1186
* Utile pour Chrome, Safari...
1185
* Utile pour Chrome, Safari...
1187
*/
1186
*/
1188
function arreter(evenement) {
1187
function arreter(evenement) {
1189
	if (evenement.stopPropagation) {
1188
	if (evenement.stopPropagation) {
1190
		evenement.stopPropagation();
1189
		evenement.stopPropagation();
1191
	}
1190
	}
1192
	if (evenement.preventDefault) {
1191
	if (evenement.preventDefault) {
1193
		evenement.preventDefault();
1192
		evenement.preventDefault();
1194
	}
1193
	}
1195
	return false;
1194
	return false;
1196
}
1195
}
1197
 
1196
 
1198
/**
1197
/**
1199
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1198
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1200
 * @param jqXHR
1199
 * @param jqXHR
1201
 * @returns {String}
1200
 * @returns {String}
1202
 */
1201
 */
1203
function extraireEnteteDebug(jqXHR) {
1202
function extraireEnteteDebug(jqXHR) {
1204
	var msgDebug = '';
1203
	var msgDebug = '';
1205
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1204
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1206
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1205
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1207
		if (debugInfos != null) {
1206
		if (debugInfos != null) {
1208
			$.each(debugInfos, function (cle, valeur) {
1207
			$.each(debugInfos, function (cle, valeur) {
1209
				msgDebug += valeur + "\n";
1208
				msgDebug += valeur + "\n";
1210
			});
1209
			});
1211
		}
1210
		}
1212
	}
1211
	}
1213
	return msgDebug;
1212
	return msgDebug;
1214
}
1213
}
1215
 
1214
 
1216
/*
1215
/*
1217
 * jQuery UI Autocomplete HTML Extension
1216
 * jQuery UI Autocomplete HTML Extension
1218
 *
1217
 *
1219
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1218
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1220
 * Dual licensed under the MIT or GPL Version 2 licenses.
1219
 * Dual licensed under the MIT or GPL Version 2 licenses.
1221
 *
1220
 *
1222
 * http://github.com/scottgonzalez/jquery-ui-extensions
1221
 * http://github.com/scottgonzalez/jquery-ui-extensions
1223
 *
1222
 *
1224
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1223
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1225
 */
1224
 */
1226
(function( $ ) {
1225
(function( $ ) {
1227
	var proto = $.ui.autocomplete.prototype,
1226
	var proto = $.ui.autocomplete.prototype,
1228
		initSource = proto._initSource;
1227
		initSource = proto._initSource;
1229
 
1228
 
1230
	WidgetSaisie.prototype.filter = function( array, term ) {
1229
	WidgetSaisie.prototype.filter = function( array, term ) {
1231
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1230
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1232
		return $.grep( array, function(value) {
1231
		return $.grep( array, function(value) {
1233
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1232
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1234
		});
1233
		});
1235
	}
1234
	}
1236
 
1235
 
1237
	$.extend( proto, {
1236
	$.extend( proto, {
1238
		_initSource: function() {
1237
		_initSource: function() {
1239
			if ( this.options.html && $.isArray(this.options.source) ) {
1238
			if ( this.options.html && $.isArray(this.options.source) ) {
1240
				this.source = function( request, response ) {
1239
				this.source = function( request, response ) {
1241
					response( filter( this.options.source, request.term ) );
1240
					response( filter( this.options.source, request.term ) );
1242
				};
1241
				};
1243
			} else {
1242
			} else {
1244
				initSource.call( this );
1243
				initSource.call( this );
1245
			}
1244
			}
1246
		},
1245
		},
1247
		_renderItem: function( ul, item) {
1246
		_renderItem: function( ul, item) {
1248
			if (item.retenu == true) {
1247
			if (item.retenu == true) {
1249
				item.label = "<strong>"+item.label+"</strong>";
1248
				item.label = "<strong>"+item.label+"</strong>";
1250
			}
1249
			}
1251
 
1250
 
1252
			return $( "<li></li>" )
1251
			return $( "<li></li>" )
1253
				.data( "item.autocomplete", item )
1252
				.data( "item.autocomplete", item )
1254
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1253
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1255
				.appendTo( ul );
1254
				.appendTo( ul );
1256
		}
1255
		}
1257
	});
1256
	});
1258
})( jQuery );
1257
})( jQuery );