Subversion Repositories eFlore/Applications.cel

Rev

Rev 2670 | 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;
777
			if (afficherIndividusNbreGroupe()) {
2412 jpm 778
				var abondance = $('#abondance').val();
779
				if (abondance === '1-4 individus') {
780
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 1 && value < 5);
781
				} else if (abondance == '5-9 individus') {
782
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 5 && value < 10);
783
				} else if (abondance === '10-49 individus') {
784
					ok = value === '' || (value !== '' && /^[0-9]+$/.test(value) && value >= 10 && value < 50);
785
				}
2410 jpm 786
			}
787
			return ok;
788
		},
2412 jpm 789
		"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 790
 
2412 jpm 791
	$.validator.addMethod(
2410 jpm 792
		'isbn',
793
		function (value, element) {
794
			var isbn = value.trim();
795
			return (value == '' || (/^ISBN(-1(?:(0)|3))?:?( )*[0-9]+[- ][0-9]+[- ][0-9]+[- ][0-9]*[- ]*[xX0-9]$/).test(isbn));
796
		},
797
		'Format : ISBN 10 ou 13 avec chaque partie séparée par un espace ou tiret. <br />'+
798
		'Doit débuter par : "ISBN" ou "ISBN-10" ou "ISBN-13". Suivi par ":" ou ": " ou directement le code ISBN.<br />'+
799
		'(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).');
800
 
801
	// Modification des méthodes par défaut de Jquery Validation pour Boostrap 3
802
	$.validator.setDefaults({
803
		ignore: [],// Forcer Jquery Validate à examiner les éléments en "display:none;"
2406 jpm 804
		highlight: function(element) {
2410 jpm 805
			$(element).closest('.form-group').addClass('has-error');
2406 jpm 806
		},
2410 jpm 807
		unhighlight: function(element) {
808
			$(element).closest('.form-group').removeClass('has-error');
809
		},
2406 jpm 810
		success: function(element) {
2410 jpm 811
			$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
2406 jpm 812
 
2410 jpm 813
			if ($(element).attr('id') == 'taxon' && $('#taxon').val() != '') {
2406 jpm 814
				// Si le taxon n'est pas lié au référentiel, on vide le data associé
815
				if ($('#taxon').data('value') != $('#taxon').val()) {
816
					$('#taxon').data('numNomSel', '');
817
					$('#taxon').data('nomRet', '');
818
					$('#taxon').data('numNomRet', '');
819
					$('#taxon').data('nt', '');
820
					$('#taxon').data('famille', '');
821
				}
822
			}
2410 jpm 823
		},
824
		errorElement: 'span',
825
		errorClass: 'help-block',
826
		errorPlacement: function(error, element) {
827
			//console.log(element.attr('name') +'-'+ element.parent('.input-group').length);
828
			if (element.parent('.input-group').length) {
829
				error.insertAfter(element.parent());
830
			} else {
831
				error.insertAfter(element);
832
			}
2406 jpm 833
		}
834
	});
835
}
836
 
837
function definirReglesFormValidator() {
838
	$('#form-observateur').validate({
839
		rules: {
840
			courriel : {
841
				required : true,
842
				email : true},
843
			courriel_confirmation : {
844
				required : true,
845
				equalTo: '#courriel'}
846
		}
847
	});
848
	$('#form-station').validate({
849
		rules: {
850
			latitude : {
851
				range: [-90, 90],
852
				required: true},
853
			longitude : {
854
				range: [-180, 180],
855
				required: true},
2410 jpm 856
			'l93-x': 'required',
857
			'l93-y': 'required'
2406 jpm 858
		}
859
	});
2412 jpm 860
	$('#form-obs-date').validate({
2406 jpm 861
		rules: {
862
			date: {
863
				required: true,
2412 jpm 864
				'dateCel' : true}
865
		}
866
	});
867
	$('#form-obs').validate({
868
		rules: {
2410 jpm 869
			individusNombre: {individusNbre: true},
870
			determinationSource: {isbn: true}
2406 jpm 871
		}
872
	});
873
}
874
 
875
function configurerDatePicker() {
2410 jpm 876
	$.datepicker.setDefaults($.datepicker.regional['fr']);
877
	$('#date').datepicker({
878
		dateFormat: 'dd/mm/yy',
2406 jpm 879
		maxDate: new Date,
2410 jpm 880
		showOn: 'button',
2406 jpm 881
		buttonImageOnly: true,
882
		buttonImage: CALENDRIER_ICONE_URL,
2410 jpm 883
		buttonText: 'Afficher le calendrier pour saisir la date.',
2406 jpm 884
		showButtonPanel: true,
885
		onSelect: function(date) {
886
			$(this).valid();
887
		}
888
	});
2410 jpm 889
	$('img.ui-datepicker-trigger').appendTo('#date-icone');
2406 jpm 890
}
891
 
892
function fermerPanneauAlert() {
2410 jpm 893
	$(this).parentsUntil('.zone-alerte', '.alert').hide();
2406 jpm 894
}
895
 
896
function basculerOuvertureFermetureCadre(element) {
2410 jpm 897
	if (element.hasClass('glyphicon-plus-sign')) {
898
		element.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign');
2406 jpm 899
	} else {
2410 jpm 900
		element.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign');
2406 jpm 901
	}
902
}
903
 
904
function basculerAffichageAide()  {
905
	if ($(this).hasClass('btn-warning')) {
906
		$('.has-tooltip').tooltip('enable');
907
		$(this).removeClass('btn-warning').addClass('btn-success');
908
		$('#btn-aide-txt', this).text("Désactiver l'aide");
909
	} else {
910
		$('.has-tooltip').tooltip('disable');
911
		$(this).removeClass('btn-success').addClass('btn-warning');
912
		$('#btn-aide-txt', this).text("Activer l'aide");
913
	}
914
}
915
 
916
function bloquerCopierCollerCourriel() {
2410 jpm 917
	afficherPanneau('#dialogue-bloquer-copier-coller');
2406 jpm 918
	return false;
919
}
920
 
921
function basculerAffichageCoord() {
2410 jpm 922
	var textActuel = $(this).text(),
923
			textARemplacer = $(this).data('toggle-text');
924
	$(this).text(textARemplacer).data('toggle-text', textActuel);
925
 
926
	if ($(this).hasClass('cacher-coord')) {
927
		$(this).removeClass('cacher-coord').addClass('afficher-coord');
928
		$('#coordonnees-geo').addClass('hidden');
929
	} else {
930
		$(this).removeClass('afficher-coord').addClass('cacher-coord');
931
		$('#coordonnees-geo').removeClass('hidden');
932
	}
933
 
2406 jpm 934
	return false;
935
}
936
 
937
function ajouterObs() {
2410 jpm 938
	// Fermeture automatique des dialogue de transmission de données
939
	$('#dialogue-obs-transaction-ko').hide();
940
	$('#dialogue-obs-transaction-ok').hide();
941
 
2406 jpm 942
	if (validerFormulaire() == true) {
943
		obsNbre = obsNbre + 1;
2410 jpm 944
		$('.obs-nbre').text(obsNbre);
945
		$('.obs-nbre').triggerHandler('changement');
2406 jpm 946
		afficherObs();
947
		stockerObsData();
948
		supprimerMiniatures();
949
		if(!ESPECE_IMPOSEE) {
2410 jpm 950
			$('#taxon').val('');
951
			$('#taxon').data('numNomSel',undefined);
2406 jpm 952
		}
953
		$('#barre-progression-upload').attr('aria-valuemax', obsNbre);
2410 jpm 954
		$('#barre-progression-upload .sr-only').text('0/'+obsNbre+' observations transmises');
2406 jpm 955
	} else {
956
		afficherPanneau('#dialogue-form-invalide');
957
	}
958
}
959
 
960
function afficherObs() {
2410 jpm 961
	var date = $('#date').val(),
962
		commune = $('#commune-nom').text(),
963
		codeInsee = $('#commune-code-insee').text(),
964
		lat = $('input[name="latitude"]').val(),
965
		lng = $('input[name="longitude"]').val(),
966
		lieudit = $('#lieudit').val(),
967
		station = $('#station').val(),
968
 
969
		milieux = $('#milieu').val(),
970
		exposition = getTextOptionSelectionne('station-exposition'),
971
		pente = getTextOptionSelectionne('station-pente'),
972
 
973
		phenologie = getTextOptionSelectionne('phenologie'),
974
		abondance = getTextOptionSelectionne('abondance'),
975
		individus = (($('#individus-nbre').val() === undefined || $('#individus-nbre').val() === '') ? '' : ' (' + $('#individus-nbre').val() + ')'),
976
		typeReleve = getTextOptionSelectionne('releve-type'),
977
		sourceDet = $('#determination-source').val(),
978
 
979
		notes = $('#notes').val();
980
 
981
	$('#liste-obs').prepend(
982
		'<div id="obs'+obsNbre+'" class="obs obs'+obsNbre+'">'+
2406 jpm 983
				'<div class="well">'+
984
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
985
						'title="Supprimer cette observation de la liste à transmettre">'+
986
						'<button class="btn btn-danger supprimer-obs" value="'+obsNbre+'" title="'+obsNbre+'">'+
2410 jpm 987
							'<span class="glyphicon glyphicon-trash icon-white"></i>'+
2406 jpm 988
						'</button>'+
989
					'</div> '+
2410 jpm 990
					'<div class="row">'+
991
						'<div class="col-md-2 obs-miniatures">'+
2406 jpm 992
							ajouterImgMiniatureAuTransfert()+
993
						'</div>'+
2410 jpm 994
						'<div class="col-md-8">'+
995
							'<ul class="list-unstyled obs-entete">'+
2406 jpm 996
								'<li>'+
2410 jpm 997
									'Observé à ' +
998
									'<span class="commune">' + commune + '</span> ' +
999
									'(' + codeInsee + ') [' + lat +' / ' + lng + ']' +
1000
									' le ' +
1001
									'<span class="date">' + date + '</span>' +
1002
								'</li>' +
1003
							'</ul>'+
1004
							'<ul class="list-unstyled obs-details">'+
1005
								'<li>' +
1006
									'<span>Lieu-dit :</span> ' + lieudit + ' ; ' +
1007
									'<span>Station :</span> ' + station + ' ; ' +
1008
								'</li>' +
1009
								'<li>' +
1010
									'<span>Milieu :</span> ' + milieux + ' ; ' +
1011
									'<span>Exposition :</span> ' + exposition + ' ; ' +
1012
									'<span>Pente :</span> ' + pente + ' ; ' +
1013
								'</li>' +
1014
								'<li>' +
1015
									'<span>Phénologie :</span> ' + phenologie + ' ; ' +
1016
									'<span>Abondance :</span> ' + abondance + individus + ' ; ' +
1017
									'<span>Relevé :</span> ' + typeReleve + ' ; ' +
1018
									'<span>Source :</span> ' + sourceDet + ' ; ' +
1019
								'</li>' +
1020
								'<li>' +
1021
									'<span>Commentaires :</span> ' + notes +
2406 jpm 1022
								'</li>'+
1023
							'</ul>'+
1024
						'</div>'+
1025
					'</div>'+
1026
				'</div>'+
1027
		'</div>');
1028
}
1029
 
2410 jpm 1030
function getTextOptionSelectionne(id) {
1031
	var optionVal = $('#' + id).val(),
1032
		optionText = $('#' + id + ' option:selected').text();
2440 jpm 1033
	//console.log(optionVal+'-'+optionText);
2410 jpm 1034
	return ((optionVal === undefined || optionVal === '') ? '' : optionText);
1035
}
1036
 
2406 jpm 1037
function stockerObsData() {
2410 jpm 1038
	var numNomSel = $('#taxon').data('numNomSel'),
1039
		nomSel = $('#taxon').val(),
1040
		nomRet = $('#taxon').data('nomRet'),
1041
		numNomRet = $('#taxon').data('numNomRet'),
1042
		numTaxon = $('#taxon').data('nt'),
1043
		famille = $('#taxon').data('famille'),
1044
		referentiel = (numNomSel == undefined) ? '' : NOM_SCI_REFERENTIEL;
2406 jpm 1045
 
2410 jpm 1046
	$('#liste-obs').data('obsId'+obsNbre, {
1047
		'date' : $('#date').val(),
1048
		'notes' : $('#notes').val().trim(),
2406 jpm 1049
 
2410 jpm 1050
		'nom_sel': nomSel,
1051
		'num_nom_sel': numNomSel,
1052
		'nom_ret': nomRet,
1053
		'num_nom_ret': numNomRet,
1054
		'num_taxon': numTaxon,
1055
		'famille': famille,
1056
		'referentiel': referentiel,
2406 jpm 1057
 
2410 jpm 1058
		'latitude' : $('#latitude').val(),
1059
		'longitude' : $('#longitude').val(),
1060
		'commune_nom' : $('#commune-nom').text(),
1061
		'commune_code_insee' : $('#commune-code-insee').text(),
1062
		'altitude': $('#altitude').text(),
1063
		'lieudit': $('#lieudit').val().trim(),
1064
		'station': $('#station').val().trim(),
1065
		'milieu': $('#milieu').val().trim(),
1066
		'abondance': $('#abondance').val(),
1067
		'phenologie': $('#phenologie').val(),
1068
 
2406 jpm 1069
		//Ajout des champs images
1070
		'image_nom' : getNomsImgsOriginales(),
1071
 
1072
		// Ajout des champs étendus de l'obs
1073
		'obs_etendue': getObsChpEtendus()
1074
	});
1075
}
1076
 
1077
function getObsChpEtendus() {
1078
	var champs = [];
1079
 
1080
	$('.obs-chp-etendu').each(function() {
1081
		var valeur = $(this).val(),
2410 jpm 1082
			cle = $(this).attr('name');
2406 jpm 1083
		if (valeur != '') {
2410 jpm 1084
			var chpEtendu = {cle: cle, valeur: valeur.trim()};
2406 jpm 1085
			champs.push(chpEtendu);
1086
		}
1087
	});
1088
	return champs;
1089
}
1090
 
1091
function surChangementNbreObs() {
1092
	if (obsNbre == 0) {
2410 jpm 1093
		$('#transmettre-obs').attr('disabled', 'disabled');
1094
		$('#ajouter-obs').removeAttr('disabled');
2406 jpm 1095
	} else if (obsNbre > 0 && obsNbre < OBS_MAX_NBRE) {
2410 jpm 1096
		$('#transmettre-obs').removeAttr('disabled');
1097
		$('#ajouter-obs').removeAttr('disabled');
2406 jpm 1098
	} else if (obsNbre >= OBS_MAX_NBRE) {
2410 jpm 1099
		$('#ajouter-obs').attr('disabled', 'disabled');
1100
		afficherPanneau('#dialogue-bloquer-creer-obs');
2406 jpm 1101
	}
1102
}
1103
 
1104
var nbObsEnCours = 1;
1105
var totalObsATransmettre = 0;
1106
function transmettreObs() {
2410 jpm 1107
	var observations = $('#liste-obs').data();
1108
	if (DEBUG) {
1109
		console.log(observations);
1110
	}
2406 jpm 1111
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
2410 jpm 1112
		afficherPanneau('#dialogue-zero-obs');
2406 jpm 1113
	} else {
1114
		nbObsEnCours = 1;
1115
		nbObsTransmises = 0;
1116
		totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
1117
		depilerObsPourEnvoi();
1118
	}
1119
	return false;
1120
}
1121
 
1122
function depilerObsPourEnvoi() {
2410 jpm 1123
	var observations = $('#liste-obs').data();
2406 jpm 1124
	// la boucle est factice car on utilise un tableau
1125
	// dont on a besoin de n'extraire que le premier élément
1126
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
1127
	// TODO: utiliser var.keys quand ça sera plus répandu
1128
	// ou bien utiliser un vrai tableau et pas un objet
1129
	for (var obsNum in observations) {
1130
		obsATransmettre = new Object();
1131
 
1132
	    obsATransmettre['projet'] = TAG_PROJET;
1133
	    obsATransmettre['tag-obs'] = TAG_OBS;
1134
	    obsATransmettre['tag-img'] = TAG_IMG;
1135
 
1136
		var utilisateur = new Object();
2410 jpm 1137
		utilisateur.id_utilisateur = $('#id_utilisateur').val();
1138
		utilisateur.prenom = $('#prenom').val();
1139
		utilisateur.nom = $('#nom').val();
1140
		utilisateur.courriel = $('#courriel').val();
2406 jpm 1141
		obsATransmettre['utilisateur'] = utilisateur;
1142
		obsATransmettre[obsNum] = observations[obsNum];
1143
		var idObsNumerique = obsNum.replace('obsId', '');
1144
		if (idObsNumerique != '') {
1145
			envoyerObsAuCel(idObsNumerique, obsATransmettre);
1146
		}
1147
 
1148
		break;
1149
	}
1150
}
1151
 
1152
var nbObsTransmises = 0;
1153
function mettreAJourProgression() {
1154
	nbObsTransmises++;
1155
	var pct = (nbObsTransmises/totalObsATransmettre)*100;
1156
	$('#barre-progression-upload').attr('aria-valuenow', nbObsTransmises);
2410 jpm 1157
	$('#barre-progression-upload').attr('style', 'width: '+pct+'%');
1158
	$('#barre-progression-upload .sr-only').text(nbObsTransmises+'/'+totalObsATransmettre+' observations transmises');
2406 jpm 1159
 
2410 jpm 1160
	if (obsNbre == 0) {
2406 jpm 1161
		$('.progress').removeClass('active');
1162
		$('.progress').removeClass('progress-striped');
1163
	}
1164
}
1165
 
1166
function envoyerObsAuCel(idObs, observation) {
2410 jpm 1167
	var erreurMsg = '';
2406 jpm 1168
	$.ajax({
1169
		url : SERVICE_SAISIE_URL,
2410 jpm 1170
		type : 'POST',
2406 jpm 1171
		data : observation,
2410 jpm 1172
		dataType : 'json',
2406 jpm 1173
		beforeSend : function() {
2410 jpm 1174
			$('#dialogue-obs-transaction-ko').hide();
1175
			$('#dialogue-obs-transaction-ok').hide();
1176
			$('.alert-txt .msg').remove();
1177
			$('.alert-txt .msg-erreur').remove();
1178
			$('.alert-txt .msg-debug').remove();
1179
			$('#chargement').show();
2406 jpm 1180
		},
1181
		success : function(data, textStatus, jqXHR) {
1182
			// mise à jour du nombre d'obs à transmettre
1183
			// et suppression de l'obs
1184
			supprimerObsParId(idObs);
1185
			nbObsEnCours++;
1186
			// mise à jour du statut
1187
			mettreAJourProgression();
1188
			if(obsNbre > 0) {
1189
				// dépilement de la suivante
1190
				depilerObsPourEnvoi();
1191
			}
1192
		},
1193
		statusCode : {
1194
			500 : function(jqXHR, textStatus, errorThrown) {
1195
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
1196
		    }
1197
		},
1198
		error : function(jqXHR, textStatus, errorThrown) {
1199
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
1200
			try {
1201
				reponse = jQuery.parseJSON(jqXHR.responseText);
1202
				if (reponse != null) {
1203
					$.each(reponse, function (cle, valeur) {
1204
						erreurMsg += valeur + "\n";
1205
					});
1206
				}
1207
			} catch(e) {
1208
				erreurMsg += "L'erreur n'était pas en JSON.";
1209
			}
1210
		},
1211
		complete : function(jqXHR, textStatus) {
1212
			var debugMsg = extraireEnteteDebug(jqXHR);
1213
 
1214
			if (erreurMsg != '') {
1215
				if (DEBUG) {
2410 jpm 1216
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
1217
					$('#dialogue-obs-transaction-ko .alert-txt').append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
2406 jpm 1218
				}
2410 jpm 1219
				var hrefCourriel = 'mailto:cel_remarques@tela-botanica.org?'+
1220
					'subject=Dysfonctionnement du widget de saisie '+TAG_PROJET+
1221
					'&body='+erreurMsg+'%0D%0ADébogage :%0D%0A'+debugMsg;
2406 jpm 1222
 
1223
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1224
				$('#obs'+idObs+' div div').addClass('obs-erreur');
2410 jpm 1225
				window.location.hash = 'obs'+idObs;
2406 jpm 1226
 
2410 jpm 1227
				$('#dialogue-obs-transaction-ko .alert-txt').append($('#tpl-transmission-ko').clone()
2406 jpm 1228
					.find('.courriel-erreur')
1229
					.attr('href', hrefCourriel)
1230
					.end()
1231
					.html());
2410 jpm 1232
				$('#dialogue-obs-transaction-ko').show();
1233
				$('#chargement').hide();
2406 jpm 1234
				initialiserBarreProgression();
1235
			} else {
1236
				if (DEBUG) {
2410 jpm 1237
					$('#dialogue-obs-transaction-ok .alert-txt').append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
2406 jpm 1238
				}
1239
				if(obsNbre == 0) {
1240
					setTimeout(function() {
2410 jpm 1241
						$('#chargement').hide();
2406 jpm 1242
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
2410 jpm 1243
						$('#dialogue-obs-transaction-ok').show();
1244
						window.location.hash = 'dialogue-obs-transaction-ok';
2406 jpm 1245
						initialiserObs();
1246
					}, 1500);
1247
				}
1248
			}
1249
		}
1250
	});
1251
}
1252
 
1253
function validerFormulaire() {
2412 jpm 1254
	var observateur = $('#form-observateur').valid(),
1255
		station = $('#form-station').valid(),
1256
		obsDate = $('#form-obs-date').valid(),
1257
		obs = $('#form-obs').valid();
1258
	return (observateur == true && station == true && obs == true && obsDate == true) ? true : false;
2406 jpm 1259
}
1260
 
1261
function getNomsImgsOriginales() {
1262
	var noms = new Array();
2410 jpm 1263
	$('.miniature-img').each(function() {
2406 jpm 1264
		noms.push($(this).attr('alt'));
1265
	});
1266
	return noms;
1267
}
1268
 
1269
function supprimerObs() {
1270
	var obsId = $(this).val();
1271
	// Problème avec IE 6 et 7
2410 jpm 1272
	if (obsId == 'Supprimer') {
1273
		obsId = $(this).attr('title');
2406 jpm 1274
	}
1275
	supprimerObsParId(obsId);
1276
}
1277
 
1278
function supprimerObsParId(obsId) {
1279
	obsNbre = obsNbre - 1;
2410 jpm 1280
	$('.obs-nbre').text(obsNbre);
1281
	$('.obs-nbre').triggerHandler('changement');
2406 jpm 1282
	$('.obs'+obsId).remove();
2410 jpm 1283
	$('#liste-obs').removeData('obsId'+obsId);
2406 jpm 1284
}
1285
 
1286
function initialiserBarreProgression() {
1287
	$('#barre-progression-upload').attr('aria-valuenow', 0);
2410 jpm 1288
	$('#barre-progression-upload').attr('style', 'width: 0%');
1289
	$('#barre-progression-upload .sr-only').text('0/0 observations transmises');
2406 jpm 1290
	$('.progress').addClass('active');
1291
	$('.progress').addClass('progress-striped');
1292
}
1293
 
1294
function initialiserObs() {
1295
	obsNbre = 0;
1296
	nbObsTransmises = 0;
1297
	nbObsEnCours = 0;
1298
	totalObsATransmettre = 0;
1299
	initialiserBarreProgression();
2410 jpm 1300
	$('.obs-nbre').text(obsNbre);
1301
	$('.obs-nbre').triggerHandler('changement');
1302
	$('#liste-obs').removeData();
2406 jpm 1303
	$('.obs').remove();
2410 jpm 1304
	$('#dialogue-bloquer-creer-obs').hide();
2406 jpm 1305
}
1306
 
1307
function ajouterImgMiniatureAuTransfert() {
1308
	var html = '';
1309
	var miniatures = '';
1310
	var premiere = true;
2410 jpm 1311
	if ($('#miniatures img').length >= 1) {
1312
		$('#miniatures img').each(function() {
2406 jpm 1313
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1314
			premiere = false;
2410 jpm 1315
			var css = $(this).hasClass('b64') ? 'thumbnail b64' : 'thumbnail';
1316
			var src = $(this).attr('src');
1317
			var alt = $(this).attr('alt');
1318
			miniature = '<img class="'+css+' '+visible+'" alt="'+alt+'"src="'+src+'" />';
2406 jpm 1319
			miniatures += miniature;
1320
		});
2410 jpm 1321
		visible = ($('#miniatures img').length > 1) ? '' : 'defilement-miniatures-cache';
2406 jpm 1322
		var html =
1323
			'<div class="defilement-miniatures">'+
2410 jpm 1324
				'<a class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
2406 jpm 1325
				miniatures+
2410 jpm 1326
				'<a class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
2406 jpm 1327
			'</div>';
1328
	} else {
2410 jpm 1329
		html = '<img class="thumbnail" alt="Aucune photo"src="'+PAS_DE_PHOTO_ICONE_URL+'" />';
2406 jpm 1330
	}
1331
	return html;
1332
}
1333
 
1334
function defilerMiniatures(element) {
2410 jpm 1335
	var miniatureSelectionne = element.siblings('img.miniature-selectionnee');
2406 jpm 1336
	miniatureSelectionne.removeClass('miniature-selectionnee');
1337
	miniatureSelectionne.addClass('miniature-cachee');
1338
	var miniatureAffichee = miniatureSelectionne;
1339
 
1340
	if(element.hasClass('defilement-miniatures-gauche')) {
1341
		if(miniatureSelectionne.prev('.miniature').length != 0) {
2410 jpm 1342
			miniatureAffichee = miniatureSelectionne.prev('.thumbnail');
2406 jpm 1343
		} else {
2410 jpm 1344
			miniatureAffichee = miniatureSelectionne.siblings('.thumbnail').last();
2406 jpm 1345
		}
1346
	} else {
1347
		if(miniatureSelectionne.next('.miniature').length != 0) {
2410 jpm 1348
			miniatureAffichee = miniatureSelectionne.next('.thumbnail');
2406 jpm 1349
		} else {
2410 jpm 1350
			miniatureAffichee = miniatureSelectionne.siblings('.thumbnail').first();
2406 jpm 1351
		}
1352
	}
1353
	//console.log(miniatureAffichee);
1354
	miniatureAffichee.addClass('miniature-selectionnee');
1355
	miniatureAffichee.removeClass('miniature-cachee');
1356
}
1357
 
2410 jpm 1358
 
1359
function formaterNumNomSel(numNomSel) {
2406 jpm 1360
	var nn = '';
2410 jpm 1361
	if (numNomSel == undefined) {
2406 jpm 1362
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1363
	} else {
2410 jpm 1364
		nn = '<span class="nn">[nn'+numNomSel+']</span>';
2406 jpm 1365
	}
1366
	return nn;
2410 jpm 1367
}