Subversion Repositories eFlore/Applications.cel

Rev

Rev 915 | Rev 941 | 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
3
var pointImageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
4
var pointsOrigine = null;
5
var boundsOrigine = null;
6
var markerClusterer = null;
7
var map = null;
8
var infoBulle = new google.maps.InfoWindow();
9
var pointClique = null;
10
var carteCentre = new google.maps.LatLng(46.4, 3.10);
11
var carteOptions = {
12
	zoom: 6,
13
	mapTypeId: google.maps.MapTypeId.ROADMAP,
14
	mapTypeControlOptions: {
15
		mapTypeIds: ['OSM',
16
		             google.maps.MapTypeId.ROADMAP,
17
		             google.maps.MapTypeId.HYBRID,
18
		             google.maps.MapTypeId.SATELLITE,
19
		             google.maps.MapTypeId.TERRAIN]
20
	}
21
};
22
var ctaLayer = null;
23
var osmMapType = new google.maps.ImageMapType({
24
	getTileUrl: function(coord, zoom) {
25
		return "http://tile.openstreetmap.org/" +
26
		zoom + "/" + coord.x + "/" + coord.y + ".png";
27
	},
28
	tileSize: new google.maps.Size(256, 256),
29
	isPng: true,
30
	alt: "OpenStreetMap",
31
	name: "OSM",
32
	maxZoom: 19
33
});
915 jpm 34
var pagineur = {'limite':50, 'start':0, 'total':0, 'stationId':null, 'format':'tableau'};
35
var station = {'commune':'', 'obsNbre':0};
36
var obsStation = new Array();
37
var obsPage = new Array();
939 jpm 38
var taxonsCarte = new Array();
836 jpm 39
/*+--------------------------------------------------------------------------------------------------------+*/
40
// INITIALISATION DU CODE
41
 
42
//Déclenchement d'actions quand JQuery et le document HTML sont OK
43
$(document).ready(function() {
44
	initialiserWidget();
45
});
46
 
47
function initialiserWidget() {
48
	afficherStats();
49
	initialiserAffichageCarte();
50
	initialiserAffichagePanneauLateral();
51
 
52
	initialiserCarte();
53
	initialiserInfoBulle();
54
	chargerLimitesCommunales();
55
	rafraichirCarte();
56
}
57
 
915 jpm 58
/*+--------------------------------------------------------------------------------------------------------+*/
59
// AFFICHAGE GÉNÉRAL
60
 
836 jpm 61
function afficherStats() {
62
	// Ajout du nombre de communes où des observations ont eu lieu
939 jpm 63
	$('#commune-nbre').text(stations.stats.communes.formaterNombre());
836 jpm 64
	// Ajout du nombre d'observations
939 jpm 65
	$('#obs-nbre').text(stations.stats.observations.formaterNombre());
836 jpm 66
}
67
 
915 jpm 68
/*+--------------------------------------------------------------------------------------------------------+*/
69
// CARTE
70
 
836 jpm 71
function initialiserAffichageCarte() {
72
	$('#carte').height($(window).height() - 35);
73
	$('#carte').width($(window).width() - 24);
74
 
75
	if (nt != '*') {
76
		$('#carte').css('left', 0);
77
	}
78
}
79
 
80
function initialiserCarte() {
81
	map = new google.maps.Map(document.getElementById('carte'), carteOptions);
82
	// Ajout de la couche OSM à la carte
83
	map.mapTypes.set('OSM', osmMapType);
84
}
85
 
86
 
87
function chargerLimitesCommunales() {
88
	if (urlsLimitesCommunales != null) {
89
		for (urlId in urlsLimitesCommunales) {
90
			var url = urlsLimitesCommunales[urlId];
91
			ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: true});
92
			ctaLayer.setMap(map);
93
		}
94
	}
95
}
96
 
97
function rafraichirCarte() {
98
	var points = [];
99
	var bounds = new google.maps.LatLngBounds();
939 jpm 100
	for (var i = 0; i < stations.stats.communes; ++i) {
101
		var maLatLng = new google.maps.LatLng(stations.points[i].coord_x, stations.points[i].coord_y);
836 jpm 102
		var pointImage = new google.maps.MarkerImage(pointImageUrl, new google.maps.Size(24, 32));
103
		var point = new google.maps.Marker({
104
			position: maLatLng,
105
			map: map,
106
			icon: pointImage,
939 jpm 107
			stationId: stations.points[i].id
836 jpm 108
		});
109
 
110
		bounds.extend(maLatLng);
111
 
112
		google.maps.event.addListener(point, 'click', function() {
113
			pointClique =  this;
114
			infoBulle.open(map, this);
115
 
116
			var limites = map.getBounds();
117
			var centre = limites.getCenter();
118
			var nordEst = limites.getNorthEast();
119
			var centreSudLatLng = new google.maps.LatLng(nordEst.lat(), centre.lng());
120
			map.panTo(centreSudLatLng);
121
 
915 jpm 122
			afficherInfoBulle();
939 jpm 123
			chargerObs(0, 0);
836 jpm 124
		});
125
 
126
		points.push(point);
127
	}
128
 
129
	if (pointsOrigine == null && boundsOrigine == null) {
130
		pointsOrigine = points;
131
		boundsOrigine = bounds;
132
	}
133
 
134
	executerMarkerClusterer(points, bounds);
135
}
136
 
915 jpm 137
function deplacerCartePointClique() {
138
	map.panTo(pointClique.position);
139
}
140
 
141
function executerMarkerClusterer(points, bounds) {
142
	if (markerClusterer) {
143
		markerClusterer.clearMarkers();
836 jpm 144
	}
915 jpm 145
	markerClusterer = new MarkerClusterer(map, points);
146
	map.fitBounds(bounds);
147
}
148
 
149
/*+--------------------------------------------------------------------------------------------------------+*/
150
// INFO BULLE
151
 
152
function initialiserInfoBulle() {
153
	google.maps.event.addListener(infoBulle, 'domready', initialiserContenuInfoBulle);
154
	google.maps.event.addListener(infoBulle, 'closeclick', deplacerCartePointClique);
155
}
156
 
157
function afficherInfoBulle() {
158
	var obsHtml = $("#tpl-obs").html();
159
	infoBulle.setContent(obsHtml);
160
}
161
 
162
function afficherMessageChargement(element) {
163
	if ($('#chargement').get() == '') {
164
		$('#tpl-chargement').tmpl().appendTo(element);
165
	}
166
}
167
 
168
function supprimerMessageChargement() {
169
	$('#chargement').remove();
170
}
171
 
172
function chargerObs(depart, total) {
939 jpm 173
	if (depart == 0 || depart < total) {
915 jpm 174
		var limite = 300;
175
		if (depart == 0) {
176
			obsStation = new Array();
177
		}
178
		console.log("Chargement de "+depart+" à "+(depart+limite));
939 jpm 179
		var urlObs = observationsUrl+'&start={start}&limit='+limite;
915 jpm 180
		urlObs = urlObs.replace(/\{stationId\}/g, pointClique.stationId);
939 jpm 181
		urlObs = urlObs.replace(/\{nt\}/g, nt);
915 jpm 182
		urlObs = urlObs.replace(/\{start\}/g, depart);
183
 
184
		$.getJSON(urlObs, function(observations){
185
			obsStation = obsStation.concat(observations.observations);
939 jpm 186
			if (depart == 0) {
187
				actualiserInfosStation(observations);
188
				actualiserPagineur();
189
				creerTitreInfoBulle();
190
			}
915 jpm 191
			console.log("Chargement ok");
939 jpm 192
			chargerObs(depart+limite, station.obsNbre);
915 jpm 193
		});
194
	} else {
195
		if (pagineur.limite < total) {
196
			afficherPagination();
197
		} else {
198
			surClicPagePagination(0, null);
939 jpm 199
			selectionnerOnglet("#obs-vue-"+pagineur.format);
915 jpm 200
		}
201
	}
202
}
203
 
939 jpm 204
function actualiserInfosStation(infos) {
205
	station.commune = infos.commune;
206
	station.obsNbre = infos.total;
207
}
915 jpm 208
 
939 jpm 209
function actualiserPagineur() {
210
	pagineur.stationId = pointClique.stationId;
211
	pagineur.total = station.obsNbre;
212
	console.log("Total pagineur: "+pagineur.total);
213
	if (pagineur.total > 4) {
214
		pagineur.format = 'tableau';
215
	} else {
216
		pagineur.format = 'liste';
217
	}
218
}
219
 
915 jpm 220
function afficherPagination(observations) {
221
	$(".navigation").pagination(pagineur.total, {
222
		items_per_page:pagineur.limite,
223
		callback:surClicPagePagination,
224
		next_text:'Suivant',
225
		prev_text:'Précédent',
226
		prev_show_always:false,
227
		num_edge_entries:1,
228
		num_display_entries:5,
229
		load_first_page:true
230
	});
231
}
232
 
233
function surClicPagePagination(pageIndex, paginationConteneur) {
234
	var index = pageIndex * pagineur.limite;
235
	var indexMax = index + pagineur.limite;
236
	pagineur.depart = index;
237
	obsPage = new Array();
238
    for(index; index < indexMax; index++) {
239
    	obsPage.push(obsStation[index]);
240
    }
241
 
242
    supprimerMessageChargement();
243
    mettreAJourObservations();
244
	return false;
245
}
246
 
247
function mettreAJourObservations() {
248
	$("#obs-"+pagineur.format+"-lignes").empty();
249
   	$("#obs-vue-"+pagineur.format).css('display', 'block');
250
   	$(".obs-conteneur").css('counter-reset', 'item '+pagineur.depart);
251
	$("#tpl-obs-"+pagineur.format).tmpl(obsPage).appendTo("#obs-"+pagineur.format+"-lignes");
252
 
253
	// Actualisation de Fancybox
254
	if (pagineur.format == 'liste') {
836 jpm 255
		ajouterGaleriePhoto("a.cel-img");
256
	}
257
}
258
 
915 jpm 259
function creerTitreInfoBulle() {
260
	$("#obs-total").append(station.obsNbre);
261
	$("#obs-commune").append(station.commune);
262
}
263
 
264
function initialiserContenuInfoBulle() {
265
	afficherOnglets();
266
	afficherMessageChargement('#observations');
267
	ajouterTableauTriable("#obs-tableau");
268
	afficherTextStationId();
269
	corrigerLargeurInfoWindow();
270
}
271
 
272
function afficherOnglets() {
273
	var $tabs = $('#obs').tabs();
274
	$('#obs').bind('tabsselect', function(event, ui) {
275
		if (ui.panel.id == 'obs-vue-tableau') {
276
			surClicAffichageTableau();
277
		} else if (ui.panel.id == 'obs-vue-liste') {
278
			surClicAffichageListe();
279
		}
280
	});
281
	$tabs.tabs('select', "#obs-vue-"+pagineur.format);
282
}
283
 
939 jpm 284
function selectionnerOnglet(onglet) {
285
	$('#obs').tabs('select', onglet);
286
}
287
 
915 jpm 288
function afficherTextStationId() {
289
	$('#obs-station-id').text(pointClique.stationId);
290
}
291
 
292
function corrigerLargeurInfoWindow() {
293
	$("#info-bulle").width($("#info-bulle").width() - 16);
294
}
295
 
296
function surClicAffichageTableau(event) {
297
	console.log('tableau');
298
	pagineur.format = 'tableau';
299
	mettreAJourObservations();
300
	mettreAJourTableauTriable("#obs-tableau");
301
}
302
 
303
function surClicAffichageListe(event) {
304
	console.log('liste');
305
	pagineur.format = 'liste';
306
	mettreAJourObservations();
307
	ajouterGaleriePhoto("a.cel-img");
308
}
309
 
836 jpm 310
function ajouterTableauTriable(element) {
311
	// add parser through the tablesorter addParser method
312
	$.tablesorter.addParser({
313
		// Définition d'un id unique pour ce parsseur
314
		id: 'date_cel',
315
		is: function(s) {
915 jpm 316
			// doit retourner false si le parsseur n'est pas autodétecté
317
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
836 jpm 318
		},
915 jpm 319
		format: function(date) {
836 jpm 320
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
915 jpm 321
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
836 jpm 322
			// Remplace la date par un nombre de millisecondes pour trier numériquement
915 jpm 323
			return $.tablesorter.formatFloat(new Date(date).getTime());
836 jpm 324
		},
325
		// set type, either numeric or text
326
		type: 'numeric'
327
	});
328
	$(element).tablesorter({
329
        headers: {
915 jpm 330
			1: {
331
            	sorter:'date_cel'
332
        	}
333
    	}
334
	});
836 jpm 335
}
336
 
915 jpm 337
function mettreAJourTableauTriable(element) {
338
	$(element).trigger('update');
339
}
340
 
836 jpm 341
function ajouterGaleriePhoto(element) {
342
	$(element).fancybox({
915 jpm 343
		transitionIn:'elastic',
344
		transitionOut:'elastic',
345
		speedIn	:600,
346
		speedOut:200,
347
		overlayShow:true,
348
		titleShow:true,
349
		titlePosition:'inside',
350
		titleFormat:function (titre, currentArray, currentIndex, currentOpts) {
351
			var motif = /urn:lsid:tela-botanica[.]org:cel:img([0-9]+)$/;
352
			motif.exec(titre);
353
			var id = RegExp.$1;
354
			var info = $('#cel-info-'+id).clone().html();
355
			var tpl =
356
				'<div class="cel-legende">'+
357
				'<p class="cel-legende-vei">'+'Image n°' + (currentIndex + 1) + ' sur ' + currentArray.length +'<\/p>'+
358
				(titre && titre.length ? '<p>'+info+'<\/p>' : '' )+
359
				'<\/div>';
360
			return tpl;
836 jpm 361
		}
915 jpm 362
		}).live('click', function(e) {
363
			if (e.stopPropagation) {
364
				e.stopPropagation();
365
			}
366
			return false;
367
		});
836 jpm 368
}
369
 
915 jpm 370
/*+--------------------------------------------------------------------------------------------------------+*/
371
// PANNEAU LATÉRAL
836 jpm 372
 
915 jpm 373
function initialiserAffichagePanneauLateral() {
374
	$('#panneau-lateral').height($(window).height() - 35);
841 jpm 375
 
915 jpm 376
	if (nt == '*') {
377
		$('#pl-ouverture').bind('click', afficherPanneauLateral);
378
		$('#pl-fermeture').bind('click', cacherPanneauLateral);
836 jpm 379
	}
939 jpm 380
	chargerTaxons(0, 0);
836 jpm 381
}
382
 
939 jpm 383
function chargerTaxons(depart, total) {
384
	if (depart == 0 || depart < total) {
385
		var limite = 7000;
386
		console.log("Chargement des taxons de "+depart+" à "+(depart+limite));
387
		var urlTax = taxonsUrl+'&start={start}&limit='+limite;
388
		urlTax = urlTax.replace(/\{start\}/g, depart);
389
		$.getJSON(urlTax, function(infos) {
390
			taxonsCarte = taxonsCarte.concat(infos.taxons);
391
			console.log("Nbre taxons :"+taxonsCarte.length);
392
			chargerTaxons(depart+limite, infos.total);
393
		});
394
	} else {
395
		if (nt == '*') {
396
			afficherTaxons();
397
		} else {
398
			afficherNomPlante();
399
		}
400
	}
401
}
402
 
403
function afficherTaxons() {
404
	// Ajout du nombre de plantes au titre
405
	$('.plantes-nbre').text(taxonsCarte.length.formaterNombre());
406
 
407
	$("#tpl-taxons-liste").tmpl({'taxons':taxonsCarte}).appendTo("#pl-corps");
408
	$('.taxon').live('click', filtrerParTaxon);
409
}
410
 
411
function afficherNomPlante() {
412
	if (nt != '*') {
413
		var taxon = taxonsCarte[0];
414
		$('.plante-titre').text('pour '+taxon.nom);
415
	}
416
}
417
 
915 jpm 418
function afficherPanneauLateral() {
836 jpm 419
	$('#panneau-lateral').width(300);
420
	$('#pl-contenu').css('display', 'block');
421
	$('#pl-ouverture').css('display', 'none');
422
	$('#pl-fermeture').css('display', 'block');
423
	$('#carte').css('left', '300px');
424
 
425
	google.maps.event.trigger(map, 'resize');
426
};
427
 
915 jpm 428
function cacherPanneauLateral() {
836 jpm 429
	$('#panneau-lateral').width(24);
430
	$('#pl-contenu').css('display', 'none');
431
	$('#pl-ouverture').css('display', 'block');
432
	$('#pl-fermeture').css('display', 'none');
433
	$('#carte').css('left', '24px');
434
 
435
	google.maps.event.trigger(map, 'resize');
436
};
437
 
438
function ouvrirPopUp(url, nom) {
439
	window.open(url, nom, 'scrollbars=yes,width=650,height=600,directories=no,location=no,menubar=no,status=no,toolbar=no');
440
};
441
 
442
function filtrerParTaxon() {
443
	var ntAFiltrer = $('.nt', this).text();
444
	infoBulle.close();
445
	$('#taxon-'+nt).removeClass('taxon-actif');
446
	if (nt == ntAFiltrer) {
447
		nt = '*';
448
		executerMarkerClusterer(pointsOrigine, boundsOrigine);
449
	} else {
939 jpm 450
		var url = stationsUrl+'&'+
836 jpm 451
			'num_taxon='+ntAFiltrer+'&'+
939 jpm 452
			'formatRetour=jsonP'+'&'+
836 jpm 453
			'callback=?';
939 jpm 454
		$.getJSON(url, function (stationsFiltrees) {
455
			stations = stationsFiltrees;
836 jpm 456
			nt = ntAFiltrer;
457
			$('#taxon-'+nt).addClass('taxon-actif');
458
			rafraichirCarte();
459
		});
460
	}
461
};
462
 
915 jpm 463
/*+--------------------------------------------------------------------------------------------------------+*/
464
// FONCTIONS UTILITAIRES
465
 
466
function arreter(event) {
467
	if (event.stopPropagation) {
468
		event.stopPropagation();
469
	} else if (window.event) {
470
		window.event.cancelBubble = true;
471
	}
472
	return false;
473
}
474
 
836 jpm 475
/**
476
 * +-------------------------------------+
477
 * Number.prototype.formaterNombre
478
 * +-------------------------------------+
479
 * Params (facultatifs):
480
 * - Int decimales: nombre de decimales (exemple: 2)
481
 * - String signe: le signe precedent les decimales (exemple: "," ou ".")
482
 * - String separateurMilliers: comme son nom l'indique
483
 * Returns:
484
 * - String chaine formatee
485
 * @author	::mastahbenus::
486
 * @author	Jean-Pascal MILCENT <jpm@tela-botanica.org> : ajout détection auto entier/flotant
487
 * @souce	http://www.javascriptfr.com/codes/FORMATER-NOMBRE-FACON-NUMBER-FORMAT-PHP_40060.aspx
488
 */
489
Number.prototype.formaterNombre = function (decimales, signe, separateurMilliers) {
490
	var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
491
 
492
	function is_int(nbre) {
493
		nbre = nbre.replace(',', '.');
494
		return !(parseFloat(nbre)-parseInt(nbre) > 0);
495
	}
496
 
497
	if (decimales == undefined) {
498
		if (is_int(_sNombre)) {
499
			decimales = 0;
500
		} else {
501
			decimales = 2;
502
		}
503
	}
504
	if (signe == undefined) {
505
		if (is_int(_sNombre)) {
506
			signe = '';
507
		} else {
508
			signe = '.';
509
		}
510
	}
511
	if (separateurMilliers == undefined) {
512
		separateurMilliers = ' ';
513
	}
514
 
515
	function separeMilliers (sNombre) {
516
		var sRetour = "";
517
		while (sNombre.length % 3 != 0) {
518
			sNombre = "0"+sNombre;
519
		}
520
		for (i = 0; i < sNombre.length; i += 3) {
521
			if (i == sNombre.length-1) separateurMilliers = '';
522
			sRetour += sNombre.substr(i, 3) + separateurMilliers;
523
		}
524
		while (sRetour.substr(0, 1) == "0") {
525
			sRetour = sRetour.substr(1);
526
		}
527
		return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
528
	}
529
 
530
	if (_sNombre.indexOf('.') == -1) {
531
		for (i = 0; i < decimales; i++) {
532
			_sDecimales += "0";
533
		}
534
		_sRetour = separeMilliers(_sNombre) + signe + _sDecimales;
535
	} else {
536
		var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
537
		if (sDecimalesTmp.length > decimales) {
538
			var nDecimalesManquantes = sDecimalesTmp.length - decimales;
539
			var nDiv = 1;
540
			for (i = 0; i < nDecimalesManquantes; i++) {
541
				nDiv *= 10;
542
			}
543
			_sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
544
		}
545
		_sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')))+String(signe)+_sDecimales;
546
	}
547
	return _sRetour;
915 jpm 548
}
549
 
550
function debug(objet) {
551
	var msg = '';
552
	if (objet != null) {
553
		$.each(objet, function (cle, valeur) {
554
			msg += cle+":"+valeur + "\n";
555
		});
556
	} else {
557
		msg = "La variable vaut null.";
558
	}
559
	console.log(msg);
836 jpm 560
}