Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 1210 Rev 1213
1
//+---------------------------------------------------------------------------------------------------------+
1
//+---------------------------------------------------------------------------------------------------------+
2
// GÉNÉRAL
2
// GÉNÉRAL
3
/**
3
/**
4
 * Stope l'évènement courrant quand on clique sur un lien.
4
 * Stope l'évènement courrant quand on clique sur un lien.
5
 * Utile pour Chrome, Safari...
5
 * Utile pour Chrome, Safari...
6
 * @param evenement
6
 * @param evenement
7
 * @return
7
 * @return
8
 */
8
 */
9
function arreter(evenement) {
9
function arreter(evenement) {
10
	if (evenement.stopPropagation) {
10
	if (evenement.stopPropagation) {
11
		evenement.stopPropagation();
11
		evenement.stopPropagation();
12
	}
12
	}
13
	return false;
13
	return false;
14
}
14
}
15
 
15
 
16
// TODO : voir si cette fonction est bien utile. Résoud le pb d'un warning sous chrome.
16
// TODO : voir si cette fonction est bien utile. Résoud le pb d'un warning sous chrome.
17
(function(){
17
(function(){
18
    // remove layerX and layerY
18
    // remove layerX and layerY
19
    var all = $.event.props,
19
    var all = $.event.props,
20
        len = all.length,
20
        len = all.length,
21
        res = [];
21
        res = [];
22
    while (len--) {
22
    while (len--) {
23
      var el = all[len];
23
      var el = all[len];
24
      if (el != 'layerX' && el != 'layerY') res.push(el);
24
      if (el != 'layerX' && el != 'layerY') res.push(el);
25
    }
25
    }
26
    $.event.props = res;
26
    $.event.props = res;
27
}());
27
}());
28
 
28
 
29
//+----------------------------------------------------------------------------------------------------------+
29
//+----------------------------------------------------------------------------------------------------------+
30
//UPLOAD PHOTO : Traitement de l'image 
30
//UPLOAD PHOTO : Traitement de l'image 
31
$(document).ready(function() {	
31
$(document).ready(function() {	
32
	
32
	
33
	$("#effacer-miniature").click(function () {
33
	$("#effacer-miniature").click(function () {
34
		supprimerMiniature();
34
		supprimerMiniature();
35
	});
35
	});
36
	
36
	
37
	if (HTML5 && window.File && window.FileReader && isCanvasSupported()) {
37
	if (HTML5 && window.File && window.FileReader && isCanvasSupported()) {
38
		if (DEBUG) {
38
		if (DEBUG) {
39
			console.log("Support OK pour : API File et Canvas.");
39
			console.log("Support OK pour : API File et Canvas.");
40
		}
40
		}
41
		$('#fichier').bind('change', function(e) {
41
		$('#fichier').bind('change', function(e) {
42
			afficherMiniatureHtml5(e);
42
			afficherMiniatureHtml5(e);
43
		});	
43
		});	
44
	} else {
44
	} else {
45
		$("#fichier").bind('change', function (e) {
45
		$("#fichier").bind('change', function (e) {
46
			arreter(e);
46
			arreter(e);
47
			var options = { 
47
			var options = { 
48
				success: afficherMiniature, // post-submit callback 
48
				success: afficherMiniature, // post-submit callback 
49
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
49
				dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type) 
50
				resetForm: true // reset the form after successful submit 
50
				resetForm: true // reset the form after successful submit 
51
			};
51
			};
52
			$("#form-upload").ajaxSubmit(options);
52
			$("#form-upload").ajaxSubmit(options);
53
			return false;
53
			return false;
54
		});
54
		});
55
	}	
55
	}	
56
});
56
});
57
function isCanvasSupported(){
57
function isCanvasSupported(){
58
	var elem = document.createElement('canvas');
58
	var elem = document.createElement('canvas');
59
	return !!(elem.getContext && elem.getContext('2d'));
59
	return !!(elem.getContext && elem.getContext('2d'));
60
}
60
}
61
 
61
 
62
function afficherMiniatureHtml5(evt) {
62
function afficherMiniatureHtml5(evt) {
63
	supprimerMiniature();
63
	supprimerMiniature();
64
	
64
	
65
	var selectedfiles = evt.target.files;
65
	var selectedfiles = evt.target.files;
66
	var f = selectedfiles[0];// Nous récupérons seulement le premier fichier.
66
	var f = selectedfiles[0];// Nous récupérons seulement le premier fichier.
67
	if (f.type != 'image/jpeg') {
67
	if (f.type != 'image/jpeg') {
68
		var message = "Seule les images JPEG sont supportées.";
68
		var message = "Seule les images JPEG sont supportées.";
69
		$("#miniature-msg").append(message);
69
		$("#miniature-msg").append(message);
70
	} else if (f.size > 5242880) {
70
	} else if (f.size > 5242880) {
71
		var message = "Votre image à un poids supérieur à 5Mo.";
71
		var message = "Votre image à un poids supérieur à 5Mo.";
72
		$("#miniature-msg").append(message);
72
		$("#miniature-msg").append(message);
73
	} else {
73
	} else {
74
		var reader = new FileReader();
74
		var reader = new FileReader();
75
		// Lit le fichier image commune url de données
75
		// Lit le fichier image commune url de données
76
		reader.readAsDataURL(f);
76
		reader.readAsDataURL(f);
77
		var imgNom = f.name;
77
		var imgNom = f.name;
78
	
78
	
79
		// Closure pour capturer les infos du fichier
79
		// Closure pour capturer les infos du fichier
80
		reader.onload = (function(theFile) {
80
		reader.onload = (function(theFile) {
81
			return function(e) {
81
			return function(e) {
82
				// Rendre la miniature
82
				// Rendre la miniature
83
				var imageBase64 = e.target.result;
83
				var imageBase64 = e.target.result;
84
				//$("#miniature").append('<img id="miniature-img" class="miniature b64" src="'+imageBase64+'" alt="'+imgNom+'"/>');
84
				//$("#miniature").append('<img id="miniature-img" class="miniature b64" src="'+imageBase64+'" alt="'+imgNom+'"/>');
85
				
85
				
86
				// HTML5 Canvas
86
				// HTML5 Canvas
87
				var img = new Image();
87
				var img = new Image();
88
			    img.src = imageBase64;
88
			    img.src = imageBase64;
89
			    img.alt = imgNom;
89
			    img.alt = imgNom;
90
			    img.onload = function() {
90
			    img.onload = function() {
91
			    	transformerImgEnCanvas(this, 100, 100, false, 'white');
91
			    	transformerImgEnCanvas(this, 100, 100, false, 'white');
92
			    };
92
			    };
93
			};
93
			};
94
		})(f);
94
		})(f);
95
	}
95
	}
96
	$("#effacer-miniature").show();
96
	$("#effacer-miniature").show();
97
}
97
}
98
function transformerImgEnCanvas(img, thumbwidth, thumbheight, crop, background) {
98
function transformerImgEnCanvas(img, thumbwidth, thumbheight, crop, background) {
99
	var canvas = document.createElement('canvas');
99
	var canvas = document.createElement('canvas');
100
	canvas.width = thumbwidth;
100
	canvas.width = thumbwidth;
101
	canvas.height = thumbheight;
101
	canvas.height = thumbheight;
102
	var dimensions = calculerDimenssions(img.width, img.height, thumbwidth, thumbheight);
102
	var dimensions = calculerDimenssions(img.width, img.height, thumbwidth, thumbheight);
103
	if (crop) {
103
	if (crop) {
104
		canvas.width = dimensions.w;
104
		canvas.width = dimensions.w;
105
		canvas.height = dimensions.h;
105
		canvas.height = dimensions.h;
106
		dimensions.x = 0;
106
		dimensions.x = 0;
107
		dimensions.y = 0;
107
		dimensions.y = 0;
108
	}
108
	}
109
	cx = canvas.getContext('2d');
109
	cx = canvas.getContext('2d');
110
	if (background !== 'transparent') {
110
	if (background !== 'transparent') {
111
		cx.fillStyle = background;
111
		cx.fillStyle = background;
112
		cx.fillRect(0, 0, thumbwidth, thumbheight);
112
		cx.fillRect(0, 0, thumbwidth, thumbheight);
113
	}
113
	}
114
	cx.drawImage(img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
114
	cx.drawImage(img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
115
	afficherMiniatureCanvas(img, canvas);
115
	afficherMiniatureCanvas(img, canvas);
116
}
116
}
117
 
117
 
118
function calculerDimenssions(imagewidth, imageheight, thumbwidth, thumbheight) {
118
function calculerDimenssions(imagewidth, imageheight, thumbwidth, thumbheight) {
119
	var w = 0, h = 0, x = 0, y = 0,
119
	var w = 0, h = 0, x = 0, y = 0,
120
	    widthratio = imagewidth / thumbwidth,
120
	    widthratio = imagewidth / thumbwidth,
121
	    heightratio = imageheight / thumbheight,
121
	    heightratio = imageheight / thumbheight,
122
	    maxratio = Math.max(widthratio, heightratio);
122
	    maxratio = Math.max(widthratio, heightratio);
123
	if (maxratio > 1) {
123
	if (maxratio > 1) {
124
	    w = imagewidth / maxratio;
124
	    w = imagewidth / maxratio;
125
	    h = imageheight / maxratio;
125
	    h = imageheight / maxratio;
126
	} else {
126
	} else {
127
	    w = imagewidth;
127
	    w = imagewidth;
128
	    h = imageheight;
128
	    h = imageheight;
129
	}
129
	}
130
	x = (thumbwidth - w) / 2;
130
	x = (thumbwidth - w) / 2;
131
	y = (thumbheight - h) / 2;
131
	y = (thumbheight - h) / 2;
132
	return {w:w, h:h, x:x, y:y};
132
	return {w:w, h:h, x:x, y:y};
133
}
133
}
134
 
134
 
135
function afficherMiniatureCanvas(imgB64, canvas) {
135
function afficherMiniatureCanvas(imgB64, canvas) {
136
	var url = canvas.toDataURL('image/jpeg' , 0.8);
136
	var url = canvas.toDataURL('image/jpeg' , 0.8);
137
	var alt = imgB64.alt;
137
	var alt = imgB64.alt;
138
	var title = Math.round(url.length / 1000 * 100) / 100 + ' KB';
138
	var title = Math.round(url.length / 1000 * 100) / 100 + ' KB';
139
	var miniature = '<img id="miniature-img" class="miniature b64-canvas" src="'+url+'" alt="'+alt+'" title="'+title+'" />';
139
	var miniature = '<img id="miniature-img" class="miniature b64-canvas" src="'+url+'" alt="'+alt+'" title="'+title+'" />';
140
	$("#miniature").append(miniature);
140
	$("#miniature").append(miniature);
141
	$("#miniature-img").data('b64', imgB64.src);
141
	$("#miniature-img").data('b64', imgB64.src);
142
}
142
}
143
 
143
 
144
function afficherMiniature(reponse) { 
144
function afficherMiniature(reponse) { 
145
	supprimerMiniature();
145
	supprimerMiniature();
146
	if (DEBUG) {
146
	if (DEBUG) {
147
		var debogage = $("debogage", reponse).text();
147
		var debogage = $("debogage", reponse).text();
148
		console.log("Débogage upload : "+debogage);
148
		console.log("Débogage upload : "+debogage);
149
	}
149
	}
150
	var message = $("message", reponse).text();
150
	var message = $("message", reponse).text();
151
	if (message != '') {
151
	if (message != '') {
152
		$("#miniature-msg").append(message);
152
		$("#miniature-msg").append(message);
153
	} else {
153
	} else {
154
		var miniatureUrl = $("miniature-url", reponse).text();
154
		var miniatureUrl = $("miniature-url", reponse).text();
155
		var imgNom = $("image-nom", reponse).text();
155
		var imgNom = $("image-nom", reponse).text();
156
		$("#miniature").append('<img id="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>');
156
		$("#miniature").append('<img id="miniature-img" class="miniature" alt="'+imgNom+'" src="'+miniatureUrl+'"/>');
157
	}
157
	}
158
	$("#effacer-miniature").show();		
158
	$("#effacer-miniature").show();		
159
}
159
}
160
 
160
 
161
function supprimerMiniature() {
161
function supprimerMiniature() {
162
	$("#miniature").empty();
162
	$("#miniature").empty();
163
	$("#miniature-msg").empty();
163
	$("#miniature-msg").empty();
164
	$("#effacer-miniature").hide();
164
	$("#effacer-miniature").hide();
165
}
165
}
166
 
166
 
167
//+----------------------------------------------------------------------------------------------------------+
167
//+----------------------------------------------------------------------------------------------------------+
168
// GOOGLE MAP
168
// GOOGLE MAP
169
var map;
169
var map;
170
var marker;
170
var marker;
171
var latLng;
171
var latLng;
172
 
172
 
173
function initialiserGoogleMap(){
173
function initialiserGoogleMap(){
174
	// Carte
174
	// Carte
175
	var latLng = new google.maps.LatLng(48.8543, 2.3483);// Paris
175
	var latLng = new google.maps.LatLng(48.8543, 2.3483);// Paris
176
	
176
	
177
	var options = {
177
	var options = {
178
		zoom: 16,
178
		zoom: 16,
179
		center: latLng,
179
		center: latLng,
180
		mapTypeId: google.maps.MapTypeId.HYBRID,
180
		mapTypeId: google.maps.MapTypeId.HYBRID,
181
		mapTypeControlOptions: {
181
		mapTypeControlOptions: {
182
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
182
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
183
	};
183
	};
184
 
184
 
185
	// Ajout de la couche OSM à la carte
185
	// Ajout de la couche OSM à la carte
186
	osmMapType = new google.maps.ImageMapType({
186
	osmMapType = new google.maps.ImageMapType({
187
		getTileUrl: function(coord, zoom) {
187
		getTileUrl: function(coord, zoom) {
188
			return "http://tile.openstreetmap.org/" +
188
			return "http://tile.openstreetmap.org/" +
189
			zoom + "/" + coord.x + "/" + coord.y + ".png";
189
			zoom + "/" + coord.x + "/" + coord.y + ".png";
190
		},
190
		},
191
		tileSize: new google.maps.Size(256, 256),
191
		tileSize: new google.maps.Size(256, 256),
192
		isPng: true,
192
		isPng: true,
193
		alt: 'OpenStreetMap',
193
		alt: 'OpenStreetMap',
194
		name: 'OSM',
194
		name: 'OSM',
195
		maxZoom: 19
195
		maxZoom: 19
196
	});
196
	});
197
	
197
	
198
	// Création de la carte Google
198
	// Création de la carte Google
199
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
199
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
200
	map.mapTypes.set('OSM', osmMapType);
200
	map.mapTypes.set('OSM', osmMapType);
201
	
201
	
202
	// Marqueur google draggable
202
	// Marqueur google draggable
203
	marker = new google.maps.Marker({
203
	marker = new google.maps.Marker({
204
		map: map,
204
		map: map,
205
		draggable: true,
205
		draggable: true,
206
		title: 'Ma station',
206
		title: 'Ma station',
207
		icon: GOOGLE_MAP_MARQUEUR_URL,
207
		icon: GOOGLE_MAP_MARQUEUR_URL,
208
		position: latLng
208
		position: latLng
209
	});
209
	});
210
	
210
	
211
	deplacerMarker(latLng);
211
	deplacerMarker(latLng);
212
	
212
	
213
	// Tentative de geocalisation
213
	// Tentative de geocalisation
214
	if (navigator.geolocation) {
214
	if (navigator.geolocation) {
215
		navigator.geolocation.getCurrentPosition(function(position) {
215
		navigator.geolocation.getCurrentPosition(function(position) {
216
			var latitude = position.coords.latitude;
216
			var latitude = position.coords.latitude;
217
			var longitude = position.coords.longitude;
217
			var longitude = position.coords.longitude;
218
			latLng = new google.maps.LatLng(latitude, longitude);
218
			latLng = new google.maps.LatLng(latitude, longitude);
219
			deplacerMarker(latLng);
219
			deplacerMarker(latLng);
220
		});
220
		});
221
	}
221
	}
222
}
222
}
223
 
223
 
224
$(document).ready(function() {
224
$(document).ready(function() {
225
	
225
	
226
	initialiserGoogleMap();
226
	initialiserGoogleMap();
227
	
227
	
228
	$("#geolocaliser").click(function() {
228
	$("#geolocaliser").click(function() {
229
		var latitude = $('#latitude').val();
229
		var latitude = $('#latitude').val();
230
		var longitude = $('#longitude').val();
230
		var longitude = $('#longitude').val();
231
		latLng = new google.maps.LatLng(latitude, longitude);
231
		latLng = new google.maps.LatLng(latitude, longitude);
232
		deplacerMarker(latLng);
232
		deplacerMarker(latLng);
233
	});
233
	});
234
	
234
	
235
	google.maps.event.addListener(marker, 'dragend', function() {
235
	google.maps.event.addListener(marker, 'dragend', function() {
236
		trouverCommune(marker.getPosition());
236
		trouverCommune(marker.getPosition());
237
		mettreAJourMarkerPosition(marker.getPosition());
237
		mettreAJourMarkerPosition(marker.getPosition());
238
	});
238
	});
239
	
239
	
240
	google.maps.event.addListener(map, 'click', function(event) {
240
	google.maps.event.addListener(map, 'click', function(event) {
241
		deplacerMarker(event.latLng);
241
		deplacerMarker(event.latLng);
242
	});
242
	});
243
});
243
});
244
 
244
 
245
function deplacerMarker(latLng) {
245
function deplacerMarker(latLng) {
246
	if (marker != undefined) {
246
	if (marker != undefined) {
247
		marker.setPosition(latLng);
247
		marker.setPosition(latLng);
248
		map.setCenter(latLng);
248
		map.setCenter(latLng);
249
		mettreAJourMarkerPosition(latLng);
249
		mettreAJourMarkerPosition(latLng);
250
		trouverCommune(latLng);
250
		trouverCommune(latLng);
251
	}
251
	}
252
}
252
}
253
 
253
 
254
function mettreAJourMarkerPosition(latLng) {
254
function mettreAJourMarkerPosition(latLng) {
255
	var lat = latLng.lat().toFixed(5);
255
	var lat = latLng.lat().toFixed(5);
256
	var lng = latLng.lng().toFixed(5); 
256
	var lng = latLng.lng().toFixed(5); 
257
	remplirChampLatitude(lat);
257
	remplirChampLatitude(lat);
258
	remplirChampLongitude(lng);
258
	remplirChampLongitude(lng);
259
}
259
}
260
 
260
 
261
function remplirChampLatitude(latDecimale) {
261
function remplirChampLatitude(latDecimale) {
262
	var lat = Math.round(latDecimale * 100000) / 100000;
262
	var lat = Math.round(latDecimale * 100000) / 100000;
263
	$('#latitude').val(lat);
263
	$('#latitude').val(lat);
264
}
264
}
265
 
265
 
266
function remplirChampLongitude(lngDecimale) {
266
function remplirChampLongitude(lngDecimale) {
267
	var lng = Math.round(lngDecimale * 100000) / 100000;
267
	var lng = Math.round(lngDecimale * 100000) / 100000;
268
	$('#longitude').val(lng);
268
	$('#longitude').val(lng);
269
}
269
}
270
 
270
 
271
function trouverCommune(pos) {
271
function trouverCommune(pos) {
272
	$(function() {
272
	$(function() {
273
		var urlNomCommuneFormatee = SERVICE_NOM_COMMUNE_URL.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
273
		var urlNomCommuneFormatee = SERVICE_NOM_COMMUNE_URL.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
274
		$.ajax({
274
		$.ajax({
275
			url : urlNomCommuneFormatee,
275
			url : urlNomCommuneFormatee,
276
			type : "GET",
276
			type : "GET",
277
			dataType : "jsonp",
277
			dataType : "jsonp",
278
			beforeSend : function() {
278
			beforeSend : function() {
279
				$(".commune-info").empty();	
279
				$(".commune-info").empty();	
280
				$("#dialogue-erreur").empty();
280
				$("#dialogue-erreur").empty();
281
			},
281
			},
282
			success : function(data, textStatus, jqXHR) {
282
			success : function(data, textStatus, jqXHR) {
283
				$(".commune-info").empty();
283
				$(".commune-info").empty();
284
				$("#commune-nom").append(data.nom);
284
				$("#commune-nom").append(data.nom);
285
				$("#commune-code-insee").append(data.codeINSEE);
285
				$("#commune-code-insee").append(data.codeINSEE);
286
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
286
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
287
			},
287
			},
288
			statusCode : {
288
			statusCode : {
289
			    500 : function(jqXHR, textStatus, errorThrown) {
289
			    500 : function(jqXHR, textStatus, errorThrown) {
290
					if (DEBUG) {	
290
					if (DEBUG) {	
291
						$("#dialogue-erreur").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
291
						$("#dialogue-erreur").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
292
						reponse = jQuery.parseJSON(jqXHR.responseText);
292
						reponse = jQuery.parseJSON(jqXHR.responseText);
293
						var erreurMsg = "";
293
						var erreurMsg = "";
294
						if (reponse != null) {
294
						if (reponse != null) {
295
							$.each(reponse, function (cle, valeur) {
295
							$.each(reponse, function (cle, valeur) {
296
								erreurMsg += valeur + "<br />";
296
								erreurMsg += valeur + "<br />";
297
							});
297
							});
298
						}
298
						}
299
						
299
						
300
						$("#dialogue-erreur").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
300
						$("#dialogue-erreur").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
301
					}
301
					}
302
			    }
302
			    }
303
			},
303
			},
304
			error : function(jqXHR, textStatus, errorThrown) {
304
			error : function(jqXHR, textStatus, errorThrown) {
305
				if (DEBUG) {
305
				if (DEBUG) {
306
					$("#dialogue-erreur").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
306
					$("#dialogue-erreur").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
307
					reponse = jQuery.parseJSON(jqXHR.responseText);
307
					reponse = jQuery.parseJSON(jqXHR.responseText);
308
					var erreurMsg = "";
308
					var erreurMsg = "";
309
					if (reponse != null) {
309
					if (reponse != null) {
310
						$.each(reponse, function (cle, valeur) {
310
						$.each(reponse, function (cle, valeur) {
311
							erreurMsg += valeur + "<br />";
311
							erreurMsg += valeur + "<br />";
312
						});
312
						});
313
					}
313
					}
314
					
314
					
315
					$("#dialogue-erreur").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
315
					$("#dialogue-erreur").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
316
				}
316
				}
317
			},
317
			},
318
			complete : function(jqXHR, textStatus) {
318
			complete : function(jqXHR, textStatus) {
319
				if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
319
				if (DEBUG && jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
320
					var debugMsg = "";
320
					var debugMsg = "";
321
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
321
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
322
					if (debugInfos != null) {
322
					if (debugInfos != null) {
323
						$.each(debugInfos, function (cle, valeur) {
323
						$.each(debugInfos, function (cle, valeur) {
324
							debugMsg += valeur + "<br />";
324
							debugMsg += valeur + "<br />";
325
						});
325
						});
326
						$("#dialogue-erreur").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
326
						$("#dialogue-erreur").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
327
					}
327
					}
328
				}
328
				}
329
				if ($("#dialogue-erreur .msg").length > 0) {
329
				if ($("#dialogue-erreur .msg").length > 0) {
330
					$("#dialogue-erreur").dialog();
330
					$("#dialogue-erreur").dialog();
331
				}
331
				}
332
			}
332
			}
333
		});
333
		});
334
	});
334
	});
335
}
335
}
336
 
336
 
337
//+---------------------------------------------------------------------------------------------------------+
337
//+---------------------------------------------------------------------------------------------------------+
338
// FORMULAIRE
338
// FORMULAIRE
339
$(document).ready(function() {
339
$(document).ready(function() {
340
	$("#prenom").bind("change", function(event) {
340
	$("#prenom").bind("change", function(event) {
341
		var prenom = new Array();
341
		var prenom = new Array();
342
		var mots = $(this).val().split('-');
342
		var mots = $(this).val().split('-');
343
        for(var i = 0; i < mots.length; i++) {
343
        for(var i = 0; i < mots.length; i++) {
344
        	var mot = mots[i];
344
        	var mot = mots[i];
345
        	var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
345
        	var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
346
        	prenom.push(motMajuscule);
346
        	prenom.push(motMajuscule);
347
        }
347
        }
348
		$(this).val(prenom.join('-'));
348
		$(this).val(prenom.join('-'));
349
	});
349
	});
350
	$("#nom").bind("change", function(event) {
350
	$("#nom").bind("change", function(event) {
351
		$(this).val($(this).val().toUpperCase());
351
		$(this).val($(this).val().toUpperCase());
352
	});
352
	});
353
	
353
	
354
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
354
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
355
	$("#date").datepicker({
355
	$("#date").datepicker({
356
		dateFormat: "dd/mm/yy",  
356
		dateFormat: "dd/mm/yy",  
357
		showOn: "button",
357
		showOn: "button",
358
		buttonImageOnly: true,  
358
		buttonImageOnly: true,  
359
		buttonImage: CALENDRIER_ICONE_URL,
359
		buttonImage: CALENDRIER_ICONE_URL,
360
		buttonText: "Afficher le calendrier pour saisir la date.",
360
		buttonText: "Afficher le calendrier pour saisir la date.",
361
		showButtonPanel: true
361
		showButtonPanel: true
362
	});
362
	});
363
	$("img.ui-datepicker-trigger").appendTo("#date-icone");
363
	$("img.ui-datepicker-trigger").appendTo("#date-icone");
364
	
364
	
365
	ajouterAutocompletionNoms();
365
	ajouterAutocompletionNoms();
366
	
366
	
367
	$.validator.addMethod(
367
	$.validator.addMethod(
368
		"dateCel", 
368
		"dateCel", 
369
		function (value, element) { 
369
		function (value, element) { 
370
			return /^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value); 
370
			return /^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value); 
-
 
371
		}, 
371
		}, "Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
372
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
372
	$.extend($.validator.defaults, {
373
	$.extend($.validator.defaults, {
373
		errorClass: "control-group error",
374
		errorClass: "control-group error",
374
		validClass: "control-group success",
375
		validClass: "control-group success",
375
		errorElement: "span",
376
		errorElement: "span",
376
		highlight: function (element, errorClass, validClass) {
377
		highlight: function(element, errorClass, validClass) {
377
			if (element.type === 'radio') {
378
			if (element.type === 'radio') {
378
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
379
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
379
			} else { 
380
			} else { 
380
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
381
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
381
			}
382
			}
382
		},
383
		},
383
		unhighlight: function (element, errorClass, validClass) {
384
		unhighlight: function(element, errorClass, validClass) {
384
			if (element.type === 'radio') {
385
			if (element.type === 'radio') {
385
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
386
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
386
			} else {
387
			} else {
-
 
388
				if ($(element).attr('id') == 'taxon') {
-
 
389
					var warningClass = "control-group warning";
-
 
390
					if ($("#taxon").data("selection") != $("#taxon").val()) {
-
 
391
						$("#taxon").data("selection", "");
-
 
392
						$("#taxon").data("nn", "");
-
 
393
						if ($("#taxon").val() != '') {
-
 
394
							$("#taxon-input-groupe").removeClass(validClass)
-
 
395
								.removeClass(errorClass)
-
 
396
								.addClass(warningClass);
-
 
397
							this.showLabel(element, "Nom abscent du référentiel.");
-
 
398
						}
-
 
399
					} else {
-
 
400
						if ($("#taxon").val() != '') {
-
 
401
							$("#taxon-input-groupe").removeClass(warningClass)
-
 
402
								.removeClass(errorClass)
-
 
403
								.addClass(validClass);
-
 
404
							$(element).next(" span.help-inline").remove();
-
 
405
						}
-
 
406
					}
-
 
407
				} else {
387
				$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
408
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
388
				$(element).next('span.help-inline').text('');
409
					$(element).next(" span.help-inline").remove();
-
 
410
				}
389
			}
411
			}
390
		}
412
		}
391
	});
413
	});
392
	$("#form-observateur").validate({
414
	$("#form-observateur").validate({
393
		rules: {
415
		rules: {
394
			courriel : {
416
			courriel : {
395
				required : true,
417
				required : true,
396
				email : true},
418
				email : true},
397
			courriel_confirmation : {
419
			courriel_confirmation : {
398
				required : true,
420
				required : true,
399
				equalTo: "#courriel"}
421
				equalTo: "#courriel"}
400
		}
422
		}
401
	});
423
	});
402
	$("#form-station").validate({
424
	$("#form-station").validate({
403
		rules: {
425
		rules: {
404
			latitude : {
426
			latitude : {
405
				required: true,
427
				required: true,
406
				range: [-90, 90]},
428
				range: [-90, 90]},
407
			longitude : {
429
			longitude : {
408
				required: true,
430
				required: true,
409
				range: [-180, 180]}
431
				range: [-180, 180]}
410
		}
432
		}
411
	});
433
	});
412
	$("#form-obs").validate({
434
	$("#form-obs").validate({
413
		rules: {
435
		rules: {
414
			date : {
-
 
415
				dateCel: true},
436
			date : "dateCel",
416
			taxon : "required"
437
			taxon : "required"
417
		}
438
		}
418
	});
439
	});
419
	
440
	
420
	$("#courriel_confirmation").bind('paste', function(e) {
441
	$("#courriel_confirmation").bind('paste', function(e) {
421
		$("#dialogue-bloquer-copier-coller").dialog();
442
		$("#dialogue-bloquer-copier-coller").dialog();
422
		return false;
443
		return false;
423
	});
444
	});
424
		
445
		
425
	//bascule le texte d'afficher à masquer
446
	//bascule le texte d'afficher à masquer
426
	$("a.afficher-coord").click(function() {
447
	$("a.afficher-coord").click(function() {
427
		$("a.afficher-coord").toggle();
448
		$("a.afficher-coord").toggle();
428
		$("#coordonnees-geo").toggle('slow');
449
		$("#coordonnees-geo").toggle('slow');
429
		//valeur false pour que le lien ne soit pas suivi
450
		//valeur false pour que le lien ne soit pas suivi
430
		return false;
451
		return false;
431
	});
452
	});
432
	
453
	
433
	var obsNumero = 0;
454
	var obsNumero = 0;
434
	$("#ajouter-obs").bind('click', function(e) {
455
	$("#ajouter-obs").bind('click', function(e) {
435
		if (validerFormulaire() == true) {
456
		if (validerFormulaire() == true) {
436
			//rassemble les obs dans un tableau html
457
			//rassemble les obs dans un tableau html
437
			obsNumero = obsNumero + 1;
458
			obsNumero = obsNumero + 1;
438
			$("#liste-obs tbody").append(
459
			$("#liste-obs tbody").append(
439
					'<tr id="obs'+obsNumero+'" class="obs">'+
460
					'<tr id="obs'+obsNumero+'" class="obs">'+
440
					'<td>'+obsNumero+'</td>'+
461
					'<td>'+obsNumero+'</td>'+
441
					'<td>'+$("#date").val()+'</td>'+
462
					'<td>'+$("#date").val()+'</td>'+
442
					'<td>'+$("#taxon").val()+'</td>'+
463
					'<td>'+$("#taxon").val()+'</td>'+
443
					'<td>'+$("#latitude").val()+' / '+$("#longitude").val()+'</td>'+
464
					'<td>'+$("#latitude").val()+' / '+$("#longitude").val()+'</td>'+
444
					'<td>'+$('#commune-nom').text()+' ('+$('#commune-code-insee').text()+')</td>'+
465
					'<td>'+$('#commune-nom').text()+' ('+$('#commune-code-insee').text()+')</td>'+
445
					'<td>'+$('#lieudit').val()+'</td>'+
466
					'<td>'+$('#lieudit').val()+'</td>'+
446
					'<td>'+$('#station').val()+'</td>'+
467
					'<td>'+$('#station').val()+'</td>'+
447
					'<td>'+$('#milieu').val()+'</td>'+
468
					'<td>'+$('#milieu').val()+'</td>'+
448
					'<td class="obs-miniature">'+ajouterImgMiniatureAuTransfert()+'</td>'+
469
					'<td class="obs-miniature">'+ajouterImgMiniatureAuTransfert()+'</td>'+
449
					'<td>'+$("#notes").val()+'</td>'+
470
					'<td>'+$("#notes").val()+'</td>'+
450
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
471
					'<td><button class="supprimer-obs" value="'+obsNumero+'" title="Supprimer l\'observation '+obsNumero+'">'+
451
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
472
					'<img src="'+SUPPRIMER_ICONE_URL+'"/></button></td>'+
452
				'</tr>');
473
				'</tr>');
453
			//rassemble les obs dans #liste-obs
474
			//rassemble les obs dans #liste-obs
454
			var numNomSel = $("#taxon").val();
475
			var numNomSel = $("#taxon").val();
455
			$("#liste-obs").data('obsId'+obsNumero, {
476
			$("#liste-obs").data('obsId'+obsNumero, {
456
				'date' : $("#date").val(), 
477
				'date' : $("#date").val(), 
457
				'num_nom_sel' : numNomSel,
478
				'num_nom_sel' : numNomSel,
458
				'nom_sel' : taxons[numNomSel]['nom_sel'],
479
				'nom_sel' : taxons[numNomSel]['nom_sel'],
459
				'nom_ret' : taxons[numNomSel]['nom_ret'],
480
				'nom_ret' : taxons[numNomSel]['nom_ret'],
460
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
481
				'num_nom_ret' : taxons[numNomSel]['num_nom_ret'],
461
				'num_taxon' : taxons[numNomSel]['num_taxon'],
482
				'num_taxon' : taxons[numNomSel]['num_taxon'],
462
				'famille' : taxons[numNomSel]['famille'],
483
				'famille' : taxons[numNomSel]['famille'],
463
				'nom_fr' : taxons[numNomSel]['nom_fr'],
484
				'nom_fr' : taxons[numNomSel]['nom_fr'],
464
				'milieu' : $('input[name=milieu]:checked').val(),
485
				'milieu' : $('input[name=milieu]:checked').val(),
465
				'latitude' : $("#latitude").val(),
486
				'latitude' : $("#latitude").val(),
466
				'longitude' : $("#longitude").val(),
487
				'longitude' : $("#longitude").val(),
467
				'commune_nom' : $("#commune-nom").text(),
488
				'commune_nom' : $("#commune-nom").text(),
468
				'commune_code_insee' : $("#commune-code-insee").text(),
489
				'commune_code_insee' : $("#commune-code-insee").text(),
469
				'lieu_dit' : $("#rue").val(),
490
				'lieu_dit' : $("#rue").val(),
470
				'station' : $("#rue_num_debut").val()+'-'+$("#rue_num_fin").val()+'-'+$("#rue_cote").val(),
491
				'station' : $("#rue_num_debut").val()+'-'+$("#rue_num_fin").val()+'-'+$("#rue_cote").val(),
471
				'notes' : $("#notes").val(),
492
				'notes' : $("#notes").val(),
472
				//Ajout des champs images
493
				//Ajout des champs images
473
				'image_nom' : $("#miniature-img").attr('alt'),
494
				'image_nom' : $("#miniature-img").attr('alt'),
474
				'image_b64' : getB64ImgOriginal()
495
				'image_b64' : getB64ImgOriginal()
475
			});
496
			});
476
		}
497
		}
477
	});
498
	});
478
	
499
	
479
	$(".supprimer-obs").live('click', supprimerObs);
500
	$(".supprimer-obs").live('click', supprimerObs);
480
	
501
	
481
	$("#transmettre-obs").click(function(e) {
502
	$("#transmettre-obs").click(function(e) {
482
		var observations = $("#liste-obs").data();
503
		var observations = $("#liste-obs").data();
483
		
504
		
484
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
505
		if (observations == undefined || jQuery.isEmptyObject(observations)) {
485
			$("#dialogue-zero-obs").dialog();
506
			$("#dialogue-zero-obs").dialog();
486
		} else if ($("#saisie-obs").valid() == false) {
507
		} else if ($("#saisie-obs").valid() == false) {
487
			$("#dialogue-form-invalide").dialog();
508
			$("#dialogue-form-invalide").dialog();
488
		} else {
509
		} else {
489
			observations['projet'] = 'Sauvages';
510
			observations['projet'] = 'Sauvages';
490
			
511
			
491
			var utilisateur = new Object();
512
			var utilisateur = new Object();
492
			utilisateur.prenom = $("#prenom").val();
513
			utilisateur.prenom = $("#prenom").val();
493
			utilisateur.nom = $("#nom").val();
514
			utilisateur.nom = $("#nom").val();
494
			utilisateur.courriel = $("#courriel").val();
515
			utilisateur.courriel = $("#courriel").val();
495
			observations['utilisateur'] = utilisateur;
516
			observations['utilisateur'] = utilisateur;
496
			
517
			
497
			var erreurMsg = "";
518
			var erreurMsg = "";
498
			$.ajax({
519
			$.ajax({
499
				url : SERVICE_SAISIE_URL,
520
				url : SERVICE_SAISIE_URL,
500
				type : "POST",
521
				type : "POST",
501
				data : observations,
522
				data : observations,
502
				dataType : "json",
523
				dataType : "json",
503
				beforeSend : function() {
524
				beforeSend : function() {
504
					$(".msg").remove();	
525
					$(".msg").remove();	
505
					$(".msg-erreur").remove();
526
					$(".msg-erreur").remove();
506
					$(".msg-debug").remove();
527
					$(".msg-debug").remove();
507
					$("#chargement").show();
528
					$("#chargement").show();
508
				},
529
				},
509
				success : function(data, textStatus, jqXHR) {
530
				success : function(data, textStatus, jqXHR) {
510
					$("#dialogue-obs-transaction").append('<p class="msg">Vos observations ont bien été transmises.</p>');
531
					$("#dialogue-obs-transaction").append('<p class="msg">Vos observations ont bien été transmises.</p>');
511
					supprimerMiniature();
532
					supprimerMiniature();
512
				},
533
				},
513
				statusCode : {
534
				statusCode : {
514
					500 : function(jqXHR, textStatus, errorThrown) {
535
					500 : function(jqXHR, textStatus, errorThrown) {
515
						$("#chargement").hide();
536
						$("#chargement").hide();
516
						erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
537
						erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
517
						if (DEBUG) {
538
						if (DEBUG) {
518
							$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
539
							$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
519
						}
540
						}
520
				    }
541
				    }
521
				},
542
				},
522
				error : function(jqXHR, textStatus, errorThrown) {
543
				error : function(jqXHR, textStatus, errorThrown) {
523
					erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
544
					erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
524
					try {
545
					try {
525
						reponse = jQuery.parseJSON(jqXHR.responseText);
546
						reponse = jQuery.parseJSON(jqXHR.responseText);
526
						if (reponse != null) {
547
						if (reponse != null) {
527
							$.each(reponse, function (cle, valeur) {
548
							$.each(reponse, function (cle, valeur) {
528
								erreurMsg += valeur + "\n";
549
								erreurMsg += valeur + "\n";
529
							});
550
							});
530
						}
551
						}
531
					} catch(e) {
552
					} catch(e) {
532
						erreurMsg += "L'erreur n'était pas en JSON.";
553
						erreurMsg += "L'erreur n'était pas en JSON.";
533
					}
554
					}
534
					
555
					
535
					if (DEBUG) {
556
					if (DEBUG) {
536
						$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
557
						$("#dialogue-obs-transaction").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
537
					}
558
					}
538
				},
559
				},
539
				complete : function(jqXHR, textStatus) {
560
				complete : function(jqXHR, textStatus) {
540
					$("#chargement").hide();
561
					$("#chargement").hide();
541
					var debugMsg = '';
562
					var debugMsg = '';
542
					if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
563
					if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
543
						debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
564
						debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
544
						if (debugInfos != null) {
565
						if (debugInfos != null) {
545
							$.each(debugInfos, function (cle, valeur) {
566
							$.each(debugInfos, function (cle, valeur) {
546
								debugMsg += valeur + "\n";
567
								debugMsg += valeur + "\n";
547
							});
568
							});
548
						}
569
						}
549
					}
570
					}
550
					if (erreurMsg != '') {
571
					if (erreurMsg != '') {
551
						$("#dialogue-obs-transaction").append('<p class="msg">'+
572
						$("#dialogue-obs-transaction").append('<p class="msg">'+
552
								'Une erreur est survenue lors de la transmission de vos observations.'+'<br />'+
573
								'Une erreur est survenue lors de la transmission de vos observations.'+'<br />'+
553
								'Vous pouvez signaler le disfonctionnement à <a href="'+
574
								'Vous pouvez signaler le disfonctionnement à <a href="'+
554
								'mailto:cel@tela-botanica.org'+'?'+
575
								'mailto:cel@tela-botanica.org'+'?'+
555
								'subject=Disfonctionnement du widget de saisie Biodiversite34'+
576
								'subject=Disfonctionnement du widget de saisie Biodiversite34'+
556
								"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
577
								"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
557
								'">cel@tela-botanica.org</a>.'+
578
								'">cel@tela-botanica.org</a>.'+
558
								'</p>');
579
								'</p>');
559
					}
580
					}
560
					if (DEBUG) {
581
					if (DEBUG) {
561
						$("#dialogue-obs-transaction").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
582
						$("#dialogue-obs-transaction").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
562
					}
583
					}
563
					
584
					
564
					$("#dialogue-obs-transaction").dialog();
585
					$("#dialogue-obs-transaction").dialog();
565
					$("#liste-obs").removeData();
586
					$("#liste-obs").removeData();
566
					$('.obs').remove();
587
					$('.obs').remove();
567
					obsNumero = 0;
588
					obsNumero = 0;
568
				}
589
				}
569
			});
590
			});
570
		}
591
		}
571
		return false;
592
		return false;
572
	});
593
	});
573
});
594
});
574
 
595
 
575
function validerFormulaire() {
596
function validerFormulaire() {
576
	$observateur = $("#form-observateur").valid();
597
	$observateur = $("#form-observateur").valid();
577
	$station = $("#form-station").valid();
598
	$station = $("#form-station").valid();
578
	$obs = $("#form-obs").valid();
599
	$obs = $("#form-obs").valid();
579
	return ($observateur == true && $station == true && $obs == true) ? true : false;
600
	return ($observateur == true && $station == true && $obs == true) ? true : false;
580
}
601
}
581
 
602
 
582
function getB64ImgOriginal() {
603
function getB64ImgOriginal() {
583
	var b64 = '';
604
	var b64 = '';
584
	if ($("#miniature-img").hasClass('b64')) {
605
	if ($("#miniature-img").hasClass('b64')) {
585
		b64 = $("#miniature-img").attr('src');
606
		b64 = $("#miniature-img").attr('src');
586
	} else if ($("#miniature-img").hasClass('b64-canvas')) {
607
	} else if ($("#miniature-img").hasClass('b64-canvas')) {
587
		b64 = $("#miniature-img").data('b64');
608
		b64 = $("#miniature-img").data('b64');
588
	}
609
	}
589
	return b64;
610
	return b64;
590
}
611
}
591
 
612
 
592
function supprimerObs() {
613
function supprimerObs() {
593
	var obsId = $(this).val();
614
	var obsId = $(this).val();
594
	// Problème avec IE 6 et 7
615
	// Problème avec IE 6 et 7
595
	if (obsId == "Supprimer") {
616
	if (obsId == "Supprimer") {
596
		obsId = $(this).attr("title");
617
		obsId = $(this).attr("title");
597
	}
618
	}
598
	
619
	
599
	$('#obs'+obsId).remove();
620
	$('#obs'+obsId).remove();
600
	$("#liste-obs").removeData('obsId'+obsId);
621
	$("#liste-obs").removeData('obsId'+obsId);
601
}
622
}
602
 
623
 
603
function ajouterImgMiniatureAuTransfert() {
624
function ajouterImgMiniatureAuTransfert() {
604
	var miniature = '';
625
	var miniature = '';
605
	if ($("#miniature img").length == 1) {
626
	if ($("#miniature img").length == 1) {
606
		var css = $("#miniature-img").hasClass('b64') ? 'miniature b64' : 'miniature';
627
		var css = $("#miniature-img").hasClass('b64') ? 'miniature b64' : 'miniature';
607
		var src = $("#miniature-img").attr("src");
628
		var src = $("#miniature-img").attr("src");
608
		var alt = $("#miniature-img").attr("alt");
629
		var alt = $("#miniature-img").attr("alt");
609
		miniature = '<img class="'+css+'" alt="'+alt+'"src="'+src+'" />';
630
		miniature = '<img class="'+css+'" alt="'+alt+'"src="'+src+'" />';
610
	}
631
	}
611
	return miniature;
632
	return miniature;
612
}
633
}
613
 
634
 
614
//+---------------------------------------------------------------------------------------------------------+
635
//+---------------------------------------------------------------------------------------------------------+
615
// AUTO-COMPLÉTION Noms Scientifiques
636
// AUTO-COMPLÉTION Noms Scientifiques
616
var listeNomsScientifiques = new Object();
637
var listeNomsScientifiques = new Object();
617
 
638
 
618
function ajouterAutocompletionNoms() {
639
function ajouterAutocompletionNoms() {
619
	$('#taxon').autocomplete({
640
	$('#taxon').autocomplete({
620
		source: function(requete, add){  
641
		source: function(requete, add){  
621
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
642
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
622
			requete = "";
643
			requete = "";
623
			$.getJSON(getUrlAutocompletionNomsSci($('#taxon').val()), requete, function(data) {  
644
			$.getJSON(getUrlAutocompletionNomsSci($('#taxon').val()), requete, function(data) {  
624
				var suggestions = traiterRetourNomsSci(data);
645
				var suggestions = traiterRetourNomsSci(data);
625
				add(suggestions);  
646
				add(suggestions);  
626
            });
647
            });
627
        },
648
        },
628
        html: true
649
        html: true
629
	});
650
	});
-
 
651
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
-
 
652
		$("#taxon").data("selection", ui.item.value);
-
 
653
		$("#taxon").data("nn", ui.item.nn);
-
 
654
	});
630
}
655
}
631
 
656
 
632
function getUrlAutocompletionNomsSci(mots) {
657
function getUrlAutocompletionNomsSci(mots) {
633
	var url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL.replace('{masque}', mots);
658
	var url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL.replace('{masque}', mots);
634
	return url;
659
	return url;
635
}
660
}
636
 
661
 
637
function traiterRetourNomsSci(data) {
662
function traiterRetourNomsSci(data) {
638
	var suggestions = [];  
663
	var suggestions = [];  
639
	if (data.resultat != undefined) {
664
	if (data.resultat != undefined) {
640
		$.each(data.resultat, function(i, val) {
665
		$.each(data.resultat, function(i, val) {
641
			val.nn = i;
666
			val.nn = i;
-
 
667
			var nom = {};
-
 
668
			if (suggestions.length >= 20) {
-
 
669
				nom.label = "...";
-
 
670
				nom.value = $('#taxon').val();
-
 
671
				nom.nn = "";
-
 
672
				suggestions.push(nom);
-
 
673
				return false;
-
 
674
			} else {
-
 
675
				nom.label = val.nom_sci;
-
 
676
				nom.value = val.nom_sci;
-
 
677
				nom.nn = val.nn;
642
			listeNomsScientifiques[val.nom_sci] = val;
678
				listeNomsScientifiques[val.nom_sci] = val;
643
			suggestions.push(val.nom_sci);
679
				suggestions.push(nom);
-
 
680
			}			
644
		});
681
		});
645
	}
682
	}
646
	
683
		
647
	if (suggestions.length >= 50) {
-
 
648
		suggestions.push("...");
-
 
649
	}	
-
 
650
	return suggestions;
684
	return suggestions;
651
}
685
}
652
 
686
 
653
/*
687
/*
654
 * jQuery UI Autocomplete HTML Extension
688
 * jQuery UI Autocomplete HTML Extension
655
 *
689
 *
656
 * Copyright 2010, Scott González (http://scottgonzalez.com)
690
 * Copyright 2010, Scott González (http://scottgonzalez.com)
657
 * Dual licensed under the MIT or GPL Version 2 licenses.
691
 * Dual licensed under the MIT or GPL Version 2 licenses.
658
 *
692
 *
659
 * http://github.com/scottgonzalez/jquery-ui-extensions
693
 * http://github.com/scottgonzalez/jquery-ui-extensions
660
 * 
694
 * 
661
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
695
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
662
 */
696
 */
663
(function( $ ) {
697
(function( $ ) {
664
 
698
 
665
var proto = $.ui.autocomplete.prototype,
699
var proto = $.ui.autocomplete.prototype,
666
	initSource = proto._initSource;
700
	initSource = proto._initSource;
667
 
701
 
668
function filter( array, term ) {
702
function filter( array, term ) {
669
	var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
703
	var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
670
	return $.grep( array, function(value) {
704
	return $.grep( array, function(value) {
671
		return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
705
		return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
672
	});
706
	});
673
}
707
}
674
 
708
 
675
$.extend( proto, {
709
$.extend( proto, {
676
	_initSource: function() {
710
	_initSource: function() {
677
		if ( this.options.html && $.isArray(this.options.source) ) {
711
		if ( this.options.html && $.isArray(this.options.source) ) {
678
			this.source = function( request, response ) {
712
			this.source = function( request, response ) {
679
				response( filter( this.options.source, request.term ) );
713
				response( filter( this.options.source, request.term ) );
680
			};
714
			};
681
		} else {
715
		} else {
682
			initSource.call( this );
716
			initSource.call( this );
683
		}
717
		}
684
	},
718
	},
685
	_renderItem: function( ul, item) {
719
	_renderItem: function( ul, item) {
686
		if(listeNomsScientifiques[item.label] != undefined && listeNomsScientifiques[item.label].retenu == "true") {
720
		if (listeNomsScientifiques[item.label] != undefined && listeNomsScientifiques[item.label].retenu == "true") {
687
			item.label = "<b>"+item.label+"</b>";
721
			item.label = "<b>"+item.label+"</b>";
688
		}
722
		}
689
		
723
		
690
		if(item.label == '...') {
724
		if (item.label == '...') {
691
			item.label = "<b>"+item.label+"</b>";
725
			item.label = "<b>"+item.label+"</b>";
692
		}
726
		}
693
		
727
		
694
		return $( "<li></li>" )
728
		return $( "<li></li>" )
695
			.data( "item.autocomplete", item )
729
			.data( "item.autocomplete", item )
696
			.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
730
			.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
697
			.appendTo( ul );
731
			.appendTo( ul );
698
	}
732
	}
699
});
733
});
700
 
734
 
701
})( jQuery );
735
})( jQuery );