Subversion Repositories eFlore/Applications.cel

Rev

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