Subversion Repositories eFlore/Applications.cel

Rev

Rev 2697 | Rev 2701 | 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();
1356 aurelien 493
	//TODO: mettre ceci en paramètre de config
2700 mathias 494
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;//http://localhost/applications/annuaire/jrest/
1249 jpm 495
	$.ajax({
496
		url : urlAnnuaire,
497
		type : "GET",
498
		success : function(data, textStatus, jqXHR) {
1822 aurelien 499
			//console.log('SUCCESS:'+textStatus);
1249 jpm 500
			if (data != undefined && data[courriel] != undefined) {
501
				var infos = data[courriel];
1352 aurelien 502
				$("#id_utilisateur").val(infos.id);
1249 jpm 503
				$("#prenom").val(infos.prenom);
504
				$("#nom").val(infos.nom);
505
				$("#courriel_confirmation").val(courriel);
506
				$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
507
				$("#date").focus();
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();
1249 jpm 521
		}
1241 jpm 522
	});
2688 mathias 523
};
1210 jpm 524
 
2688 mathias 525
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
1249 jpm 526
	$("#prenom, #nom, #courriel_confirmation").val('');
527
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
2700 mathias 528
	this.afficherPanneau("#dialogue-courriel-introuvable");
2688 mathias 529
};
1210 jpm 530
//+---------------------------------------------------------------------------------------------------------+
2256 aurelien 531
//FORMULAIRE
532
 
2688 mathias 533
WidgetSaisie.prototype.chargerInfoObs = function() {
2700 mathias 534
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
2256 aurelien 535
	$.ajax({
536
		url: urlObs,
537
		type: 'GET',
538
		success: function(data, textStatus, jqXHR) {
539
			if (data != undefined && data != "") {
2688 mathias 540
				this.prechargerForm(data);
2328 jpm 541
			}
2256 aurelien 542
			// TODO: voir s'il est pertinent d'indiquer quelque chose en cas d'erreur ou d'obs
2328 jpm 543
			// inexistante
2256 aurelien 544
		},
545
		error: function(jqXHR, textStatus, errorThrown) {
546
			// TODO: cf TODO ci-dessus
547
		}
548
	});
2688 mathias 549
};
2256 aurelien 550
 
2688 mathias 551
WidgetSaisie.prototype.prechargerForm = function(data) {
2328 jpm 552
 
2256 aurelien 553
	$("#milieu").val(data.milieu);
2328 jpm 554
 
2256 aurelien 555
	$("#carte-recherche").val(data.zoneGeo);
556
	$("#commune-nom").text(data.zoneGeo);
2328 jpm 557
 
2257 aurelien 558
	if(data.hasOwnProperty("codeZoneGeo")) {
559
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
560
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
561
	}
2328 jpm 562
 
2256 aurelien 563
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
564
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
2688 mathias 565
		this.mettreAJourMarkerPosition(latLng);
566
		this.marker.setPosition(latLng);
567
		this.map.setCenter(latLng);
568
		this.map.setZoom(16);
2256 aurelien 569
	}
2688 mathias 570
};
2256 aurelien 571
 
2688 mathias 572
WidgetSaisie.prototype.configurerFormValidator = function() {
1210 jpm 573
	$.validator.addMethod(
2328 jpm 574
		"dateCel",
575
		function (value, element) {
576
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
577
		},
1213 jpm 578
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
1210 jpm 579
	$.extend($.validator.defaults, {
580
		errorClass: "control-group error",
581
		validClass: "control-group success",
582
		errorElement: "span",
1213 jpm 583
		highlight: function(element, errorClass, validClass) {
1210 jpm 584
			if (element.type === 'radio') {
585
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
2328 jpm 586
			} else {
1210 jpm 587
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
588
			}
589
		},
1213 jpm 590
		unhighlight: function(element, errorClass, validClass) {
1210 jpm 591
			if (element.type === 'radio') {
592
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
593
			} else {
1213 jpm 594
				if ($(element).attr('id') == 'taxon') {
1493 aurelien 595
					if ($("#taxon").val() != '') {
596
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
2688 mathias 597
						if ($("#taxon").data("value") != $("#taxon").val()) {
1493 aurelien 598
							$("#taxon").data("numNomSel","");
599
							$("#taxon").data("nomRet","");
600
							$("#taxon").data("numNomRet","");
601
							$("#taxon").data("nt","");
602
							$("#taxon").data("famille","");
1213 jpm 603
						}
1493 aurelien 604
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
605
						$(element).next(" span.help-inline").remove();
1213 jpm 606
					}
607
				} else {
608
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
609
					$(element).next(" span.help-inline").remove();
610
				}
1210 jpm 611
			}
612
		}
613
	});
2688 mathias 614
};
1249 jpm 615
 
2688 mathias 616
WidgetSaisie.prototype.definirReglesFormValidator = function() {
1210 jpm 617
	$("#form-observateur").validate({
618
		rules: {
619
			courriel : {
620
				required : true,
621
				email : true},
622
			courriel_confirmation : {
623
				required : true,
624
				equalTo: "#courriel"}
625
		}
626
	});
627
	$("#form-station").validate({
628
		rules: {
629
			latitude : {
630
				range: [-90, 90]},
631
			longitude : {
632
				range: [-180, 180]}
633
		}
634
	});
635
	$("#form-obs").validate({
636
		rules: {
1213 jpm 637
			date : "dateCel",
1210 jpm 638
			taxon : "required"
639
		}
640
	});
2688 mathias 641
};
1249 jpm 642
 
2688 mathias 643
WidgetSaisie.prototype.configurerDatePicker = function() {
1249 jpm 644
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
645
	$("#date").datepicker({
1990 jpm 646
		dateFormat: "dd/mm/yy",
647
		maxDate: new Date,
1249 jpm 648
		showOn: "button",
1990 jpm 649
		buttonImageOnly: true,
2700 mathias 650
		buttonImage: this.calendrierIconeUrl,
1249 jpm 651
		buttonText: "Afficher le calendrier pour saisir la date.",
652
		showButtonPanel: true
1210 jpm 653
	});
1249 jpm 654
	$("img.ui-datepicker-trigger").appendTo("#date-icone");
2688 mathias 655
};
1249 jpm 656
 
2688 mathias 657
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1249 jpm 658
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
2688 mathias 659
};
1249 jpm 660
 
2688 mathias 661
WidgetSaisie.prototype.formaterNom = function() {
1249 jpm 662
	$(this).val($(this).val().toUpperCase());
2688 mathias 663
};
1249 jpm 664
 
2688 mathias 665
WidgetSaisie.prototype.formaterPrenom = function() {
1249 jpm 666
	var prenom = new Array();
667
	var mots = $(this).val().split(' ');
668
	for (var i = 0; i < mots.length; i++) {
669
		var mot = mots[i];
670
		if (mot.indexOf('-') >= 0) {
671
			var prenomCompose = new Array();
672
			var motsComposes = mot.split('-');
673
		    for (var j = 0; j < motsComposes.length; j++) {
674
		    	var motSimple = motsComposes[j];
675
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
676
		    	prenomCompose.push(motMajuscule);
677
		    }
678
		    prenom.push(prenomCompose.join('-'));
679
		} else {
680
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
681
			prenom.push(motMajuscule);
682
		}
683
	}
684
	$(this).val(prenom.join(' '));
2688 mathias 685
};
1249 jpm 686
 
2688 mathias 687
WidgetSaisie.prototype.basculerAffichageAide = function()  {
1249 jpm 688
	if ($(this).hasClass('btn-warning')) {
689
		$("[rel=tooltip]").tooltip('enable');
690
		$(this).removeClass('btn-warning').addClass('btn-success');
691
		$('#btn-aide-txt', this).text("Désactiver l'aide");
692
	} else {
693
		$("[rel=tooltip]").tooltip('disable');
694
		$(this).removeClass('btn-success').addClass('btn-warning');
695
		$('#btn-aide-txt', this).text("Activer l'aide");
696
	}
2688 mathias 697
};
1249 jpm 698
 
2688 mathias 699
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
2700 mathias 700
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
1249 jpm 701
	return false;
2688 mathias 702
};
1249 jpm 703
 
2688 mathias 704
WidgetSaisie.prototype.basculerAffichageCoord = function() {
1249 jpm 705
	$("a.afficher-coord").toggle();
706
	$("#coordonnees-geo").toggle('slow');
707
	//valeur false pour que le lien ne soit pas suivi
708
	return false;
2688 mathias 709
};
1249 jpm 710
 
2688 mathias 711
/**
712
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
713
 */
714
WidgetSaisie.prototype.ajouterObs = function() {
715
	if (this.validerFormulaire() == true) {
716
		this.obsNbre = this.obsNbre + 1;
717
		$(".obs-nbre").text(this.obsNbre);
1249 jpm 718
		$(".obs-nbre").triggerHandler('changement');
2688 mathias 719
		this.afficherObs();
720
		this.stockerObsData();
721
		this.supprimerMiniatures();
2700 mathias 722
		if(! this.especeImposee) {
1856 aurelien 723
			$("#taxon").val("");
724
			$("#taxon").data("numNomSel",undefined);
725
		}
2688 mathias 726
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
727
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
1249 jpm 728
	} else {
2700 mathias 729
		this.afficherPanneau('#dialogue-form-invalide');
1249 jpm 730
	}
2688 mathias 731
};
1249 jpm 732
 
2688 mathias 733
/**
734
 * Affiche une observation dans la liste des observations à transmettre
735
 */
736
WidgetSaisie.prototype.afficherObs = function() {
1249 jpm 737
	$("#liste-obs").prepend(
2688 mathias 738
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
1249 jpm 739
			'<div class="span12">'+
1253 jpm 740
				'<div class="well">'+
741
					'<div class="obs-action pull-right" rel="tooltip" data-placement="bottom" '+
742
						'title="Supprimer cette observation de la liste à transmettre">'+
2688 mathias 743
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
1249 jpm 744
							'<i class="icon-trash icon-white"></i>'+
745
						'</button>'+
2328 jpm 746
					'</div> '+
747
					'<div class="row-fluid">'+
1249 jpm 748
						'<div class="thumbnail span2">'+
2688 mathias 749
						this.ajouterImgMiniatureAuTransfert()+
1240 jpm 750
						'</div>'+
1249 jpm 751
						'<div class="span9">'+
752
							'<ul class="unstyled">'+
753
								'<li>'+
754
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
2688 mathias 755
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
2700 mathias 756
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
1249 jpm 757
									' observé à '+
758
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
759
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
760
									' le '+
761
									'<span class="date">'+$("#date").val()+'</span>'+
762
								'</li>'+
763
								'<li>'+
764
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
765
									'<span>Station :</span> '+$('#station').val()+' '+
766
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
767
								'</li>'+
768
								'<li>'+
769
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
770
								'</li>'+
771
							'</ul>'+
772
						'</div>'+
1237 jpm 773
					'</div>'+
1249 jpm 774
				'</div>'+
775
			'</div>'+
776
		'</div>');
2688 mathias 777
};
1249 jpm 778
 
2688 mathias 779
WidgetSaisie.prototype.stockerObsData = function() {
780
	var lthis = this;
781
	$("#liste-obs").data('obsId'+this.obsNbre, {
2328 jpm 782
		'date' : $("#date").val(),
1249 jpm 783
		'notes' : $("#notes").val(),
2328 jpm 784
 
1249 jpm 785
		'nom_sel' : $("#taxon").val(),
786
		'num_nom_sel' : $("#taxon").data("numNomSel"),
787
		'nom_ret' : $("#taxon").data("nomRet"),
788
		'num_nom_ret' : $("#taxon").data("numNomRet"),
789
		'num_taxon' : $("#taxon").data("nt"),
790
		'famille' : $("#taxon").data("famille"),
2700 mathias 791
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
2328 jpm 792
 
1249 jpm 793
		'latitude' : $("#latitude").val(),
794
		'longitude' : $("#longitude").val(),
795
		'commune_nom' : $("#commune-nom").text(),
796
		'commune_code_insee' : $("#commune-code-insee").text(),
1251 jpm 797
		'lieudit' : $("#lieudit").val(),
1249 jpm 798
		'station' : $("#station").val(),
799
		'milieu' : $("#milieu").val(),
2328 jpm 800
 
1249 jpm 801
		//Ajout des champs images
2688 mathias 802
		'image_nom' : lthis.getNomsImgsOriginales(),
803
		'image_b64' : lthis.getB64ImgsOriginales()
1210 jpm 804
	});
2688 mathias 805
};
1249 jpm 806
 
2688 mathias 807
WidgetSaisie.prototype.surChangementReferentiel = function() {
2700 mathias 808
	this.nomSciReferentiel = $('#referentiel').val();
1476 aurelien 809
	$('#taxon').val('');
2688 mathias 810
	this.initialiserAutocompleteCommune();
811
	this.initialiserGoogleMap();
812
};
1476 aurelien 813
 
2688 mathias 814
WidgetSaisie.prototype.surChangementNbreObs = function() {
815
	if (this.obsNbre == 0) {
1249 jpm 816
		$("#transmettre-obs").attr('disabled', 'disabled');
817
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 818
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
1249 jpm 819
		$("#transmettre-obs").removeAttr('disabled');
820
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 821
	} else if (this.obsNbre >= this.obsMaxNbre) {
1249 jpm 822
		$("#ajouter-obs").attr('disabled', 'disabled');
2700 mathias 823
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
1249 jpm 824
	}
2688 mathias 825
};
1249 jpm 826
 
2688 mathias 827
WidgetSaisie.prototype.transmettreObs = function() {
1249 jpm 828
	var observations = $("#liste-obs").data();
829
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
2700 mathias 830
		this.afficherPanneau("#dialogue-zero-obs");
1249 jpm 831
	} else {
2688 mathias 832
		this.nbObsEnCours = 1;
833
		this.nbObsTransmises = 0;
834
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
835
		this.depilerObsPourEnvoi();
2110 aurelien 836
	}
837
	return false;
2688 mathias 838
};
2110 aurelien 839
 
2688 mathias 840
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
2110 aurelien 841
	var observations = $("#liste-obs").data();
842
	// la boucle est factice car on utilise un tableau
843
	// dont on a besoin de n'extraire que le premier élément
844
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
845
	// TODO: utiliser var.keys quand ça sera plus répandu
846
	// ou bien utiliser un vrai tableau et pas un objet
2328 jpm 847
	for (var obsNum in observations) {
2697 mathias 848
		var obsATransmettre = {
2700 mathias 849
			'projet' : this.tagProjet,
850
			'tag-obs' : this.tagObs,
851
			'tag-img' : this.tagImg
2688 mathias 852
		};
2697 mathias 853
		var utilisateur = {
854
			id_utilisateur : $("#id_utilisateur").val(),
855
			prenom : $("#prenom").val(),
856
			nom : $("#nom").val(),
857
			courriel : $("#courriel").val()
858
		};
2110 aurelien 859
		obsATransmettre['utilisateur'] = utilisateur;
860
		obsATransmettre[obsNum] = observations[obsNum];
861
		var idObsNumerique = obsNum.replace('obsId', '');
862
		if(idObsNumerique != "") {
2688 mathias 863
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
2110 aurelien 864
		}
2328 jpm 865
 
2110 aurelien 866
		break;
1249 jpm 867
	}
2700 mathias 868
	$('#zone-liste-obs').addClass("hidden");
2688 mathias 869
};
1249 jpm 870
 
2688 mathias 871
WidgetSaisie.prototype.mettreAJourProgression = function() {
872
	this.nbObsTransmises++;
873
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
874
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
2110 aurelien 875
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
2688 mathias 876
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
2110 aurelien 877
 
2688 mathias 878
	if(this.obsNbre == 0) {
2110 aurelien 879
		$('.progress').removeClass('active');
880
		$('.progress').removeClass('progress-striped');
881
	}
2688 mathias 882
};
2110 aurelien 883
 
2688 mathias 884
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
885
	var lthis = this;
1249 jpm 886
	var erreurMsg = "";
887
	$.ajax({
2700 mathias 888
		url : lthis.serviceSaisieUrl,
1249 jpm 889
		type : "POST",
2110 aurelien 890
		data : observation,
1249 jpm 891
		dataType : "json",
892
		beforeSend : function() {
1251 jpm 893
			$("#dialogue-obs-transaction-ko").hide();
894
			$("#dialogue-obs-transaction-ok").hide();
2697 mathias 895
			$('.alert-txt').empty();
1249 jpm 896
			$("#chargement").show();
897
		},
898
		success : function(data, textStatus, jqXHR) {
2110 aurelien 899
			// mise à jour du nombre d'obs à transmettre
900
			// et suppression de l'obs
2688 mathias 901
			lthis.supprimerObsParId(idObs);
2700 mathias 902
			lthis.nbObsEnCours++;
2110 aurelien 903
			// mise à jour du statut
2688 mathias 904
			lthis.mettreAJourProgression();
2700 mathias 905
			if(lthis.obsNbre > 0) {
2110 aurelien 906
				// dépilement de la suivante
2688 mathias 907
				lthis.depilerObsPourEnvoi();
2110 aurelien 908
			}
1249 jpm 909
		},
910
		statusCode : {
911
			500 : function(jqXHR, textStatus, errorThrown) {
912
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
913
		    }
914
		},
915
		error : function(jqXHR, textStatus, errorThrown) {
916
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
917
			try {
918
				reponse = jQuery.parseJSON(jqXHR.responseText);
919
				if (reponse != null) {
920
					$.each(reponse, function (cle, valeur) {
921
						erreurMsg += valeur + "\n";
922
					});
923
				}
924
			} catch(e) {
2700 mathias 925
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
1249 jpm 926
			}
927
		},
928
		complete : function(jqXHR, textStatus) {
929
			var debugMsg = extraireEnteteDebug(jqXHR);
2328 jpm 930
 
1249 jpm 931
			if (erreurMsg != '') {
2700 mathias 932
				if (this.debug) {
1249 jpm 933
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
934
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
1210 jpm 935
				}
1901 mathias 936
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
2700 mathias 937
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
1902 mathias 938
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
2328 jpm 939
 
2110 aurelien 940
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
941
				$('#obs'+idObs+' div div').addClass('obs-erreur');
942
				window.location.hash = "obs"+idObs;
2328 jpm 943
 
1249 jpm 944
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
945
					.find('.courriel-erreur')
946
					.attr('href', hrefCourriel)
947
					.end()
948
					.html());
949
				$("#dialogue-obs-transaction-ko").show();
2110 aurelien 950
				$("#chargement").hide();
2688 mathias 951
				lthis.initialiserBarreProgression();
1249 jpm 952
			} else {
2700 mathias 953
				if (lthis.debug) {
1249 jpm 954
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
955
				}
2700 mathias 956
				if(lthis.obsNbre == 0) {
2110 aurelien 957
					setTimeout(function() {
958
						$("#chargement").hide();
959
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
960
						$("#dialogue-obs-transaction-ok").show();
2117 aurelien 961
						window.location.hash = "dialogue-obs-transaction-ok";
2688 mathias 962
						lthis.initialiserObs();
2110 aurelien 963
					}, 1500);
2328 jpm 964
 
965
				}
1251 jpm 966
			}
1210 jpm 967
		}
968
	});
2688 mathias 969
};
1210 jpm 970
 
2688 mathias 971
WidgetSaisie.prototype.validerFormulaire = function() {
1210 jpm 972
	$observateur = $("#form-observateur").valid();
973
	$station = $("#form-station").valid();
974
	$obs = $("#form-obs").valid();
975
	return ($observateur == true && $station == true && $obs == true) ? true : false;
2688 mathias 976
};
1210 jpm 977
 
2688 mathias 978
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1524 aurelien 979
	var noms = new Array();
980
	$(".miniature-img").each(function() {
981
		noms.push($(this).attr('alt'));
982
	});
983
	return noms;
2688 mathias 984
};
1524 aurelien 985
 
2688 mathias 986
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1524 aurelien 987
	var b64 = new Array();
988
	$(".miniature-img").each(function() {
989
		if ($(this).hasClass('b64')) {
990
			b64.push($(this).attr('src'));
991
		} else if ($(this).hasClass('b64-canvas')) {
992
			b64.push($(this).data('b64'));
993
		}
994
	});
995
 
1210 jpm 996
	return b64;
2688 mathias 997
};
1210 jpm 998
 
2688 mathias 999
WidgetSaisie.prototype.supprimerObs = function(selector) {
1000
	var obsId = $(selector).val();
1210 jpm 1001
	// Problème avec IE 6 et 7
1002
	if (obsId == "Supprimer") {
2688 mathias 1003
		obsId = $(selector).attr("title");
1210 jpm 1004
	}
2688 mathias 1005
	this.supprimerObsParId(obsId);
1006
};
2110 aurelien 1007
 
2688 mathias 1008
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1009
	this.obsNbre = this.obsNbre - 1;
1010
	$(".obs-nbre").text(this.obsNbre);
1237 jpm 1011
	$(".obs-nbre").triggerHandler('changement');
1215 jpm 1012
	$('.obs'+obsId).remove();
1210 jpm 1013
	$("#liste-obs").removeData('obsId'+obsId);
2688 mathias 1014
};
1210 jpm 1015
 
2688 mathias 1016
WidgetSaisie.prototype.initialiserBarreProgression = function() {
2110 aurelien 1017
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1018
	$('#barre-progression-upload').attr('style', "width: 0%");
1019
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1020
	$('.progress').addClass('active');
1021
	$('.progress').addClass('progress-striped');
2688 mathias 1022
};
2110 aurelien 1023
 
2688 mathias 1024
WidgetSaisie.prototype.initialiserObs = function() {
1025
	this.obsNbre = 0;
1026
	this.nbObsTransmises = 0;
1027
	this.nbObsEnCours = 0;
1028
	this.totalObsATransmettre = 0;
1029
	this.initialiserBarreProgression();
1030
	$(".obs-nbre").text(this.obsNbre);
1249 jpm 1031
	$(".obs-nbre").triggerHandler('changement');
1032
	$("#liste-obs").removeData();
1033
	$('.obs').remove();
1034
	$("#dialogue-bloquer-creer-obs").hide();
2688 mathias 1035
};
1231 jpm 1036
 
2688 mathias 1037
/**
1038
 * Ajoute une boîte de miniatures avec défilement des images,
1039
 * pour une obs de la liste des obs à transmettre
1040
 */
1041
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1042
	var html = '',
1043
		miniatures = '',
1044
		premiere = true;
1524 aurelien 1045
	if ($("#miniatures img").length >= 1) {
1046
		$("#miniatures img").each(function() {
1047
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1048
			premiere = false;
2688 mathias 1049
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1050
				src = $(this).attr("src"),
1051
				alt = $(this).attr("alt"),
1052
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1053
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1524 aurelien 1054
			miniatures += miniature;
1055
		});
1056
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
2328 jpm 1057
		var html =
1524 aurelien 1058
			'<div class="defilement-miniatures">'+
1059
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1060
				miniatures+
1061
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1062
			'</div>';
1237 jpm 1063
	} else {
2700 mathias 1064
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1210 jpm 1065
	}
1524 aurelien 1066
	return html;
2688 mathias 1067
};
1210 jpm 1068
 
2688 mathias 1069
WidgetSaisie.prototype.defilerMiniatures = function(element) {
2328 jpm 1070
 
2688 mathias 1071
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1524 aurelien 1072
	miniatureSelectionne.removeClass('miniature-selectionnee');
1073
	miniatureSelectionne.addClass('miniature-cachee');
1074
	var miniatureAffichee = miniatureSelectionne;
2328 jpm 1075
 
1524 aurelien 1076
	if(element.hasClass('defilement-miniatures-gauche')) {
1077
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1078
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1079
		} else {
1080
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1081
		}
1082
	} else {
1083
		if(miniatureSelectionne.next('.miniature').length != 0) {
1084
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1085
		} else {
1086
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1087
		}
1088
	}
1822 aurelien 1089
	//console.log(miniatureAffichee);
1524 aurelien 1090
	miniatureAffichee.addClass('miniature-selectionnee');
1091
	miniatureAffichee.removeClass('miniature-cachee');
2688 mathias 1092
};
1524 aurelien 1093
 
2688 mathias 1094
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1240 jpm 1095
	var nn = '';
1096
	if ($("#taxon").data("numNomSel") == undefined) {
1097
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1098
	} else {
1099
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1100
	}
1101
	return nn;
2688 mathias 1102
};
1240 jpm 1103
 
2688 mathias 1104
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1105
	var lthis = this;
1210 jpm 1106
	$('#taxon').autocomplete({
2328 jpm 1107
		source: function(requete, add){
1210 jpm 1108
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1109
			requete = "";
2343 aurelien 1110
			if($("#referentiel").val() != "autre") {
2688 mathias 1111
				var url = lthis.getUrlAutocompletionNomsSci();
2343 aurelien 1112
				$.getJSON(url, requete, function(data) {
2688 mathias 1113
					var suggestions = lthis.traiterRetourNomsSci(data);
2343 aurelien 1114
					add(suggestions);
1115
	            });
1116
			}
1210 jpm 1117
        },
1118
        html: true
1119
	});
2328 jpm 1120
 
1213 jpm 1121
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1215 jpm 1122
		$("#taxon").data(ui.item);
1123
		if (ui.item.retenu == true) {
1124
			$("#taxon").addClass('ns-retenu');
1125
		} else {
1126
			$("#taxon").removeClass('ns-retenu');
1127
		}
1213 jpm 1128
	});
2688 mathias 1129
};
1210 jpm 1130
 
2688 mathias 1131
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1215 jpm 1132
	var mots = $('#taxon').val();
2700 mathias 1133
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1476 aurelien 1134
	url = url.replace('{masque}', mots);
1210 jpm 1135
	return url;
2688 mathias 1136
};
1210 jpm 1137
 
2688 mathias 1138
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
2328 jpm 1139
	var suggestions = [];
1210 jpm 1140
	if (data.resultat != undefined) {
1141
		$.each(data.resultat, function(i, val) {
1142
			val.nn = i;
2328 jpm 1143
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1215 jpm 1144
				nomRet : '', numNomRet : '', famille : '', retenu : false
1145
			};
2700 mathias 1146
			if (suggestions.length >= this.autocompletionElementsNbre) {
1213 jpm 1147
				nom.label = "...";
1148
				nom.value = $('#taxon').val();
1149
				suggestions.push(nom);
1150
				return false;
1151
			} else {
1231 jpm 1152
				nom.label = val.nom_sci_complet;
1153
				nom.value = val.nom_sci_complet;
1215 jpm 1154
				nom.nt = val.num_taxonomique;
1155
				nom.nomSel = val.nom_sci;
1156
				nom.nomSelComplet = val.nom_sci_complet;
1157
				nom.numNomSel = val.nn;
1237 jpm 1158
				nom.nomRet = val.nom_retenu_complet;
1220 jpm 1159
				nom.numNomRet = val["nom_retenu.id"];
1231 jpm 1160
				nom.famille = val.famille;
2243 mathias 1161
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1162
				// en tout cas c'est harmonisé avec le CeL
1163
				nom.retenu = (val.retenu == 'true') ? true : false;
2328 jpm 1164
 
1213 jpm 1165
				suggestions.push(nom);
2328 jpm 1166
			}
1210 jpm 1167
		});
1168
	}
2328 jpm 1169
 
1210 jpm 1170
	return suggestions;
2688 mathias 1171
};
1210 jpm 1172
 
2700 mathias 1173
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1174
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
1175
}
1176
 
2697 mathias 1177
// lib hors objet --
1178
 
1179
/**
1180
* Stope l'évènement courant quand on clique sur un lien.
1181
* Utile pour Chrome, Safari...
1182
*/
1183
function arreter(evenement) {
1184
	if (evenement.stopPropagation) {
1185
		evenement.stopPropagation();
1186
	}
1187
	if (evenement.preventDefault) {
1188
		evenement.preventDefault();
1189
	}
1190
	return false;
1191
}
1192
 
1193
/**
1194
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1195
 * @param jqXHR
1196
 * @returns {String}
1197
 */
1198
function extraireEnteteDebug(jqXHR) {
1199
	var msgDebug = '';
1200
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1201
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1202
		if (debugInfos != null) {
1203
			$.each(debugInfos, function (cle, valeur) {
1204
				msgDebug += valeur + "\n";
1205
			});
1206
		}
1207
	}
1208
	return msgDebug;
1209
}
1210
 
1210 jpm 1211
/*
1212
 * jQuery UI Autocomplete HTML Extension
1213
 *
1214
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1215
 * Dual licensed under the MIT or GPL Version 2 licenses.
1216
 *
1217
 * http://github.com/scottgonzalez/jquery-ui-extensions
2328 jpm 1218
 *
1210 jpm 1219
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1220
 */
1221
(function( $ ) {
1215 jpm 1222
	var proto = $.ui.autocomplete.prototype,
1223
		initSource = proto._initSource;
2328 jpm 1224
 
2688 mathias 1225
	WidgetSaisie.prototype.filter = function( array, term ) {
1215 jpm 1226
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1227
		return $.grep( array, function(value) {
1228
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1229
		});
1230
	}
2328 jpm 1231
 
1215 jpm 1232
	$.extend( proto, {
1233
		_initSource: function() {
1234
			if ( this.options.html && $.isArray(this.options.source) ) {
1235
				this.source = function( request, response ) {
1236
					response( filter( this.options.source, request.term ) );
1237
				};
1238
			} else {
1239
				initSource.call( this );
1240
			}
1241
		},
1242
		_renderItem: function( ul, item) {
1243
			if (item.retenu == true) {
1244
				item.label = "<strong>"+item.label+"</strong>";
1245
			}
2328 jpm 1246
 
1215 jpm 1247
			return $( "<li></li>" )
1248
				.data( "item.autocomplete", item )
1249
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1250
				.appendTo( ul );
1251
		}
1210 jpm 1252
	});
1253
})( jQuery );