Subversion Repositories eFlore/Applications.cel

Rev

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