Subversion Repositories eFlore/Applications.cel

Rev

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

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