Subversion Repositories eFlore/Applications.cel

Rev

Rev 2410 | Rev 2440 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2406 jpm 1
//+---------------------------------------------------------------------------------------------------------+
2
// GÉNÉRAL
3
$(document).ready(function() {
4
	if (DEBUG == false) {
5
		$(window).on('beforeunload', function(event) {
6
			return 'Êtes vous sûr de vouloir quiter la page?\nLes observations saisies mais non transmises seront perdues.';
7
		});
8
	}
9
});
10
//+----------------------------------------------------------------------------------------------------------+
11
// FONCTIONS GÉNÉRIQUES
12
/**
13
 * Stope l'évènement courrant quand on clique sur un lien.
14
 * Utile pour Chrome, Safari...
15
 * @param evenement
16
 * @return
17
 */
18
function arreter(evenement) {
19
	if (evenement.stopPropagation) {
20
		evenement.stopPropagation();
21
	}
22
	if (evenement.preventDefault) {
23
		evenement.preventDefault();
24
	}
25
	return false;
26
}
27
 
28
function extraireEnteteDebug(jqXHR) {
29
	var msgDebug = '';
2410 jpm 30
	if (jqXHR.getResponseHeader('X-DebugJrest-Data') != '') {
31
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader('X-DebugJrest-Data'));
2406 jpm 32
		if (debugInfos != null) {
33
			$.each(debugInfos, function (cle, valeur) {
34
				msgDebug += valeur + "\n";
35
			});
36
		}
37
	}
38
	return msgDebug;
39
}
40
 
41
function afficherPanneau(selecteur) {
2410 jpm 42
	$(selecteur).fadeIn('slow').delay(DUREE_MESSAGE).fadeOut('slow');
2406 jpm 43
}
44
 
2410 jpm 45
 
46
//+---------------------------------------------------------------------------------------------------------+
47
//FORMULAIRE
2406 jpm 48
$(document).ready(function() {
2410 jpm 49
	if (OBS_ID != '') {
50
		chargerInfoObs();
51
	}
52
});
2406 jpm 53
 
2410 jpm 54
function chargerInfoObs() {
55
	var urlObs = SERVICE_OBS_URL + '/' + OBS_ID;
56
	$.ajax({
57
		url: urlObs,
58
		type: 'GET',
59
		success: function(data, textStatus, jqXHR) {
60
			if (data != undefined && data != '') {
61
				prechargerForm(data);
62
			}
63
			// TODO: voir s'il est pertinent d'indiquer quelque chose en cas d'erreur ou d'obs
64
			// inexistante
65
		},
66
		error: function(jqXHR, textStatus, errorThrown) {
67
			// TODO: cf TODO ci-dessus
2406 jpm 68
		}
69
	});
2410 jpm 70
}
2406 jpm 71
 
2410 jpm 72
function prechargerForm(data) {
73
	$('#milieu').val(data.milieu);
74
 
75
	$('#carte-recherche').val(data.zoneGeo);
76
	$('#commune-nom').text(data.zoneGeo);
77
 
78
	if (data.hasOwnProperty('codeZoneGeo')) {
79
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
80
		$('#commune-code-insee').text(data.codeZoneGeo.replace('INSEE-C:', ''));
2406 jpm 81
	}
82
 
2410 jpm 83
	if (data.hasOwnProperty('latitude') && data.hasOwnProperty('longitude')) {
84
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
85
		mettreAJourMarkerPosition(latLng);
86
		marker.setPosition(latLng);
87
		 map.setCenter(latLng);
88
	    map.setZoom(16);
89
	}
90
}
91
 
92
 
93
//+----------------------------------------------------------------------------------------------------------+
94
//FORM IDENTITE : gestion de l'observateur
95
 
96
$(document).ready(function() {
97
	requeterIdentite();// Sur rechargement de la page
98
 
99
	// Interaction sur le formulaire observateur
100
	$('#prenom').on('change', formaterPrenom);
101
	$('#nom').on('change', formaterNom);
102
	$('#courriel').on('blur', requeterIdentite);
103
	$('#courriel').on('keyup', testerLancementRequeteIdentite);
104
	$('#courriel_confirmation').on('paste', bloquerCopierCollerCourriel);
2406 jpm 105
});
106
 
2410 jpm 107
function testerLancementRequeteIdentite(event) {
108
	if (event.which == 13) {
109
		requeterIdentite();
110
		event.preventDefault();
111
		event.stopPropagation();
112
	}
2406 jpm 113
}
114
 
2410 jpm 115
function requeterIdentite() {
116
	var courriel = $('#courriel').val();
117
	if (courriel) {
118
		var urlAnnuaire = SERVICE_ANNUAIRE_ID_URL + courriel;
119
		$.ajax({
120
			url: urlAnnuaire,
121
			type: 'GET',
122
			success: function(data, textStatus, jqXHR) {
123
				if (data != undefined && data[courriel] != undefined) {
124
					var infos = data[courriel];
125
					surSuccesCompletionCourriel(infos, courriel);
126
				} else {
127
					surErreurCompletionCourriel();
128
				}
129
			},
130
			error: function(jqXHR, textStatus, errorThrown) {
131
				surErreurCompletionCourriel();
132
			},
133
			complete: function(jqXHR, textStatus) {
134
				$('#zone-courriel-confirmation, #zone-prenom-nom').removeClass('hidden');
135
				$('#form-observateur').valid();
136
			}
137
		});
2406 jpm 138
	}
139
}
140
 
2410 jpm 141
function surErreurCompletionCourriel() {
142
	$('#prenom, #nom, #courriel_confirmation').removeAttr('disabled');
143
	afficherPanneau('#dialogue-courriel-introuvable');
2406 jpm 144
}
145
 
2410 jpm 146
function surSuccesCompletionCourriel(infos, courriel) {
147
	$('#id_utilisateur').val(infos.id);
148
	$('#prenom').val(infos.prenom);
149
	$('#nom').val(infos.nom);
150
	$('#courriel_confirmation').val(courriel);
151
	$('#prenom, #nom, #courriel_confirmation').attr('disabled', 'disabled');
152
 
153
	$('#dialogue-courriel-introuvable').hide();
2406 jpm 154
}
155
 
2410 jpm 156
function formaterNom() {
157
	$(this).val($(this).val().toUpperCase());
158
}
2406 jpm 159
 
2410 jpm 160
function formaterPrenom() {
161
	var prenom = new Array(),
162
		mots = $(this).val().split(' ');
163
	for (var i = 0; i < mots.length; i++) {
164
		var mot = mots[i];
165
		if (mot.indexOf('-') >= 0) {
166
			var prenomCompose = new Array(),
167
				motsComposes = mot.split('-');
168
			for (var j = 0; j < motsComposes.length; j++) {
169
				var motSimple = motsComposes[j],
170
					motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
171
				prenomCompose.push(motMajuscule);
172
			}
173
			prenom.push(prenomCompose.join('-'));
174
		} else {
175
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
176
			prenom.push(motMajuscule);
177
		}
2406 jpm 178
	}
2410 jpm 179
	$(this).val(prenom.join(' '));
180
}
2406 jpm 181
 
2410 jpm 182
function bloquerCopierCollerCourriel() {
183
	afficherPanneau('#dialogue-bloquer-copier-coller');
184
	return false;
185
}
2406 jpm 186
 
187
 
188
//+----------------------------------------------------------------------------------------------------------+
189
// GOOGLE MAP
2410 jpm 190
var map,
191
	marker,
192
	latLng,
193
	geocoder;
2406 jpm 194
 
195
$(document).ready(function() {
196
	initialiserGoogleMap();
197
	initialiserAutocompleteCommune();
198
});
199
 
200
function afficherErreurGoogleMap(status) {
201
	if (DEBUG) {
202
		$('#dialogue-google-map .contenu').empty().append(
203
			'<pre class="msg-erreur">'+
204
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
205
			'</pre>');
206
		afficherPanneau('#dialogue-google-map');
207
	}
208
}
209
 
210
function surDeplacementMarker() {
211
	mettreAJourMarkerPosition(marker.getPosition());
212
}
213
 
214
function surClickDansCarte(event) {
215
	deplacerMarker(event.latLng);
216
}
217
 
218
function geolocaliser() {
2410 jpm 219
	var latitude = $('#latitude').val(),
220
		longitude = $('#longitude').val();
2406 jpm 221
	latLng = new google.maps.LatLng(latitude, longitude);
222
	deplacerMarker(latLng);
223
}
224
 
225
function initialiserGoogleMap(){
226
	// Carte
2410 jpm 227
	var latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
228
	var zoomDefaut = 5;
2406 jpm 229
 
230
	var options = {
231
		zoom: zoomDefaut,
232
		center: latLng,
233
		mapTypeId: google.maps.MapTypeId.HYBRID,
234
		mapTypeControlOptions: {
235
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
236
	};
237
 
238
	// Ajout de la couche OSM à la carte
239
	osmMapType = new google.maps.ImageMapType({
240
		getTileUrl: function(coord, zoom) {
2410 jpm 241
			return 'http://tile.openstreetmap.org/' +
242
			zoom + '/' + coord.x + '/' + coord.y + '.png';
2406 jpm 243
		},
244
		tileSize: new google.maps.Size(256, 256),
245
		isPng: true,
246
		alt: 'OpenStreetMap',
247
		name: 'OSM',
248
		maxZoom: 19
249
	});
250
 
251
	// Création de la carte Google
252
	map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
253
	map.mapTypes.set('OSM', osmMapType);
254
 
255
	// Création du Geocoder
256
	geocoder = new google.maps.Geocoder();
257
 
258
	// Marqueur google draggable
259
	marker = new google.maps.Marker({
260
		map: map,
261
		draggable: true,
262
		title: 'Ma station',
263
		icon: GOOGLE_MAP_MARQUEUR_URL,
264
		position: latLng
265
	});
266
 
267
	initialiserMarker(latLng);
268
 
269
	// Tentative de geocalisation
270
	if (navigator.geolocation) {
271
		navigator.geolocation.getCurrentPosition(function(position) {
272
			var latitude = position.coords.latitude;
273
			var longitude = position.coords.longitude;
274
			latLng = new google.maps.LatLng(latitude, longitude);
275
			deplacerMarker(latLng);
276
		});
277
	}
278
 
279
	// intéraction carte
2410 jpm 280
	$('#geolocaliser').on('click', geolocaliser);
2406 jpm 281
	google.maps.event.addListener(marker, 'dragend', surDeplacementMarker);
282
	google.maps.event.addListener(map, 'click', surClickDansCarte);
283
}
284
 
285
function initialiserMarker(latLng) {
286
	if (marker != undefined) {
287
		marker.setPosition(latLng);
288
		map.setCenter(latLng);
2410 jpm 289
		mettreAJourMarkerPosition(latLng);
2406 jpm 290
	}
291
}
292
 
293
function deplacerMarker(latLng) {
294
	if (marker != undefined) {
295
		marker.setPosition(latLng);
296
		map.setCenter(latLng);
297
		mettreAJourMarkerPosition(latLng);
298
	}
299
}
300
 
301
function mettreAJourMarkerPosition(latLng) {
2410 jpm 302
	trouverCommune(latLng);
303
	trouverAltitude(latLng);
304
 
305
	var lat = latLng.lat().toFixed(5),
306
		lng = latLng.lng().toFixed(5);
2406 jpm 307
	remplirChampLatitude(lat);
308
	remplirChampLongitude(lng);
2410 jpm 309
	remplirChampsLambert93(lat, lng);
2406 jpm 310
}
311
 
312
function remplirChampLatitude(latDecimale) {
313
	var lat = Math.round(latDecimale * 100000) / 100000;
314
	$('#latitude').val(lat);
315
}
316
 
317
function remplirChampLongitude(lngDecimale) {
318
	var lng = Math.round(lngDecimale * 100000) / 100000;
319
	$('#longitude').val(lng);
320
}
321
 
2410 jpm 322
proj4.defs([
323
	['EPSG:4326', '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'],
324
	['EPSG:2154', '+title=RGF93 / Lambert-93 +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs']
325
]);
326
function remplirChampsLambert93(lat, lng) {
327
	// Prendre en compte l'initialisation des projections
328
	var coordinate = {x: lng,y: lat};
329
	proj4(proj4.defs('EPSG:4326'), proj4.defs('EPSG:2154')).forward(coordinate);
330
	$('#l93-x').val(coordinate.x.toFixed(0));
331
	$('#l93-y').val(coordinate.y.toFixed(0));
332
}
333
 
334
function trouverAltitude(pos) {
2406 jpm 335
	$(function() {
2410 jpm 336
		var url_service = SERVICE_ALTITUDE_URL,
337
			urlAltFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
338
		$.ajax({
339
			url: urlAltFormatee,
340
			type: 'GET',
341
			dataType: 'jsonp',
342
			beforeSend : function() {
343
				$('#altitude').empty();
344
				$('#dialogue-erreur .alert-txt').empty();
345
			},
346
			success : function(data, textStatus, jqXHR) {
347
				$('#altitude').empty().append(data.altitude);
348
				$('#marqueur-altitude').data('altitude', data.altitude);
349
			},
350
			statusCode : {
351
			    500 : function(jqXHR, textStatus, errorThrown) {
352
					if (DEBUG) {
353
						$('#dialogue-erreur .alert-txt').append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissant l\'altitude.</p>');
354
						reponse = jQuery.parseJSON(jqXHR.responseText);
355
						var erreurMsg = '';
356
						if (reponse != null) {
357
							$.each(reponse, function (cle, valeur) {
358
								erreurMsg += valeur + '<br />';
359
							});
360
						}
2406 jpm 361
 
2410 jpm 362
						$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
363
					}
364
			    }
365
			},
366
			error : function(jqXHR, textStatus, errorThrown) {
367
				if (DEBUG) {
368
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de l\'appel au service fournissant l\'altitude.</p>');
369
					reponse = jQuery.parseJSON(jqXHR.responseText);
370
					var erreurMsg = '';
371
					if (reponse != null) {
372
						$.each(reponse, function (cle, valeur) {
373
							erreurMsg += valeur + '<br />';
374
						});
375
					}
2406 jpm 376
 
2410 jpm 377
					$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
378
				}
379
			},
380
			complete : function(jqXHR, textStatus) {
381
				var debugMsg = extraireEnteteDebug(jqXHR);
382
				if (debugMsg != '') {
383
					if (DEBUG) {
384
						$('#dialogue-erreur .alert-txt').append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
385
					}
386
				}
387
				if ($('#dialogue-erreur .msg').length > 0) {
388
					$('#dialogue-erreur').show();
389
				}
390
			}
391
		});
392
	});
393
}
394
 
395
function trouverCommune(pos) {
396
	$(function() {
397
		var url_service = SERVICE_NOM_COMMUNE_URL,
398
			urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
2406 jpm 399
		$.ajax({
2410 jpm 400
			url: urlNomCommuneFormatee,
401
			type: 'GET',
402
			dataType: 'jsonp',
2406 jpm 403
			beforeSend : function() {
2410 jpm 404
				$('.commune-info').empty();
405
				$('#dialogue-erreur .alert-txt').empty();
2406 jpm 406
			},
407
			success : function(data, textStatus, jqXHR) {
2410 jpm 408
				$('.commune-info').empty();
409
				$('#commune-nom').append(data.nom);
410
				$('#commune-code-insee').append(data.codeINSEE);
411
				$('#marqueur-commune').data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
2406 jpm 412
			},
413
			statusCode : {
414
			    500 : function(jqXHR, textStatus, errorThrown) {
415
					if (DEBUG) {
2410 jpm 416
						$('#dialogue-erreur .alert-txt').append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
2406 jpm 417
						reponse = jQuery.parseJSON(jqXHR.responseText);
2410 jpm 418
						var erreurMsg = '';
2406 jpm 419
						if (reponse != null) {
420
							$.each(reponse, function (cle, valeur) {
2410 jpm 421
								erreurMsg += valeur + '<br />';
2406 jpm 422
							});
423
						}
424
 
2410 jpm 425
						$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
2406 jpm 426
					}
427
			    }
428
			},
429
			error : function(jqXHR, textStatus, errorThrown) {
430
				if (DEBUG) {
431
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la transmission de vos observations.</p>');
432
					reponse = jQuery.parseJSON(jqXHR.responseText);
2410 jpm 433
					var erreurMsg = '';
2406 jpm 434
					if (reponse != null) {
435
						$.each(reponse, function (cle, valeur) {
2410 jpm 436
							erreurMsg += valeur + '<br />';
2406 jpm 437
						});
438
					}
439
 
2410 jpm 440
					$('#dialogue-erreur .alert-txt').append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
2406 jpm 441
				}
442
			},
443
			complete : function(jqXHR, textStatus) {
444
				var debugMsg = extraireEnteteDebug(jqXHR);
445
				if (debugMsg != '') {
446
					if (DEBUG) {
2410 jpm 447
						$('#dialogue-erreur .alert-txt').append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
2406 jpm 448
					}
449
				}
2410 jpm 450
				if ($('#dialogue-erreur .msg').length > 0) {
451
					$('#dialogue-erreur').show();
2406 jpm 452
				}
453
			}
454
		});
455
	});
456
}
2410 jpm 457
 
458
 
2406 jpm 459
//+---------------------------------------------------------------------------------------------------------+
2410 jpm 460
//AUTO-COMPLÉTION Noms Scientifiques
2406 jpm 461
 
2410 jpm 462
function ajouterAutocompletionNoms() {
463
	$('#taxon').autocomplete({
464
		source: function(requete, add){
465
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
2406 jpm 466
 
2410 jpm 467
			var url = getUrlAutocompletionNomsSci();
468
			$.getJSON(url, function(data) {
469
				var suggestions = traiterRetourNomsSci(data);
470
				add(suggestions);
471
			});
2406 jpm 472
		},
2410 jpm 473
		html: true
474
	});
475
 
476
	$('#taxon').on('autocompleteselect', function(event, ui) {
477
		$('#taxon').data(ui.item);
478
		if (ui.item.retenu == true) {
479
			$('#taxon').addClass('ns-retenu');
480
		} else {
481
			$('#taxon').removeClass('ns-retenu');
2406 jpm 482
		}
483
	});
484
}
485
 
2410 jpm 486
function getUrlAutocompletionNomsSci() {
487
	var mots = $('#taxon').val(),
488
		url = SERVICE_AUTOCOMPLETION_NOM_SCI_URL_TPL.replace('{referentiel}',NOM_SCI_REFERENTIEL);
489
	url = url.replace('{masque}', mots);
490
	return url;
2406 jpm 491
}
2410 jpm 492
 
493
function traiterRetourNomsSci(data) {
494
	var suggestions = [];
495
	if (data.resultat != undefined) {
496
		$.each(data.resultat, function(i, val) {
497
			val.nn = i;
498
			var nom = {label: '', value: '', nt: '', nomSel: '', nomSelComplet: '', numNomSel: '',
499
				nomRet: '', numNomRet: '', famille: '', retenu: false
500
			};
501
			if (suggestions.length >= AUTOCOMPLETION_ELEMENTS_NBRE) {
502
				nom.label = '...';
503
				nom.value = $('#taxon').val();
504
				suggestions.push(nom);
505
				return false;
506
			} else {
507
				nom.label = val.nom_sci_complet;
508
				nom.value = val.nom_sci_complet;
509
				nom.nt = val.num_taxonomique;
510
				nom.nomSel = val.nom_sci;
511
				nom.nomSelComplet = val.nom_sci_complet;
512
				nom.numNomSel = val.nn;
513
				nom.nomRet = val.nom_retenu_complet;
514
				nom.numNomRet = val['nom_retenu.id'];
515
				nom.famille = val.famille;
516
				nom.retenu = (val.retenu == 'false') ? false : true;
517
 
518
				suggestions.push(nom);
519
			}
520
		});
2406 jpm 521
	}
2410 jpm 522
	return suggestions;
523
}
2406 jpm 524
 
2410 jpm 525
/*
526
* jQuery UI Autocomplete HTML Extension
527
*
528
* Copyright 2010, Scott González (http://scottgonzalez.com)
529
* Dual licensed under the MIT or GPL Version 2 licenses.
530
*
531
* http://github.com/scottgonzalez/jquery-ui-extensions
532
*
533
* Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
534
*/
535
(function($) {
536
	var proto = $.ui.autocomplete.prototype,
537
		initSource = proto._initSource;
538
 
539
	function filter(array, term) {
540
		var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), 'i');
541
		return $.grep(array, function(value) {
542
			return matcher.test($('<div>').html(value.label || value.value || value).text());
543
		});
544
	}
545
 
546
	$.extend(proto, {
547
		_initSource: function() {
548
			if (this.options.html && $.isArray(this.options.source)) {
549
				this.source = function( request, response ) {
550
					response(filter(this.options.source, request.term));
551
				};
552
			} else {
553
				initSource.call(this);
2406 jpm 554
			}
555
		},
2410 jpm 556
		_renderItem: function(ul, item) {
557
			if (item.retenu == true) {
558
				item.label = '<strong>'+item.label+'</strong>';
559
			}
560
 
561
			return $('<li></li>')
562
				.data('item.autocomplete', item)
563
				.append($('<a></a>')[this.options.html ? 'html' : 'text'](item.label))
564
				.appendTo(ul);
2406 jpm 565
		}
566
	});
2410 jpm 567
})(jQuery);
2406 jpm 568
 
2410 jpm 569
//+----------------------------------------------------------------------------------------------------------+
570
//UPLOAD PHOTO : Traitement de l'image
571
$(document).ready(function() {
572
	$('.effacer-miniature').click(function () {
573
		supprimerMiniatures($(this));
574
	});
2406 jpm 575
 
2410 jpm 576
	$('#fichier').on('change', function (e) {
577
		arreter(e);
578
		var options = {
579
			success: afficherMiniature, // post-submit callback
580
			dataType: 'xml', // 'xml', 'script', or 'json' (expected server response type)
581
			resetForm: true // reset the form after successful submit
582
		};
583
		$('#ajouter-obs').attr('disabled', 'disabled');
584
		if (verifierFormat($('#fichier').val())) {
585
			$('#form-upload').ajaxSubmit(options);
586
		} else {
587
			$('#form-upload')[0].reset();
588
			window.alert("Le format de fichier n'est pas supporté, les formats acceptés sont "+$('#fichier').attr('accept'));
589
		}
590
		return false;
591
	});
2406 jpm 592
 
2410 jpm 593
	if (ESPECE_IMPOSEE) {
594
		$('#taxon').attr('disabled', 'disabled');
595
		$('#taxon-input-groupe').attr('title', '');
596
		var infosAssociee = new Object();
597
		infosAssociee.label = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
598
		infosAssociee.value = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
599
		infosAssociee.nt = INFOS_ESPECE_IMPOSEE.num_taxonomique;
600
		infosAssociee.nomSel = INFOS_ESPECE_IMPOSEE.nom_sci;
601
		infosAssociee.nomSelComplet = INFOS_ESPECE_IMPOSEE.nom_sci_complet;
602
		infosAssociee.numNomSel = INFOS_ESPECE_IMPOSEE.id;
603
		infosAssociee.nomRet = INFOS_ESPECE_IMPOSEE['nom_retenu.libelle'];
604
		infosAssociee.numNomRet = INFOS_ESPECE_IMPOSEE['nom_retenu.id'];
605
		infosAssociee.famille = INFOS_ESPECE_IMPOSEE.famille;
606
		infosAssociee.retenu = (INFOS_ESPECE_IMPOSEE.retenu == 'false') ? false : true;
607
		$('#taxon').data(infosAssociee);
2406 jpm 608
	}
609
 
2410 jpm 610
	$('body').on('click', '.effacer-miniature', function() {
611
		$(this).parent().remove();
612
	});
613
});
614
 
615
function verifierFormat(nom) {
616
	var parts = nom.split('.');
617
	extension = parts[parts.length - 1];
618
	return (extension.toLowerCase() == 'jpeg' || extension.toLowerCase() == 'jpg');
619
}
620
 
621
function afficherMiniature(reponse) {
622
	if (DEBUG) {
623
		var debogage = $('debogage', reponse).text();
624
		console.log("Débogage upload : "+debogage);
2406 jpm 625
	}
2410 jpm 626
	var message = $('message', reponse).text();
627
	if (message != '') {
628
		$('#miniature-msg').append(message);
629
	} else {
630
		$('#miniatures').append(creerWidgetMiniature(reponse));
631
	}
632
	$('#ajouter-obs').removeAttr('disabled');
2406 jpm 633
}
634
 
2410 jpm 635
function creerWidgetMiniature(reponse) {
636
	var miniatureUrl = $('miniature-url', reponse).text();
637
	var imgNom = $('image-nom', reponse).text();
638
	var html =
639
		'<div class="miniature">'+
640
			'<img class="miniature-img thumbnail" alt="'+imgNom+'" src="'+miniatureUrl+'"/>'+
641
			'<button class="effacer-miniature" type="button">Effacer</button>'+
642
		'</div>'
643
	return html;
644
}
645
 
646
function supprimerMiniatures() {
647
	$('#miniatures').empty();
648
	$('#miniature-msg').empty();
649
}
650
 
651
//Initialise l'autocomplétion de la commune, en fonction du référentiel
652
function initialiserAutocompleteCommune() {
653
	var geocoderOptions = {},
654
		addressSuffix = '';
655
 
656
	geocoderOptions.region = 'fr';
657
	addressSuffix = ', France';
658
 
659
	$('#carte-recherche').autocomplete({
660
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
661
		source: function(request, response) {
662
			geocoderOptions.address = request.term + addressSuffix;
663
			geocoder.geocode( geocoderOptions, function(results, status) {
664
				if (status == google.maps.GeocoderStatus.OK) {
665
					response($.map(results, function(item) {
666
						var retour = {
667
							label: item.formatted_address,
668
							value: item.formatted_address,
669
							latitude: item.geometry.location.lat(),
670
							longitude: item.geometry.location.lng()
671
						};
672
						return retour;
673
					}));
674
				} else {
675
					afficherErreurGoogleMap(status);
676
				}
677
			});
678
		},
679
		// Cette partie est executee a la selection d'une adresse
680
		select: function(event, ui) {
681
			var latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
682
			deplacerMarker(latLng);
683
		}
684
	});
685
 
686
	// Autocompletion du champ adresse
687
	$('#carte-recherche').on('focus', function() {
688
		$(this).select();
689
	});
690
	$('#carte-recherche').on('mouseup', function(event) {// Pour Safari...
691
		event.preventDefault();
692
	});
693
 
694
	$('#carte-recherche').keypress(function(e) {
695
		if (e.which == 13) {
696
			e.preventDefault();
697
		}
698
	});
699
};
700
 
701
 
702
//+---------------------------------------------------------------------------------------------------------+
703
// FORMULAIRE : traitements génériques
2406 jpm 704
var obsNbre = 0;
705
 
706
$(document).ready(function() {
2410 jpm 707
	$('.alert .close').on('click', fermerPanneauAlert);
708
	$('body').on('click', '.fermer', function(event) {
2406 jpm 709
			event.preventDefault();
710
			basculerOuvertureFermetureCadre($(this).find('.icone'));
711
	});
712
	$('.has-tooltip').tooltip('enable');
2410 jpm 713
	$('#btn-aide').on('click', basculerAffichageAide);
2406 jpm 714
 
2412 jpm 715
	// Validation du formulaire
716
	configurerFormValidator();
717
	definirReglesFormValidator();
718
 
2410 jpm 719
	// Date picker
2406 jpm 720
	configurerDatePicker();
721
 
2410 jpm 722
	// Gestion de la liste des taxons
2406 jpm 723
	ajouterAutocompletionNoms();
2410 jpm 724
	surChangementAbondance();// Vérif lors du chargement de la page
725
	$('#abondance').on('change', surChangementAbondance);
2406 jpm 726
 
2410 jpm 727
	// Gestion des obs
728
	$('.btn-coord ').on('click', basculerAffichageCoord);
729
	$('#ajouter-obs').on('click', ajouterObs);
730
	surChangementNbreObs();
731
	$('.obs-nbre').on('changement', surChangementNbreObs);
732
	$('body').on('click', '.supprimer-obs', supprimerObs);
733
	$('#transmettre-obs').on('click', transmettreObs);
2406 jpm 734
 
735
 
2410 jpm 736
	// Défilement des photos
737
	$('body').on('click', '.defilement-miniatures-gauche', function(event) {
2406 jpm 738
			event.preventDefault();
739
			defilerMiniatures($(this));
740
	});
2410 jpm 741
	$('body').on('click', '.defilement-miniatures-droite', function(event) {
2406 jpm 742
		event.preventDefault();
743
		defilerMiniatures($(this));
744
	});
745
});
746
 
2410 jpm 747
function surChangementAbondance() {
748
	if (afficherIndividusNbreGroupe()) {
749
		$('#individus-nbre-groupe').removeClass('hidden');
750
		$('#individus-nbre').valid();
751
	} else {
752
		$('#individus-nbre-groupe').addClass('hidden');
753
	}
754
}
755
 
756
function afficherIndividusNbreGroupe() {
757
	var abondance = $('#abondance').val();
2412 jpm 758
	if (abondance === '1-4 individus' || abondance === '5-9 individus' || abondance === '10-49 individus') {
2410 jpm 759
		return true;
760
	} else {
761
		return false;
762
	}
763
}
764
 
2406 jpm 765
function configurerFormValidator() {
766
	$.validator.addMethod(
2410 jpm 767
		'dateCel',
2406 jpm 768
		function (value, element) {
2412 jpm 769
			return value === '' || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
2406 jpm 770
		},
2410 jpm 771
		'Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.');
2406 jpm 772
 
2410 jpm 773
	$.validator.addMethod(
774
		'individusNbre',
775
		function (value, element) {
776
			var ok = true;
2412 jpm 777
			console.log( 'nbre:'+value+'-');
2410 jpm 778
			if (afficherIndividusNbreGroupe()) {
2412 jpm 779
				var abondance = $('#abondance').val();
780
				console.log('abondance:'+abondance+' - nbre:'+value);
781
				if (abondance === '1-4 individus') {
782
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 1 && value < 5);
783
				} else if (abondance == '5-9 individus') {
784
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 5 && value < 10);
785
				} else if (abondance === '10-49 individus') {
786
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 10 && value < 50);
787
				}
2410 jpm 788
			}
789
			return ok;
790
		},
2412 jpm 791
		"Veuillez indiquer le nombre d'individus sous forme d'entier positif et compris dans la classe définie par le champ « Abondance » (Ex. : 3, 15 ou 33...).");
2410 jpm 792
 
2412 jpm 793
	$.validator.addMethod(
2410 jpm 794
		'isbn',
795
		function (value, element) {
796
			var isbn = value.trim();
797
			return (value == '' || (/^ISBN(-1(?:(0)|3))?:?( )*[0-9]+[- ][0-9]+[- ][0-9]+[- ][0-9]*[- ]*[xX0-9]$/).test(isbn));
798
		},
799
		'Format : ISBN 10 ou 13 avec chaque partie séparée par un espace ou tiret. <br />'+
800
		'Doit débuter par : "ISBN" ou "ISBN-10" ou "ISBN-13". Suivi par ":" ou ": " ou directement le code ISBN.<br />'+
801
		'(Ex. : ISBN:978-3-642-11746-6, ISBN:978 3 642 11746 6, ISBN: 978 3 642 11746 6, ISBN-10: 3 642 11746 6).');
802
 
803
	// Modification des méthodes par défaut de Jquery Validation pour Boostrap 3
804
	$.validator.setDefaults({
805
		ignore: [],// Forcer Jquery Validate à examiner les éléments en "display:none;"
2406 jpm 806
		highlight: function(element) {
2410 jpm 807
			$(element).closest('.form-group').addClass('has-error');
2406 jpm 808
		},
2410 jpm 809
		unhighlight: function(element) {
810
			$(element).closest('.form-group').removeClass('has-error');
811
		},
2406 jpm 812
		success: function(element) {
2410 jpm 813
			$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
2406 jpm 814
 
2410 jpm 815
			if ($(element).attr('id') == 'taxon' && $('#taxon').val() != '') {
2406 jpm 816
				// Si le taxon n'est pas lié au référentiel, on vide le data associé
817
				if ($('#taxon').data('value') != $('#taxon').val()) {
818
					$('#taxon').data('numNomSel', '');
819
					$('#taxon').data('nomRet', '');
820
					$('#taxon').data('numNomRet', '');
821
					$('#taxon').data('nt', '');
822
					$('#taxon').data('famille', '');
823
				}
824
			}
2410 jpm 825
		},
826
		errorElement: 'span',
827
		errorClass: 'help-block',
828
		errorPlacement: function(error, element) {
829
			//console.log(element.attr('name') +'-'+ element.parent('.input-group').length);
830
			if (element.parent('.input-group').length) {
831
				error.insertAfter(element.parent());
832
			} else {
833
				error.insertAfter(element);
834
			}
2406 jpm 835
		}
836
	});
837
}
838
 
839
function definirReglesFormValidator() {
840
	$('#form-observateur').validate({
841
		rules: {
842
			courriel : {
843
				required : true,
844
				email : true},
845
			courriel_confirmation : {
846
				required : true,
847
				equalTo: '#courriel'}
848
		}
849
	});
850
	$('#form-station').validate({
851
		rules: {
852
			latitude : {
853
				range: [-90, 90],
854
				required: true},
855
			longitude : {
856
				range: [-180, 180],
857
				required: true},
2410 jpm 858
			'l93-x': 'required',
859
			'l93-y': 'required'
2406 jpm 860
		}
861
	});
2412 jpm 862
	$('#form-obs-date').validate({
2406 jpm 863
		rules: {
864
			date: {
865
				required: true,
2412 jpm 866
				'dateCel' : true}
867
		}
868
	});
869
	$('#form-obs').validate({
870
		rules: {
2410 jpm 871
			individusNombre: {individusNbre: true},
872
			determinationSource: {isbn: true}
2406 jpm 873
		}
874
	});
875
}
876
 
877
function configurerDatePicker() {
2410 jpm 878
	$.datepicker.setDefaults($.datepicker.regional['fr']);
879
	$('#date').datepicker({
880
		dateFormat: 'dd/mm/yy',
2406 jpm 881
		maxDate: new Date,
2410 jpm 882
		showOn: 'button',
2406 jpm 883
		buttonImageOnly: true,
884
		buttonImage: CALENDRIER_ICONE_URL,
2410 jpm 885
		buttonText: 'Afficher le calendrier pour saisir la date.',
2406 jpm 886
		showButtonPanel: true,
887
		onSelect: function(date) {
888
			$(this).valid();
889
		}
890
	});
2410 jpm 891
	$('img.ui-datepicker-trigger').appendTo('#date-icone');
2406 jpm 892
}
893
 
894
function fermerPanneauAlert() {
2410 jpm 895
	$(this).parentsUntil('.zone-alerte', '.alert').hide();
2406 jpm 896
}
897
 
898
function basculerOuvertureFermetureCadre(element) {
2410 jpm 899
	if (element.hasClass('glyphicon-plus-sign')) {
900
		element.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign');
2406 jpm 901
	} else {
2410 jpm 902
		element.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign');
2406 jpm 903
	}
904
}
905
 
906
function basculerAffichageAide()  {
907
	if ($(this).hasClass('btn-warning')) {
908
		$('.has-tooltip').tooltip('enable');
909
		$(this).removeClass('btn-warning').addClass('btn-success');
910
		$('#btn-aide-txt', this).text("Désactiver l'aide");
911
	} else {
912
		$('.has-tooltip').tooltip('disable');
913
		$(this).removeClass('btn-success').addClass('btn-warning');
914
		$('#btn-aide-txt', this).text("Activer l'aide");
915
	}
916
}
917
 
918
function bloquerCopierCollerCourriel() {
2410 jpm 919
	afficherPanneau('#dialogue-bloquer-copier-coller');
2406 jpm 920
	return false;
921
}
922
 
923
function basculerAffichageCoord() {
2410 jpm 924
	var textActuel = $(this).text(),
925
			textARemplacer = $(this).data('toggle-text');
926
	$(this).text(textARemplacer).data('toggle-text', textActuel);
927
 
928
	if ($(this).hasClass('cacher-coord')) {
929
		$(this).removeClass('cacher-coord').addClass('afficher-coord');
930
		$('#coordonnees-geo').addClass('hidden');
931
	} else {
932
		$(this).removeClass('afficher-coord').addClass('cacher-coord');
933
		$('#coordonnees-geo').removeClass('hidden');
934
	}
935
 
2406 jpm 936
	return false;
937
}
938
 
939
function ajouterObs() {
2410 jpm 940
	// Fermeture automatique des dialogue de transmission de données
941
	$('#dialogue-obs-transaction-ko').hide();
942
	$('#dialogue-obs-transaction-ok').hide();
943
 
2406 jpm 944
	if (validerFormulaire() == true) {
945
		obsNbre = obsNbre + 1;
2410 jpm 946
		$('.obs-nbre').text(obsNbre);
947
		$('.obs-nbre').triggerHandler('changement');
2406 jpm 948
		afficherObs();
949
		stockerObsData();
950
		supprimerMiniatures();
951
		if(!ESPECE_IMPOSEE) {
2410 jpm 952
			$('#taxon').val('');
953
			$('#taxon').data('numNomSel',undefined);
2406 jpm 954
		}
955
		$('#barre-progression-upload').attr('aria-valuemax', obsNbre);
2410 jpm 956
		$('#barre-progression-upload .sr-only').text('0/'+obsNbre+' observations transmises');
2406 jpm 957
	} else {
958
		afficherPanneau('#dialogue-form-invalide');
959
	}
960
}
961
 
962
function afficherObs() {
2410 jpm 963
	var date = $('#date').val(),
964
		commune = $('#commune-nom').text(),
965
		codeInsee = $('#commune-code-insee').text(),
966
		lat = $('input[name="latitude"]').val(),
967
		lng = $('input[name="longitude"]').val(),
968
		lieudit = $('#lieudit').val(),
969
		station = $('#station').val(),
970
 
971
		milieux = $('#milieu').val(),
972
		exposition = getTextOptionSelectionne('station-exposition'),
973
		pente = getTextOptionSelectionne('station-pente'),
974
 
975
		phenologie = getTextOptionSelectionne('phenologie'),
976
		abondance = getTextOptionSelectionne('abondance'),
977
		individus = (($('#individus-nbre').val() === undefined || $('#individus-nbre').val() === '') ? '' : ' (' + $('#individus-nbre').val() + ')'),
978
		typeReleve = getTextOptionSelectionne('releve-type'),
979
		sourceDet = $('#determination-source').val(),
980
 
981
		notes = $('#notes').val();
982
 
983
	$('#liste-obs').prepend(
984
		'<div id="obs'+obsNbre+'" class="obs obs'+obsNbre+'">'+
2406 jpm 985
				'<div class="well">'+
986
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
987
						'title="Supprimer cette observation de la liste à transmettre">'+
988
						'<button class="btn btn-danger supprimer-obs" value="'+obsNbre+'" title="'+obsNbre+'">'+
2410 jpm 989
							'<span class="glyphicon glyphicon-trash icon-white"></i>'+
2406 jpm 990
						'</button>'+
991
					'</div> '+
2410 jpm 992
					'<div class="row">'+
993
						'<div class="col-md-2 obs-miniatures">'+
2406 jpm 994
							ajouterImgMiniatureAuTransfert()+
995
						'</div>'+
2410 jpm 996
						'<div class="col-md-8">'+
997
							'<ul class="list-unstyled obs-entete">'+
2406 jpm 998
								'<li>'+
2410 jpm 999
									'Observé à ' +
1000
									'<span class="commune">' + commune + '</span> ' +
1001
									'(' + codeInsee + ') [' + lat +' / ' + lng + ']' +
1002
									' le ' +
1003
									'<span class="date">' + date + '</span>' +
1004
								'</li>' +
1005
							'</ul>'+
1006
							'<ul class="list-unstyled obs-details">'+
1007
								'<li>' +
1008
									'<span>Lieu-dit :</span> ' + lieudit + ' ; ' +
1009
									'<span>Station :</span> ' + station + ' ; ' +
1010
								'</li>' +
1011
								'<li>' +
1012
									'<span>Milieu :</span> ' + milieux + ' ; ' +
1013
									'<span>Exposition :</span> ' + exposition + ' ; ' +
1014
									'<span>Pente :</span> ' + pente + ' ; ' +
1015
								'</li>' +
1016
								'<li>' +
1017
									'<span>Phénologie :</span> ' + phenologie + ' ; ' +
1018
									'<span>Abondance :</span> ' + abondance + individus + ' ; ' +
1019
									'<span>Relevé :</span> ' + typeReleve + ' ; ' +
1020
									'<span>Source :</span> ' + sourceDet + ' ; ' +
1021
								'</li>' +
1022
								'<li>' +
1023
									'<span>Commentaires :</span> ' + notes +
2406 jpm 1024
								'</li>'+
1025
							'</ul>'+
1026
						'</div>'+
1027
					'</div>'+
1028
				'</div>'+
1029
		'</div>');
1030
}
1031
 
2410 jpm 1032
function getTextOptionSelectionne(id) {
1033
	var optionVal = $('#' + id).val(),
1034
		optionText = $('#' + id + ' option:selected').text();
1035
	console.log(optionVal+'-'+optionText);
1036
	return ((optionVal === undefined || optionVal === '') ? '' : optionText);
1037
}
1038
 
2406 jpm 1039
function stockerObsData() {
2410 jpm 1040
	var numNomSel = $('#taxon').data('numNomSel'),
1041
		nomSel = $('#taxon').val(),
1042
		nomRet = $('#taxon').data('nomRet'),
1043
		numNomRet = $('#taxon').data('numNomRet'),
1044
		numTaxon = $('#taxon').data('nt'),
1045
		famille = $('#taxon').data('famille'),
1046
		referentiel = (numNomSel == undefined) ? '' : NOM_SCI_REFERENTIEL;
2406 jpm 1047
 
2410 jpm 1048
	$('#liste-obs').data('obsId'+obsNbre, {
1049
		'date' : $('#date').val(),
1050
		'notes' : $('#notes').val().trim(),
2406 jpm 1051
 
2410 jpm 1052
		'nom_sel': nomSel,
1053
		'num_nom_sel': numNomSel,
1054
		'nom_ret': nomRet,
1055
		'num_nom_ret': numNomRet,
1056
		'num_taxon': numTaxon,
1057
		'famille': famille,
1058
		'referentiel': referentiel,
2406 jpm 1059
 
2410 jpm 1060
		'latitude' : $('#latitude').val(),
1061
		'longitude' : $('#longitude').val(),
1062
		'commune_nom' : $('#commune-nom').text(),
1063
		'commune_code_insee' : $('#commune-code-insee').text(),
1064
		'altitude': $('#altitude').text(),
1065
		'lieudit': $('#lieudit').val().trim(),
1066
		'station': $('#station').val().trim(),
1067
		'milieu': $('#milieu').val().trim(),
1068
		'abondance': $('#abondance').val(),
1069
		'phenologie': $('#phenologie').val(),
1070
 
2406 jpm 1071
		//Ajout des champs images
1072
		'image_nom' : getNomsImgsOriginales(),
1073
 
1074
		// Ajout des champs étendus de l'obs
1075
		'obs_etendue': getObsChpEtendus()
1076
	});
1077
}
1078
 
1079
function getObsChpEtendus() {
1080
	var champs = [];
1081
 
1082
	$('.obs-chp-etendu').each(function() {
1083
		var valeur = $(this).val(),
2410 jpm 1084
			cle = $(this).attr('name');
2406 jpm 1085
		if (valeur != '') {
2410 jpm 1086
			var chpEtendu = {cle: cle, valeur: valeur.trim()};
2406 jpm 1087
			champs.push(chpEtendu);
1088
		}
1089
	});
1090
	return champs;
1091
}
1092
 
1093
function surChangementNbreObs() {
1094
	if (obsNbre == 0) {
2410 jpm 1095
		$('#transmettre-obs').attr('disabled', 'disabled');
1096
		$('#ajouter-obs').removeAttr('disabled');
2406 jpm 1097
	} else if (obsNbre > 0 && obsNbre < OBS_MAX_NBRE) {
2410 jpm 1098
		$('#transmettre-obs').removeAttr('disabled');
1099
		$('#ajouter-obs').removeAttr('disabled');
2406 jpm 1100
	} else if (obsNbre >= OBS_MAX_NBRE) {
2410 jpm 1101
		$('#ajouter-obs').attr('disabled', 'disabled');
1102
		afficherPanneau('#dialogue-bloquer-creer-obs');
2406 jpm 1103
	}
1104
}
1105
 
1106
var nbObsEnCours = 1;
1107
var totalObsATransmettre = 0;
1108
function transmettreObs() {
2410 jpm 1109
	var observations = $('#liste-obs').data();
1110
	if (DEBUG) {
1111
		console.log(observations);
1112
	}
2406 jpm 1113
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
2410 jpm 1114
		afficherPanneau('#dialogue-zero-obs');
2406 jpm 1115
	} else {
1116
		nbObsEnCours = 1;
1117
		nbObsTransmises = 0;
1118
		totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
1119
		depilerObsPourEnvoi();
1120
	}
1121
	return false;
1122
}
1123
 
1124
function depilerObsPourEnvoi() {
2410 jpm 1125
	var observations = $('#liste-obs').data();
2406 jpm 1126
	// la boucle est factice car on utilise un tableau
1127
	// dont on a besoin de n'extraire que le premier élément
1128
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1129
	// TODO: utiliser var.keys quand ça sera plus répandu
1130
	// ou bien utiliser un vrai tableau et pas un objet
1131
	for (var obsNum in observations) {
1132
		obsATransmettre = new Object();
1133
 
1134
	    obsATransmettre['projet'] = TAG_PROJET;
1135
	    obsATransmettre['tag-obs'] = TAG_OBS;
1136
	    obsATransmettre['tag-img'] = TAG_IMG;
1137
 
1138
		var utilisateur = new Object();
2410 jpm 1139
		utilisateur.id_utilisateur = $('#id_utilisateur').val();
1140
		utilisateur.prenom = $('#prenom').val();
1141
		utilisateur.nom = $('#nom').val();
1142
		utilisateur.courriel = $('#courriel').val();
2406 jpm 1143
		obsATransmettre['utilisateur'] = utilisateur;
1144
		obsATransmettre[obsNum] = observations[obsNum];
1145
		var idObsNumerique = obsNum.replace('obsId', '');
1146
		if (idObsNumerique != '') {
1147
			envoyerObsAuCel(idObsNumerique, obsATransmettre);
1148
		}
1149
 
1150
		break;
1151
	}
1152
}
1153
 
1154
var nbObsTransmises = 0;
1155
function mettreAJourProgression() {
1156
	nbObsTransmises++;
1157
	var pct = (nbObsTransmises/totalObsATransmettre)*100;
1158
	$('#barre-progression-upload').attr('aria-valuenow', nbObsTransmises);
2410 jpm 1159
	$('#barre-progression-upload').attr('style', 'width: '+pct+'%');
1160
	$('#barre-progression-upload .sr-only').text(nbObsTransmises+'/'+totalObsATransmettre+' observations transmises');
2406 jpm 1161
 
2410 jpm 1162
	if (obsNbre == 0) {
2406 jpm 1163
		$('.progress').removeClass('active');
1164
		$('.progress').removeClass('progress-striped');
1165
	}
1166
}
1167
 
1168
function envoyerObsAuCel(idObs, observation) {
2410 jpm 1169
	var erreurMsg = '';
2406 jpm 1170
	$.ajax({
1171
		url : SERVICE_SAISIE_URL,
2410 jpm 1172
		type : 'POST',
2406 jpm 1173
		data : observation,
2410 jpm 1174
		dataType : 'json',
2406 jpm 1175
		beforeSend : function() {
2410 jpm 1176
			$('#dialogue-obs-transaction-ko').hide();
1177
			$('#dialogue-obs-transaction-ok').hide();
1178
			$('.alert-txt .msg').remove();
1179
			$('.alert-txt .msg-erreur').remove();
1180
			$('.alert-txt .msg-debug').remove();
1181
			$('#chargement').show();
2406 jpm 1182
		},
1183
		success : function(data, textStatus, jqXHR) {
1184
			// mise à jour du nombre d'obs à transmettre
1185
			// et suppression de l'obs
1186
			supprimerObsParId(idObs);
1187
			nbObsEnCours++;
1188
			// mise à jour du statut
1189
			mettreAJourProgression();
1190
			if(obsNbre > 0) {
1191
				// dépilement de la suivante
1192
				depilerObsPourEnvoi();
1193
			}
1194
		},
1195
		statusCode : {
1196
			500 : function(jqXHR, textStatus, errorThrown) {
1197
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
1198
		    }
1199
		},
1200
		error : function(jqXHR, textStatus, errorThrown) {
1201
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
1202
			try {
1203
				reponse = jQuery.parseJSON(jqXHR.responseText);
1204
				if (reponse != null) {
1205
					$.each(reponse, function (cle, valeur) {
1206
						erreurMsg += valeur + "\n";
1207
					});
1208
				}
1209
			} catch(e) {
1210
				erreurMsg += "L'erreur n'était pas en JSON.";
1211
			}
1212
		},
1213
		complete : function(jqXHR, textStatus) {
1214
			var debugMsg = extraireEnteteDebug(jqXHR);
1215
 
1216
			if (erreurMsg != '') {
1217
				if (DEBUG) {
2410 jpm 1218
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
1219
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
2406 jpm 1220
				}
2410 jpm 1221
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1222
					'subject=Dysfonctionnement du widget de saisie '+TAG_PROJET+
1223
					'&body='+erreurMsg+'%0D%0ADébogage :%0D%0A'+debugMsg;
2406 jpm 1224
 
1225
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1226
				$('#obs'+idObs+' div div').addClass('obs-erreur');
2410 jpm 1227
				window.location.hash = 'obs'+idObs;
2406 jpm 1228
 
2410 jpm 1229
				$('#dialogue-obs-transaction-ko .alert-txt').append($('#tpl-transmission-ko').clone()
2406 jpm 1230
					.find('.courriel-erreur')
1231
					.attr('href', hrefCourriel)
1232
					.end()
1233
					.html());
2410 jpm 1234
				$('#dialogue-obs-transaction-ko').show();
1235
				$('#chargement').hide();
2406 jpm 1236
				initialiserBarreProgression();
1237
			} else {
1238
				if (DEBUG) {
2410 jpm 1239
					$('#dialogue-obs-transaction-ok .alert-txt').append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
2406 jpm 1240
				}
1241
				if(obsNbre == 0) {
1242
					setTimeout(function() {
2410 jpm 1243
						$('#chargement').hide();
2406 jpm 1244
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
2410 jpm 1245
						$('#dialogue-obs-transaction-ok').show();
1246
						window.location.hash = 'dialogue-obs-transaction-ok';
2406 jpm 1247
						initialiserObs();
1248
					}, 1500);
1249
				}
1250
			}
1251
		}
1252
	});
1253
}
1254
 
1255
function validerFormulaire() {
2412 jpm 1256
	var observateur = $('#form-observateur').valid(),
1257
		station = $('#form-station').valid(),
1258
		obsDate = $('#form-obs-date').valid(),
1259
		obs = $('#form-obs').valid();
1260
	return (observateur == true && station == true && obs == true && obsDate == true) ? true : false;
2406 jpm 1261
}
1262
 
1263
function getNomsImgsOriginales() {
1264
	var noms = new Array();
2410 jpm 1265
	$('.miniature-img').each(function() {
2406 jpm 1266
		noms.push($(this).attr('alt'));
1267
	});
1268
	return noms;
1269
}
1270
 
1271
function supprimerObs() {
1272
	var obsId = $(this).val();
1273
	// Problème avec IE 6 et 7
2410 jpm 1274
	if (obsId == 'Supprimer') {
1275
		obsId = $(this).attr('title');
2406 jpm 1276
	}
1277
	supprimerObsParId(obsId);
1278
}
1279
 
1280
function supprimerObsParId(obsId) {
1281
	obsNbre = obsNbre - 1;
2410 jpm 1282
	$('.obs-nbre').text(obsNbre);
1283
	$('.obs-nbre').triggerHandler('changement');
2406 jpm 1284
	$('.obs'+obsId).remove();
2410 jpm 1285
	$('#liste-obs').removeData('obsId'+obsId);
2406 jpm 1286
}
1287
 
1288
function initialiserBarreProgression() {
1289
	$('#barre-progression-upload').attr('aria-valuenow', 0);
2410 jpm 1290
	$('#barre-progression-upload').attr('style', 'width: 0%');
1291
	$('#barre-progression-upload .sr-only').text('0/0 observations transmises');
2406 jpm 1292
	$('.progress').addClass('active');
1293
	$('.progress').addClass('progress-striped');
1294
}
1295
 
1296
function initialiserObs() {
1297
	obsNbre = 0;
1298
	nbObsTransmises = 0;
1299
	nbObsEnCours = 0;
1300
	totalObsATransmettre = 0;
1301
	initialiserBarreProgression();
2410 jpm 1302
	$('.obs-nbre').text(obsNbre);
1303
	$('.obs-nbre').triggerHandler('changement');
1304
	$('#liste-obs').removeData();
2406 jpm 1305
	$('.obs').remove();
2410 jpm 1306
	$('#dialogue-bloquer-creer-obs').hide();
2406 jpm 1307
}
1308
 
1309
function ajouterImgMiniatureAuTransfert() {
1310
	var html = '';
1311
	var miniatures = '';
1312
	var premiere = true;
2410 jpm 1313
	if ($('#miniatures img').length >= 1) {
1314
		$('#miniatures img').each(function() {
2406 jpm 1315
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1316
			premiere = false;
2410 jpm 1317
			var css = $(this).hasClass('b64') ? 'thumbnail b64' : 'thumbnail';
1318
			var src = $(this).attr('src');
1319
			var alt = $(this).attr('alt');
1320
			miniature = '<img class="'+css+' '+visible+'" alt="'+alt+'"src="'+src+'" />';
2406 jpm 1321
			miniatures += miniature;
1322
		});
2410 jpm 1323
		visible = ($('#miniatures img').length > 1) ? '' : 'defilement-miniatures-cache';
2406 jpm 1324
		var html =
1325
			'<div class="defilement-miniatures">'+
2410 jpm 1326
				'<a class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
2406 jpm 1327
				miniatures+
2410 jpm 1328
				'<a class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
2406 jpm 1329
			'</div>';
1330
	} else {
2410 jpm 1331
		html = '<img class="thumbnail" alt="Aucune photo"src="'+PAS_DE_PHOTO_ICONE_URL+'" />';
2406 jpm 1332
	}
1333
	return html;
1334
}
1335
 
1336
function defilerMiniatures(element) {
2410 jpm 1337
	var miniatureSelectionne = element.siblings('img.miniature-selectionnee');
2406 jpm 1338
	miniatureSelectionne.removeClass('miniature-selectionnee');
1339
	miniatureSelectionne.addClass('miniature-cachee');
1340
	var miniatureAffichee = miniatureSelectionne;
1341
 
1342
	if(element.hasClass('defilement-miniatures-gauche')) {
1343
		if(miniatureSelectionne.prev('.miniature').length != 0) {
2410 jpm 1344
			miniatureAffichee = miniatureSelectionne.prev('.thumbnail');
2406 jpm 1345
		} else {
2410 jpm 1346
			miniatureAffichee = miniatureSelectionne.siblings('.thumbnail').last();
2406 jpm 1347
		}
1348
	} else {
1349
		if(miniatureSelectionne.next('.miniature').length != 0) {
2410 jpm 1350
			miniatureAffichee = miniatureSelectionne.next('.thumbnail');
2406 jpm 1351
		} else {
2410 jpm 1352
			miniatureAffichee = miniatureSelectionne.siblings('.thumbnail').first();
2406 jpm 1353
		}
1354
	}
1355
	//console.log(miniatureAffichee);
1356
	miniatureAffichee.addClass('miniature-selectionnee');
1357
	miniatureAffichee.removeClass('miniature-cachee');
1358
}
1359
 
2410 jpm 1360
 
1361
function formaterNumNomSel(numNomSel) {
2406 jpm 1362
	var nn = '';
2410 jpm 1363
	if (numNomSel == undefined) {
2406 jpm 1364
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1365
	} else {
2410 jpm 1366
		nn = '<span class="nn">[nn'+numNomSel+']</span>';
2406 jpm 1367
	}
1368
	return nn;
2410 jpm 1369
}