Subversion Repositories eFlore/Applications.cel

Rev

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