Subversion Repositories eFlore/Applications.cel

Rev

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

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