Subversion Repositories eFlore/Applications.cel

Rev

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

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