Subversion Repositories eFlore/Applications.cel

Rev

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