Subversion Repositories eFlore/Applications.cel

Rev

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

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