Subversion Repositories eFlore/Applications.cel

Rev

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

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