Subversion Repositories eFlore/Applications.cel

Rev

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