Subversion Repositories eFlore/Applications.cel

Rev

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