Subversion Repositories eFlore/Applications.cel

Rev

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

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