Subversion Repositories eFlore/Applications.cel

Rev

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

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