Subversion Repositories eFlore/Applications.cel

Rev

Rev 1213 | Go to most recent revision | Details | Last modification | View Log | RSS feed

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