Subversion Repositories eFlore/Applications.cel

Rev

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