Subversion Repositories eFlore/Applications.cel

Rev

Rev 1037 | Rev 1041 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
836 jpm 1
/*+--------------------------------------------------------------------------------------------------------+*/
2
// PARAMÊTRES et CONSTANTES
941 jpm 3
// Mettre à true pour afficher les messages de débogage
950 jpm 4
var DEBUG = false;
980 jpm 5
var communeImageUrl = 'http://www.tela-botanica.org/commun/icones/carto/commune.png';
6
var pointImageUrl = 'http://www.tela-botanica.org/commun/icones/carto/point2.png';
1039 aurelien 7
var groupeImageUrlTpl = 'http://www.tela-botanica.org/service:cel:CelWidgetMap/icone-groupe?type={type}&nbre={nbre}'
836 jpm 8
var pointsOrigine = null;
9
var boundsOrigine = null;
10
var markerClusterer = null;
11
var map = null;
12
var infoBulle = new google.maps.InfoWindow();
980 jpm 13
var stations = null;
836 jpm 14
var pointClique = null;
980 jpm 15
var carteCentre = new google.maps.LatLng(25, 10);
836 jpm 16
var carteOptions = {
980 jpm 17
	zoom: 3,
18
	center:carteCentre,
836 jpm 19
	mapTypeId: google.maps.MapTypeId.ROADMAP,
20
	mapTypeControlOptions: {
21
		mapTypeIds: ['OSM',
22
		             google.maps.MapTypeId.ROADMAP,
23
		             google.maps.MapTypeId.HYBRID,
24
		             google.maps.MapTypeId.SATELLITE,
25
		             google.maps.MapTypeId.TERRAIN]
26
	}
27
};
28
var osmMapType = new google.maps.ImageMapType({
29
	getTileUrl: function(coord, zoom) {
30
		return "http://tile.openstreetmap.org/" +
31
		zoom + "/" + coord.x + "/" + coord.y + ".png";
32
	},
33
	tileSize: new google.maps.Size(256, 256),
34
	isPng: true,
35
	alt: "OpenStreetMap",
36
	name: "OSM",
37
	maxZoom: 19
38
});
980 jpm 39
var ctaLayer = null;
915 jpm 40
var pagineur = {'limite':50, 'start':0, 'total':0, 'stationId':null, 'format':'tableau'};
41
var station = {'commune':'', 'obsNbre':0};
42
var obsStation = new Array();
43
var obsPage = new Array();
939 jpm 44
var taxonsCarte = new Array();
980 jpm 45
var mgr = null;
46
var marqueursCache = new Array();
47
var zonesCache = new Array();
1035 aurelien 48
var requeteChargementPoints;
836 jpm 49
/*+--------------------------------------------------------------------------------------------------------+*/
50
// INITIALISATION DU CODE
51
 
52
//Déclenchement d'actions quand JQuery et le document HTML sont OK
53
$(document).ready(function() {
54
	initialiserWidget();
55
});
56
 
57
function initialiserWidget() {
980 jpm 58
	definirTailleTitre();
836 jpm 59
	initialiserAffichageCarte();
60
	initialiserAffichagePanneauLateral();
61
	initialiserCarte();
980 jpm 62
	initialiserGestionnaireMarqueurs()
836 jpm 63
	initialiserInfoBulle();
941 jpm 64
	initialiserFormulaireContact();
836 jpm 65
	chargerLimitesCommunales();
1032 aurelien 66
	attribuerListenerCarte();
67
	programmerRafraichissementCarte();
836 jpm 68
}
69
 
915 jpm 70
/*+--------------------------------------------------------------------------------------------------------+*/
71
// AFFICHAGE GÉNÉRAL
72
 
980 jpm 73
function afficherTitreCarte() {
74
	if (stations != null && taxonsCarte.length > 0) {
1039 aurelien 75
		var obsNbre = stations.stats.observations;
76
		var obsNbreFormate = stations.stats.observations.formaterNombre();
77
		var plteNbre = taxonsCarte.length;
78
		var plteNbreFormate = taxonsCarte.length.formaterNombre();
79
		var communeNbre = stations.stats.communes;
80
		var communeNbreFormate = stations.stats.communes.formaterNombre();
980 jpm 81
 
1039 aurelien 82
		var titre = obsNbreFormate+' observation';
980 jpm 83
		titre += (obsNbre > 1) ? 's' : '' ;
84
 
85
		if (nt == '*') {
1039 aurelien 86
			titre += ' de '+plteNbreFormate+' plante';
980 jpm 87
			titre += (plteNbre > 1) ? 's' : '' ;
88
		} else {
89
			if (taxonsCarte[0]) {
90
				var taxon = taxonsCarte[0];
91
				titre += ' pour '+taxon.nom;
92
			}
93
		}
94
 
1039 aurelien 95
		titre += ' sur '+communeNbreFormate+' commune';
980 jpm 96
		titre += (communeNbre > 1) ? 's' : '' ;
97
 
98
		$('#carte-titre-infos').text(titre);
99
	}
836 jpm 100
}
101
 
980 jpm 102
function definirTailleTitre() {
103
	var largeurViewPort = $(window).width();
104
	var taille = null;
105
	if (largeurViewPort < 400) {
106
		taille = '0.8';
107
	} else if (largeurViewPort >= 400 && largeurViewPort < 800) {
108
		taille = '1.0';
109
	} else if (largeurViewPort >= 800) {
110
		taille = '1.6';
111
	}
112
	$("#carte-titre").css('font-size', taille+'em');
113
}
114
 
915 jpm 115
/*+--------------------------------------------------------------------------------------------------------+*/
116
// CARTE
117
 
836 jpm 118
function initialiserAffichageCarte() {
119
	$('#carte').height($(window).height() - 35);
120
	$('#carte').width($(window).width() - 24);
980 jpm 121
 
836 jpm 122
	if (nt != '*') {
123
		$('#carte').css('left', 0);
124
	}
125
}
126
 
127
function initialiserCarte() {
128
	map = new google.maps.Map(document.getElementById('carte'), carteOptions);
129
	// Ajout de la couche OSM à la carte
130
	map.mapTypes.set('OSM', osmMapType);
131
}
132
 
980 jpm 133
function initialiserGestionnaireMarqueurs() {
134
	mgr = new MarkerManager(map);
135
}
836 jpm 136
 
137
function chargerLimitesCommunales() {
138
	if (urlsLimitesCommunales != null) {
139
		for (urlId in urlsLimitesCommunales) {
140
			var url = urlsLimitesCommunales[urlId];
1039 aurelien 141
			ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: false});
836 jpm 142
			ctaLayer.setMap(map);
143
		}
144
	}
145
}
1039 aurelien 146
 
980 jpm 147
var listener = null;
148
var timer = null;
1032 aurelien 149
function attribuerListenerCarte() {
980 jpm 150
	listener = google.maps.event.addListener(map, 'bounds_changed', function(){
1032 aurelien 151
		programmerRafraichissementCarte();
980 jpm 152
	});
1032 aurelien 153
	listener = google.maps.event.addListener(map, 'zoom_changed', function(){
154
		programmerRafraichissementCarte();
155
	});
980 jpm 156
}
1032 aurelien 157
function programmerRafraichissementCarte() {
158
	if(timer != null) {
159
        window.clearTimeout(timer);
1035 aurelien 160
    }
161
	if(requeteChargementPoints != null) {
162
		requeteChargementPoints.abort();
163
	}
1032 aurelien 164
	timer = window.setTimeout(function() {
165
		var zoom = map.getZoom();
1039 aurelien 166
		var NELatLng = (map.getBounds().getNorthEast().lat())+'|'+(map.getBounds().getNorthEast().lng());
167
		var SWLatLng = (map.getBounds().getSouthWest().lat())+'|'+(map.getBounds().getSouthWest().lng());
1032 aurelien 168
		chargerMarqueurs(zoom, NELatLng, SWLatLng);
169
    }, 400);
170
}
836 jpm 171
 
980 jpm 172
var marqueurs = new Array();
173
function chargerMarqueurs(zoom, NELatLng, SWLatLng) {
174
	var url = stationsUrl+
175
		'&zoom='+zoom+
176
		'&ne='+NELatLng+
177
		'&sw='+SWLatLng;
178
 
1032 aurelien 179
	if(infoBulleOuverte) {
180
		return;
181
	}
182
 
1035 aurelien 183
	if(requeteChargementPoints != null) {
184
		requeteChargementPoints.abort();
1037 aurelien 185
		cacherMessageChargementPoints();
1035 aurelien 186
	}
187
 
188
	afficherMessageChargementPoints();
189
	requeteChargementPoints = $.getJSON(url, function(data) {
190
		rafraichirMarqueurs(data);
191
		cacherMessageChargementPoints();
980 jpm 192
	});
193
}
194
 
1035 aurelien 195
function afficherMessageChargementPoints() {
196
	$('#zone-chargement-point').css('display','block');
197
}
198
 
199
function cacherMessageChargementPoints() {
200
	$('#zone-chargement-point').css('display','none');
201
}
202
 
203
function rafraichirMarqueurs(data) {
204
	$.each(marqueurs, function(index, marqueur) {
205
		marqueur.setMap(null);
206
	});
207
	marqueurs = new Array();
208
 
209
	stations = data;
210
	afficherTitreCarte();
211
 
212
	$.each(stations.points, function (index, station) {
213
		if(station != null) {
1039 aurelien 214
			var nouveauMarqueur = creerMarqueur(station);
215
			marqueurs.push(nouveauMarqueur);
1035 aurelien 216
		}
217
	});
218
}
219
 
980 jpm 220
function creerMarqueur(station) {
1037 aurelien 221
	var titre = '';
222
	if(station.nbreMarqueur) {
223
		titre = station.nbreMarqueur+' points renseignés';
224
	} else {
225
		if(station.nom) {
226
			titre = station.nom;
227
		}
228
	}
229
	//var titre = station['nbreMarqueur'];
980 jpm 230
	var icone = attribuerImageMarqueur(station['id'], station['nbreMarqueur']);
231
	var latLng = new google.maps.LatLng(station['lat'], station['lng']);
232
	var marqueur = new google.maps.Marker({
233
		position: latLng,
234
		icon: icone,
235
		title: ''+titre,
236
		map: map,
237
		stationInfos: station
238
	});
239
	attribuerListenerClick(marqueur, station['id']);
240
	marqueur.setMap(map);
241
    return marqueur;
242
}
243
 
1039 aurelien 244
function rendrePointsVisibles(bounds) {
245
	map.setCenter(bounds.getCenter());
246
	map.fitBounds(bounds);
247
	map.panToBounds(bounds);
248
}
249
 
1032 aurelien 250
function programmerRafraichissementCarteSauv() {
980 jpm 251
 
836 jpm 252
	var points = [];
253
	var bounds = new google.maps.LatLngBounds();
980 jpm 254
	for (var i = 0; i < stations.points.length; ++i) {
255
		var point = stations.points[i];
256
		var maLatLng = new google.maps.LatLng(point.lat, point.lng);
257
		var stationImage = attribuerImageMarqueur(point.id);
836 jpm 258
		var point = new google.maps.Marker({
259
			position: maLatLng,
260
			map: map,
980 jpm 261
			icon: stationImage,
262
			stationInfos: point
836 jpm 263
		});
264
		bounds.extend(maLatLng);
980 jpm 265
		google.maps.event.addListener(point, 'click', surClickMarqueur);
836 jpm 266
		points.push(point);
267
	}
268
 
269
	if (pointsOrigine == null && boundsOrigine == null) {
270
		pointsOrigine = points;
271
		boundsOrigine = bounds;
272
	}
273
 
274
	executerMarkerClusterer(points, bounds);
275
}
276
 
980 jpm 277
function attribuerImageMarqueur(id, nbreMarqueur) {
278
	var marqueurImage = null;
279
	if (etreMarqueurCommune(id)) {
280
		marqueurImage = new google.maps.MarkerImage(communeImageUrl, new google.maps.Size(24, 32));
281
	} else if (etreMarqueurStation(id)) {
282
		marqueurImage = new google.maps.MarkerImage(pointImageUrl, new google.maps.Size(16, 16));
283
	} else if (etreMarqueurGroupe(id)) {
284
		var type = 0;
285
		var largeur = 0;
286
		var hauteur = 0;
287
		if (nbreMarqueur != null) {
288
			if (nbreMarqueur >= 2 && nbreMarqueur < 100 ) {
289
				type = '1';
290
				largeur = 53;
291
				hauteur = 52;
292
			} else if (nbreMarqueur >= 100 && nbreMarqueur < 1000 ) {
293
				type = '2';
294
				largeur = 56;
295
				hauteur = 55;
296
			} else if (nbreMarqueur >= 1000 && nbreMarqueur < 10000 ) {
297
				type = '3';
298
				largeur = 66;
299
				hauteur = 65;
300
			} else if (nbreMarqueur >= 10000 && nbreMarqueur < 20000 ) {
301
				type = '4';
302
				largeur = 78;
303
				hauteur = 77;
304
			} else if (nbreMarqueur >= 20000) {
305
				type = '5';
306
				largeur = 66;
307
				hauteur = 65;
308
			}
309
		}
310
		groupeImageUrl = groupeImageUrlTpl.replace(/\{type\}/, type);
311
		groupeImageUrl = groupeImageUrl.replace(/\{nbre\}/, nbreMarqueur);
312
		marqueurImage = new google.maps.MarkerImage(groupeImageUrl, new google.maps.Size(largeur, hauteur));
313
	}
314
	return marqueurImage
315
}
316
 
317
function attribuerListenerClick(marqueur, id) {
318
	if (etreMarqueurCommune(id) || etreMarqueurStation(id)) {
319
		google.maps.event.addListener(marqueur, 'click', surClickMarqueur);
320
	} else if (etreMarqueurGroupe(id)) {
321
		google.maps.event.addListener(marqueur, 'click', surClickGroupe);
322
	}
323
}
324
 
1032 aurelien 325
function surClickMarqueur(event) {
1039 aurelien 326
 
327
	if(infoBulleOuverte) {
328
	    infoBulle.close();
329
	}
330
 
1035 aurelien 331
	pointClique = this;
980 jpm 332
	infoBulle.open(map, this);
333
	actualiserPagineur();
1035 aurelien 334
 
335
	var limites = map.getBounds();
336
	var centre = limites.getCenter();
337
	var nordEst = limites.getNorthEast();
338
	var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
339
	map.panTo(centreSudLatLng);
340
 
980 jpm 341
	afficherInfoBulle();
342
}
343
 
344
function surClickGroupe() {
345
	map.setCenter(this.getPosition());
346
	var nouveauZoom = map.getZoom() + 2;
347
	map.setZoom(nouveauZoom);
348
	mgr.clearMarkers();
349
}
350
 
351
function etreMarqueurGroupe(id) {
352
	var groupe = false;
353
	var motif = /^GROUPE/;
354
	if (motif.test(id)) {
355
		groupe = true;
356
	}
357
	return groupe;
358
}
359
 
360
function etreMarqueurCommune(id) {
361
	var commune = false;
362
	var motif = /^COMMUNE:/;
363
	if (motif.test(id)) {
364
		commune = true;
365
	}
366
	return commune;
367
}
368
 
369
function etreMarqueurStation(id) {
370
	var station = false;
371
	var motif = /^STATION:/;
372
	if (motif.test(id)) {
373
		station = true;
374
	}
375
	return station;
376
}
377
 
378
function deplacerCarteSurPointClique() {
915 jpm 379
	map.panTo(pointClique.position);
380
}
381
 
382
function executerMarkerClusterer(points, bounds) {
383
	if (markerClusterer) {
384
		markerClusterer.clearMarkers();
836 jpm 385
	}
980 jpm 386
	markerClusterer = new MarkerClusterer(map, points, {gridSize: 50, maxZoom: 18});
915 jpm 387
	map.fitBounds(bounds);
388
}
389
 
390
/*+--------------------------------------------------------------------------------------------------------+*/
391
// INFO BULLE
1032 aurelien 392
var infoBulleOuverte = false;
915 jpm 393
function initialiserInfoBulle() {
394
	google.maps.event.addListener(infoBulle, 'domready', initialiserContenuInfoBulle);
980 jpm 395
	google.maps.event.addListener(infoBulle, 'closeclick', surFermetureInfoBulle);
396
	google.maps.event.addListener(infoBulle, 'content_changed', definirLargeurInfoBulle);
915 jpm 397
}
398
 
980 jpm 399
function surFermetureInfoBulle() {
1032 aurelien 400
	infoBulleOuverte = false;
401
	programmerRafraichissementCarte();
980 jpm 402
}
403
 
404
function centrerInfoBulle() {
405
	var limites = map.getBounds();
406
	var centre = limites.getCenter();
407
	var nordEst = limites.getNorthEast();
408
	var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
409
	map.panTo(centreSudLatLng);
410
}
411
 
915 jpm 412
function afficherInfoBulle() {
413
	var obsHtml = $("#tpl-obs").html();
980 jpm 414
	var largeur = definirLargeurInfoBulle();
415
	obsHtml = obsHtml.replace(/\{largeur\}/, largeur);
915 jpm 416
	infoBulle.setContent(obsHtml);
1035 aurelien 417
	chargerObs(0, 0);
1032 aurelien 418
	infoBulleOuverte = true;
915 jpm 419
}
420
 
980 jpm 421
function definirLargeurInfoBulle() {
422
	var largeurViewPort = $(window).width();
423
	var lageurInfoBulle = null;
424
	if (largeurViewPort < 800) {
425
		largeurInfoBulle = 400;
426
	} else if (largeurViewPort >= 800 && largeurViewPort < 1200) {
427
		largeurInfoBulle = 500;
428
	} else if (largeurViewPort >= 1200) {
429
		largeurInfoBulle = 600;
430
	}
431
	return largeurInfoBulle;
432
}
433
 
915 jpm 434
function afficherMessageChargement(element) {
435
	if ($('#chargement').get() == '') {
436
		$('#tpl-chargement').tmpl().appendTo(element);
437
	}
438
}
439
 
1035 aurelien 440
function afficherMessageChargementTitreInfoBulle() {
441
	$("#obs-station-titre").text("Chargement des observations");
442
}
443
 
915 jpm 444
function supprimerMessageChargement() {
445
	$('#chargement').remove();
446
}
447
 
448
function chargerObs(depart, total) {
939 jpm 449
	if (depart == 0 || depart < total) {
915 jpm 450
		var limite = 300;
451
		if (depart == 0) {
1036 aurelien 452
			viderTableauObs();
915 jpm 453
		}
1035 aurelien 454
 
939 jpm 455
		var urlObs = observationsUrl+'&start={start}&limit='+limite;
980 jpm 456
		urlObs = urlObs.replace(/\{stationId\}/g, pointClique.stationInfos.id);
939 jpm 457
		urlObs = urlObs.replace(/\{nt\}/g, nt);
915 jpm 458
		urlObs = urlObs.replace(/\{start\}/g, depart);
459
 
460
		$.getJSON(urlObs, function(observations){
1036 aurelien 461
			surRetourChargementObs(observations, depart, total);
1035 aurelien 462
			chargerObs(depart+limite, observations.total);
915 jpm 463
		});
1036 aurelien 464
	}
465
}
466
 
467
function viderTableauObs() {
468
	obsStation = new Array();
469
	surClicPagePagination(0, null);
470
}
471
 
472
function surRetourChargementObs(observations, depart, total) {
473
	obsStation = obsStation.concat(observations.observations);
474
	if (depart == 0) {
475
		actualiserInfosStation(observations);
476
		creerTitreInfoBulle();
1035 aurelien 477
		selectionnerOnglet("#obs-vue-"+pagineur.format);
478
		surClicPagePagination(0, null);
915 jpm 479
	}
1036 aurelien 480
 
1039 aurelien 481
	afficherPagination();
1036 aurelien 482
	actualiserPagineur();
915 jpm 483
}
484
 
1035 aurelien 485
function actualiserInfosStation(infos) {
486
	pointClique.stationInfos.commune = infos.commune;
487
	pointClique.stationInfos.obsNbre = infos.total;
488
}
489
 
490
function creerTitreInfoBulle() {
491
	$("#obs-total").text(station.obsNbre);
492
	$("#obs-commune").text(station.commune);
493
	var titre = '';
494
	titre += pointClique.stationInfos.obsNbre+' observation';
495
	titre += (pointClique.stationInfos.obsNbre > 1) ? 's': '' ;
496
	titre += ' pour ';
497
	if (etreMarqueurCommune(pointClique.stationInfos.id)) {
498
		nomStation = 'la commune : ';
499
	} else {
500
		nomStation = 'la station : ';
501
	}
502
	titre += pointClique.stationInfos.nom;
503
	$("#obs-station-titre").text(titre);
504
}
505
 
939 jpm 506
function actualiserPagineur() {
980 jpm 507
	pagineur.stationId = pointClique.stationInfos.id;
1035 aurelien 508
	pagineur.total = pointClique.stationInfos.obsNbre;
939 jpm 509
	if (pagineur.total > 4) {
510
		pagineur.format = 'tableau';
511
	} else {
512
		pagineur.format = 'liste';
513
	}
514
}
515
 
915 jpm 516
function afficherPagination(observations) {
517
	$(".navigation").pagination(pagineur.total, {
518
		items_per_page:pagineur.limite,
519
		callback:surClicPagePagination,
520
		next_text:'Suivant',
521
		prev_text:'Précédent',
522
		prev_show_always:false,
523
		num_edge_entries:1,
953 jpm 524
		num_display_entries:4,
915 jpm 525
		load_first_page:true
526
	});
527
}
528
 
529
function surClicPagePagination(pageIndex, paginationConteneur) {
530
	var index = pageIndex * pagineur.limite;
531
	var indexMax = index + pagineur.limite;
532
	pagineur.depart = index;
533
	obsPage = new Array();
534
    for(index; index < indexMax; index++) {
535
    	obsPage.push(obsStation[index]);
536
    }
537
 
538
    supprimerMessageChargement();
539
    mettreAJourObservations();
540
	return false;
541
}
542
 
543
function mettreAJourObservations() {
544
	$("#obs-"+pagineur.format+"-lignes").empty();
545
   	$("#obs-vue-"+pagineur.format).css('display', 'block');
546
   	$(".obs-conteneur").css('counter-reset', 'item '+pagineur.depart);
547
	$("#tpl-obs-"+pagineur.format).tmpl(obsPage).appendTo("#obs-"+pagineur.format+"-lignes");
548
 
549
	// Actualisation de Fancybox
941 jpm 550
	ajouterFomulaireContact("a.contact");
915 jpm 551
	if (pagineur.format == 'liste') {
836 jpm 552
		ajouterGaleriePhoto("a.cel-img");
553
	}
554
}
555
 
915 jpm 556
function initialiserContenuInfoBulle() {
980 jpm 557
	afficherMessageChargement('#observations');
558
	cacherContenuOnglets();
915 jpm 559
	afficherOnglets();
560
	ajouterTableauTriable("#obs-tableau");
561
	afficherTextStationId();
562
	corrigerLargeurInfoWindow();
563
}
564
 
980 jpm 565
function cacherContenuOnglets() {
566
	$("#obs-vue-tableau").css("display", "none");
567
	$("#obs-vue-liste").css("display", "none");
568
}
569
 
915 jpm 570
function afficherOnglets() {
571
	var $tabs = $('#obs').tabs();
572
	$('#obs').bind('tabsselect', function(event, ui) {
573
		if (ui.panel.id == 'obs-vue-tableau') {
574
			surClicAffichageTableau();
575
		} else if (ui.panel.id == 'obs-vue-liste') {
576
			surClicAffichageListe();
577
		}
578
	});
980 jpm 579
	if (pointClique.stationInfos.nbre > 4) {
580
		$tabs.tabs('select', "#obs-vue-tableau");
581
	} else {
582
		$tabs.tabs('select', "#obs-vue-liste");
583
	}
584
 
915 jpm 585
}
586
 
939 jpm 587
function selectionnerOnglet(onglet) {
980 jpm 588
	$(onglet).css('display', 'block');
939 jpm 589
	$('#obs').tabs('select', onglet);
590
}
591
 
915 jpm 592
function afficherTextStationId() {
980 jpm 593
	$('#obs-station-id').text(pointClique.stationInfos.id);
915 jpm 594
}
595
 
596
function corrigerLargeurInfoWindow() {
953 jpm 597
	$("#info-bulle").width($("#info-bulle").width() - 17);
915 jpm 598
}
599
 
600
function surClicAffichageTableau(event) {
601
	pagineur.format = 'tableau';
602
	mettreAJourObservations();
603
	mettreAJourTableauTriable("#obs-tableau");
604
}
605
 
606
function surClicAffichageListe(event) {
607
	pagineur.format = 'liste';
608
	mettreAJourObservations();
609
	ajouterGaleriePhoto("a.cel-img");
610
}
611
 
836 jpm 612
function ajouterTableauTriable(element) {
613
	// add parser through the tablesorter addParser method
614
	$.tablesorter.addParser({
615
		// Définition d'un id unique pour ce parsseur
616
		id: 'date_cel',
617
		is: function(s) {
915 jpm 618
			// doit retourner false si le parsseur n'est pas autodétecté
619
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
836 jpm 620
		},
915 jpm 621
		format: function(date) {
836 jpm 622
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
915 jpm 623
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
836 jpm 624
			// Remplace la date par un nombre de millisecondes pour trier numériquement
915 jpm 625
			return $.tablesorter.formatFloat(new Date(date).getTime());
836 jpm 626
		},
627
		// set type, either numeric or text
628
		type: 'numeric'
629
	});
630
	$(element).tablesorter({
631
        headers: {
915 jpm 632
			1: {
633
            	sorter:'date_cel'
634
        	}
635
    	}
636
	});
836 jpm 637
}
638
 
915 jpm 639
function mettreAJourTableauTriable(element) {
640
	$(element).trigger('update');
641
}
642
 
836 jpm 643
function ajouterGaleriePhoto(element) {
644
	$(element).fancybox({
915 jpm 645
		transitionIn:'elastic',
646
		transitionOut:'elastic',
647
		speedIn	:600,
648
		speedOut:200,
649
		overlayShow:true,
650
		titleShow:true,
651
		titlePosition:'inside',
652
		titleFormat:function (titre, currentArray, currentIndex, currentOpts) {
653
			var motif = /urn:lsid:tela-botanica[.]org:cel:img([0-9]+)$/;
654
			motif.exec(titre);
655
			var id = RegExp.$1;
656
			var info = $('#cel-info-'+id).clone().html();
657
			var tpl =
658
				'<div class="cel-legende">'+
659
				'<p class="cel-legende-vei">'+'Image n°' + (currentIndex + 1) + ' sur ' + currentArray.length +'<\/p>'+
660
				(titre && titre.length ? '<p>'+info+'<\/p>' : '' )+
661
				'<\/div>';
662
			return tpl;
836 jpm 663
		}
1032 aurelien 664
	}).live('click', function(e) {
665
		if (e.stopPropagation) {
666
			e.stopPropagation();
667
		}
668
		return false;
669
	});
836 jpm 670
}
671
 
941 jpm 672
function ajouterFomulaireContact(element) {
673
	$(element).fancybox({
674
		transitionIn:'elastic',
675
		transitionOut:'elastic',
676
		speedIn	:600,
677
		speedOut:200,
678
		scrolling: 'no',
679
		titleShow: false,
680
		onStart: function(selectedArray, selectedIndex, selectedOpts) {
681
			var element = selectedArray[selectedIndex];
682
 
683
			var motif = / contributeur-([0-9]+)$/;
684
			motif.exec($(element).attr('class'));
685
			var id = RegExp.$1;
950 jpm 686
			//console.log('Destinataire id : '+id);
941 jpm 687
			$("#fc_destinataire_id").attr('value', id);
688
 
689
			var motif = / obs-([0-9]+) /;
690
			motif.exec($(element).attr('class'));
691
			var id = RegExp.$1;
950 jpm 692
			//console.log('Obs id : '+id);
941 jpm 693
			chargerInfoObsPourMessage(id);
694
		},
695
		onCleanup: function() {
950 jpm 696
			//console.log('Avant fermeture fancybox');
941 jpm 697
			$("#fc_destinataire_id").attr('value', '');
698
			$("#fc_sujet").attr('value', '');
699
			$("#fc_message").text('');
700
		},
701
		onClosed: function(e) {
950 jpm 702
			//console.log('Fermeture fancybox');
941 jpm 703
			if (e.stopPropagation) {
704
				e.stopPropagation();
705
			}
706
			return false;
707
		}
708
	});
709
}
710
 
711
function chargerInfoObsPourMessage(idObs) {
980 jpm 712
	var nomSci = jQuery.trim($(".cel-obs-"+idObs+" .nom-sci:eq(0)").text());
713
	var date = jQuery.trim($(".cel-obs-"+idObs+" .date:eq(0)").text());
714
	var lieu = jQuery.trim($(".cel-obs-"+idObs+" .lieu:eq(0)").text());
953 jpm 715
	var sujet = "Observation #"+idObs+" de "+nomSci;
716
	var message = "\n\n\n\n\n\n\n\n--\nConcerne l'observation de \""+nomSci+'" du "'+date+'" au lieu "'+lieu+'".';
941 jpm 717
	$("#fc_sujet").attr('value', sujet);
718
	$("#fc_message").text(message);
719
}
720
 
721
function initialiserFormulaireContact() {
950 jpm 722
	//console.log('Initialisation du form contact');
941 jpm 723
	$("#form-contact").validate({
724
		rules: {
725
			fc_sujet : "required",
726
			fc_message : "required",
953 jpm 727
			fc_utilisateur_courriel : {
728
				required : true,
729
				email : true}
941 jpm 730
		}
731
	});
732
	$("#form-contact").bind("submit", envoyerCourriel);
950 jpm 733
	$("#fc_annuler").bind("click", function() {$.fancybox.close();});
941 jpm 734
 
735
}
736
 
737
function envoyerCourriel() {
950 jpm 738
	//console.log('Formulaire soumis');
941 jpm 739
	if ($("#form-contact").valid()) {
950 jpm 740
		//console.log('Formulaire valide');
941 jpm 741
		//$.fancybox.showActivity();
742
		var destinataireId = $("#fc_destinataire_id").attr('value');
743
		var urlMessage = "http://www.tela-botanica.org/service:annuaire:Utilisateur/"+destinataireId+"/message"
744
		var erreurMsg = "";
745
		var donnees = new Array();
746
		$.each($(this).serializeArray(), function (index, champ) {
747
			var cle = champ.name;
748
			cle = cle.replace(/^fc_/, '');
953 jpm 749
 
980 jpm 750
			if (cle == 'sujet') {
953 jpm 751
				champ.value += " - Carnet en ligne - Tela Botanica";
752
			}
753
			if (cle == 'message') {
754
				champ.value += "\n--\n"+
980 jpm 755
					"Ce message vous est envoyé par l'intermédiaire du widget carto "+
953 jpm 756
					"du Carnet en Ligne du réseau Tela Botanica.\n"+
757
					"http://www.tela-botanica.org/widget:cel:carto";
758
			}
759
 
941 jpm 760
			donnees[index] = {'name':cle,'value':champ.value};
761
		});
762
		$.ajax({
763
			type : "POST",
764
			cache : false,
765
			url : urlMessage,
766
			data : donnees,
767
			beforeSend : function() {
768
				$(".msg").remove();
769
			},
770
			success : function(data) {
771
				$("#fc-zone-dialogue").append('<pre class="msg info">'+data.message+'</pre>');
772
			},
773
			error : function(jqXHR, textStatus, errorThrown) {
774
				erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
775
				reponse = jQuery.parseJSON(jqXHR.responseText);
776
				if (reponse != null) {
777
					$.each(reponse, function (cle, valeur) {
778
						erreurMsg += valeur + "\n";
779
					});
780
				}
781
			},
782
			complete : function(jqXHR, textStatus) {
783
				var debugMsg = '';
784
				if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
785
					debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
786
					if (debugInfos != null) {
787
						$.each(debugInfos, function (cle, valeur) {
788
							debugMsg += valeur + "\n";
789
						});
790
					}
791
				}
792
				if (erreurMsg != '') {
793
					$("#fc-zone-dialogue").append('<p class="msg">'+
794
							'Une erreur est survenue lors de la transmission de votre message.'+'<br />'+
795
							'Vous pouvez signaler le disfonctionnement à <a href="'+
796
							'mailto:cel@tela-botanica.org'+'?'+
980 jpm 797
							'subject=Disfonctionnement du widget carto'+
941 jpm 798
							"&body="+erreurMsg+"\nDébogage :\n"+debugMsg+
799
							'">cel@tela-botanica.org</a>.'+
800
							'</p>');
801
				}
802
				if (DEBUG) {
803
					console.log('Débogage : '+debugMsg);
804
				}
950 jpm 805
				//console.log('Débogage : '+debugMsg);
806
				//console.log('Erreur : '+erreurMsg);
941 jpm 807
			}
808
		});
809
	}
810
	return false;
811
}
915 jpm 812
/*+--------------------------------------------------------------------------------------------------------+*/
813
// PANNEAU LATÉRAL
836 jpm 814
 
915 jpm 815
function initialiserAffichagePanneauLateral() {
816
	$('#panneau-lateral').height($(window).height() - 35);
841 jpm 817
 
915 jpm 818
	if (nt == '*') {
819
		$('#pl-ouverture').bind('click', afficherPanneauLateral);
820
		$('#pl-fermeture').bind('click', cacherPanneauLateral);
836 jpm 821
	}
939 jpm 822
	chargerTaxons(0, 0);
836 jpm 823
}
824
 
939 jpm 825
function chargerTaxons(depart, total) {
826
	if (depart == 0 || depart < total) {
827
		var limite = 7000;
950 jpm 828
		//console.log("Chargement des taxons de "+depart+" à "+(depart+limite));
939 jpm 829
		var urlTax = taxonsUrl+'&start={start}&limit='+limite;
830
		urlTax = urlTax.replace(/\{start\}/g, depart);
831
		$.getJSON(urlTax, function(infos) {
832
			taxonsCarte = taxonsCarte.concat(infos.taxons);
950 jpm 833
			//console.log("Nbre taxons :"+taxonsCarte.length);
939 jpm 834
			chargerTaxons(depart+limite, infos.total);
835
		});
836
	} else {
837
		if (nt == '*') {
838
			afficherTaxons();
839
		}
980 jpm 840
		afficherTitreCarte();
939 jpm 841
	}
842
}
843
 
844
function afficherTaxons() {
980 jpm 845
	$(".plantes-nbre").text(taxonsCarte.length);
939 jpm 846
	$("#tpl-taxons-liste").tmpl({'taxons':taxonsCarte}).appendTo("#pl-corps");
847
	$('.taxon').live('click', filtrerParTaxon);
848
}
849
 
850
 
915 jpm 851
function afficherPanneauLateral() {
836 jpm 852
	$('#panneau-lateral').width(300);
853
	$('#pl-contenu').css('display', 'block');
854
	$('#pl-ouverture').css('display', 'none');
855
	$('#pl-fermeture').css('display', 'block');
856
	$('#carte').css('left', '300px');
857
 
858
	google.maps.event.trigger(map, 'resize');
859
};
860
 
915 jpm 861
function cacherPanneauLateral() {
836 jpm 862
	$('#panneau-lateral').width(24);
863
	$('#pl-contenu').css('display', 'none');
864
	$('#pl-ouverture').css('display', 'block');
865
	$('#pl-fermeture').css('display', 'none');
866
	$('#carte').css('left', '24px');
867
 
868
	google.maps.event.trigger(map, 'resize');
869
};
870
 
871
function filtrerParTaxon() {
872
	var ntAFiltrer = $('.nt', this).text();
873
	infoBulle.close();
1037 aurelien 874
	var zoom = map.getZoom();
875
	var NELatLng = map.getBounds().getNorthEast().lat()+'|'+map.getBounds().getNorthEast().lng();
876
	var SWLatLng = map.getBounds().getSouthWest().lat()+'|'+map.getBounds().getSouthWest().lng();
877
 
836 jpm 878
	$('#taxon-'+nt).removeClass('taxon-actif');
879
	if (nt == ntAFiltrer) {
880
		nt = '*';
1037 aurelien 881
		stationsUrl = stationsUrl.replace(/num_taxon=[*0-9]+/, 'num_taxon='+nt);
882
		chargerMarqueurs(zoom, NELatLng, SWLatLng);
836 jpm 883
	} else {
1035 aurelien 884
		stationsUrl = stationsUrl.replace(/num_taxon=[*0-9]+/, 'num_taxon='+ntAFiltrer);
885
		url = stationsUrl;
886
		url += '&zoom='+zoom+
887
			'&ne='+NELatLng+
888
			'&sw='+SWLatLng;
889
		requeteChargementPoints = $.getJSON(url, function (stationsFiltrees) {
939 jpm 890
			stations = stationsFiltrees;
836 jpm 891
			nt = ntAFiltrer;
892
			$('#taxon-'+nt).addClass('taxon-actif');
1035 aurelien 893
			rafraichirMarqueurs(stations);
836 jpm 894
		});
895
	}
896
};
897
 
915 jpm 898
/*+--------------------------------------------------------------------------------------------------------+*/
899
// FONCTIONS UTILITAIRES
900
 
980 jpm 901
function ouvrirPopUp(element, nomPopUp, event) {
902
	var options =
903
		'width=650,'+
904
		'height=600,'+
905
		'scrollbars=yes,'+
906
		'directories=no,'+
907
		'location=no,'+
908
		'menubar=no,'+
909
		'status=no,'+
910
		'toolbar=no';
911
	var popUp = window.open(element.href, nomPopUp, options);
912
	if (window.focus) {
913
		popUp.focus();
914
	}
915
	return arreter(event);
916
};
917
 
918
function ouvrirNouvelleFenetre(element, event) {
919
	window.open(element.href);
920
	return arreter(event);
921
}
922
 
915 jpm 923
function arreter(event) {
924
	if (event.stopPropagation) {
925
		event.stopPropagation();
926
	} else if (window.event) {
927
		window.event.cancelBubble = true;
928
	}
980 jpm 929
	if (event.preventDefault) {
930
		event.preventDefault();
931
	}
932
	event.returnValue = false;
915 jpm 933
	return false;
934
}
935
 
836 jpm 936
/**
937
 * +-------------------------------------+
938
 * Number.prototype.formaterNombre
939
 * +-------------------------------------+
940
 * Params (facultatifs):
941
 * - Int decimales: nombre de decimales (exemple: 2)
942
 * - String signe: le signe precedent les decimales (exemple: "," ou ".")
943
 * - String separateurMilliers: comme son nom l'indique
944
 * Returns:
945
 * - String chaine formatee
946
 * @author	::mastahbenus::
947
 * @author	Jean-Pascal MILCENT <jpm@tela-botanica.org> : ajout détection auto entier/flotant
948
 * @souce	http://www.javascriptfr.com/codes/FORMATER-NOMBRE-FACON-NUMBER-FORMAT-PHP_40060.aspx
949
 */
950
Number.prototype.formaterNombre = function (decimales, signe, separateurMilliers) {
951
	var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
952
 
953
	function is_int(nbre) {
954
		nbre = nbre.replace(',', '.');
955
		return !(parseFloat(nbre)-parseInt(nbre) > 0);
956
	}
957
 
958
	if (decimales == undefined) {
959
		if (is_int(_sNombre)) {
960
			decimales = 0;
961
		} else {
962
			decimales = 2;
963
		}
964
	}
965
	if (signe == undefined) {
966
		if (is_int(_sNombre)) {
967
			signe = '';
968
		} else {
969
			signe = '.';
970
		}
971
	}
972
	if (separateurMilliers == undefined) {
973
		separateurMilliers = ' ';
974
	}
975
 
976
	function separeMilliers (sNombre) {
977
		var sRetour = "";
978
		while (sNombre.length % 3 != 0) {
979
			sNombre = "0"+sNombre;
980
		}
981
		for (i = 0; i < sNombre.length; i += 3) {
982
			if (i == sNombre.length-1) separateurMilliers = '';
983
			sRetour += sNombre.substr(i, 3) + separateurMilliers;
984
		}
985
		while (sRetour.substr(0, 1) == "0") {
986
			sRetour = sRetour.substr(1);
987
		}
988
		return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
989
	}
990
 
991
	if (_sNombre.indexOf('.') == -1) {
992
		for (i = 0; i < decimales; i++) {
993
			_sDecimales += "0";
994
		}
995
		_sRetour = separeMilliers(_sNombre) + signe + _sDecimales;
996
	} else {
997
		var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
998
		if (sDecimalesTmp.length > decimales) {
999
			var nDecimalesManquantes = sDecimalesTmp.length - decimales;
1000
			var nDiv = 1;
1001
			for (i = 0; i < nDecimalesManquantes; i++) {
1002
				nDiv *= 10;
1003
			}
1004
			_sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
1005
		}
1006
		_sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
1007
	}
1008
	return _sRetour;
915 jpm 1009
}
1010
 
1011
function debug(objet) {
1012
	var msg = '';
1013
	if (objet != null) {
1014
		$.each(objet, function (cle, valeur) {
1015
			msg += cle+":"+valeur + "\n";
1016
		});
1017
	} else {
1018
		msg = "La variable vaut null.";
1019
	}
1020
	console.log(msg);
836 jpm 1021
}