Subversion Repositories eFlore/Applications.cel

Rev

Rev 2710 | 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
 
2688 mathias 312
WidgetSaisie.prototype.initialiserGoogleMap = function() {
313
	var latLng,
314
		zoomDefaut;
2553 mathias 315
	// Carte @TODO mettre ça dans la config
2700 mathias 316
	if(this.nomSciReferentiel == 'bdtre') {
2688 mathias 317
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
318
		zoomDefaut = 7;
2700 mathias 319
	} else if(this.nomSciReferentiel == 'lbf') {
2688 mathias 320
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
321
		zoomDefaut = 7;
2700 mathias 322
	} else if(this.nomSciReferentiel == 'bdtxa') {
2688 mathias 323
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
324
		zoomDefaut = 8;
2700 mathias 325
	} else if(this.nomSciReferentiel == 'isfan') {
2688 mathias 326
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
327
		zoomDefaut = 4;
2700 mathias 328
	} else if(this.nomSciReferentiel == 'apd') {
2688 mathias 329
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
330
		zoomDefaut = 4;
1476 aurelien 331
	} else {
2688 mathias 332
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France
333
		zoomDefaut = 5;
1476 aurelien 334
	}
2328 jpm 335
 
1210 jpm 336
	var options = {
1476 aurelien 337
		zoom: zoomDefaut,
1210 jpm 338
		center: latLng,
339
		mapTypeId: google.maps.MapTypeId.HYBRID,
340
		mapTypeControlOptions: {
341
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
342
	};
343
 
344
	// Ajout de la couche OSM à la carte
345
	osmMapType = new google.maps.ImageMapType({
346
		getTileUrl: function(coord, zoom) {
347
			return "http://tile.openstreetmap.org/" +
348
			zoom + "/" + coord.x + "/" + coord.y + ".png";
349
		},
350
		tileSize: new google.maps.Size(256, 256),
351
		isPng: true,
352
		alt: 'OpenStreetMap',
353
		name: 'OSM',
354
		maxZoom: 19
355
	});
2328 jpm 356
 
1210 jpm 357
	// Création de la carte Google
2688 mathias 358
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
359
	this.map.mapTypes.set('OSM', osmMapType);
2328 jpm 360
 
1216 jpm 361
	// Création du Geocoder
2688 mathias 362
	this.geocoder = new google.maps.Geocoder();
2328 jpm 363
 
1210 jpm 364
	// Marqueur google draggable
2688 mathias 365
	this.marker = new google.maps.Marker({
366
		map: this.map,
1210 jpm 367
		draggable: true,
368
		title: 'Ma station',
2700 mathias 369
		icon: this.googleMapMarqueurUrl,
1210 jpm 370
		position: latLng
371
	});
2328 jpm 372
 
2688 mathias 373
	this.initialiserMarker(latLng);
2328 jpm 374
 
1210 jpm 375
	// Tentative de geocalisation
376
	if (navigator.geolocation) {
377
		navigator.geolocation.getCurrentPosition(function(position) {
378
			var latitude = position.coords.latitude;
379
			var longitude = position.coords.longitude;
2688 mathias 380
			this.latLng = new google.maps.LatLng(latitude, longitude);
381
			this.deplacerMarker(this.latLng);
1210 jpm 382
		});
383
	}
2127 mathias 384
 
385
	// intéraction carte
2688 mathias 386
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
387
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
388
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
389
};
1210 jpm 390
 
2688 mathias 391
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
392
	if (this.marker != undefined) {
393
		this.marker.setPosition(latLng);
394
		this.map.setCenter(latLng);
2710 mathias 395
		// @WARNING TEST
396
		this.mettreAJourMarkerPosition(latLng);
1485 aurelien 397
	}
2688 mathias 398
};
1485 aurelien 399
 
2688 mathias 400
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
401
	if (this.marker != undefined) {
402
		this.marker.setPosition(latLng);
403
		this.map.setCenter(latLng);
404
		this.mettreAJourMarkerPosition(latLng);
405
		this.trouverCommune(latLng);
1210 jpm 406
	}
2688 mathias 407
};
1210 jpm 408
 
2688 mathias 409
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
1210 jpm 410
	var lat = latLng.lat().toFixed(5);
2328 jpm 411
	var lng = latLng.lng().toFixed(5);
2688 mathias 412
	this.remplirChampLatitude(lat);
413
	this.remplirChampLongitude(lng);
414
};
1210 jpm 415
 
2688 mathias 416
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
1210 jpm 417
	var lat = Math.round(latDecimale * 100000) / 100000;
418
	$('#latitude').val(lat);
2688 mathias 419
};
1210 jpm 420
 
2688 mathias 421
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
1210 jpm 422
	var lng = Math.round(lngDecimale * 100000) / 100000;
423
	$('#longitude').val(lng);
2688 mathias 424
};
1210 jpm 425
 
2688 mathias 426
WidgetSaisie.prototype.trouverCommune = function(pos) {
2700 mathias 427
	var lthis = this;
1210 jpm 428
	$(function() {
2328 jpm 429
 
2700 mathias 430
		var url_service = lthis.serviceNomCommuneUrl;
2328 jpm 431
 
1476 aurelien 432
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
1210 jpm 433
		$.ajax({
434
			url : urlNomCommuneFormatee,
435
			type : "GET",
436
			dataType : "jsonp",
437
			beforeSend : function() {
2328 jpm 438
				$(".commune-info").empty();
1220 jpm 439
				$("#dialogue-erreur .alert-txt").empty();
1210 jpm 440
			},
441
			success : function(data, textStatus, jqXHR) {
442
				$(".commune-info").empty();
443
				$("#commune-nom").append(data.nom);
444
				$("#commune-code-insee").append(data.codeINSEE);
445
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
446
			},
447
			statusCode : {
448
			    500 : function(jqXHR, textStatus, errorThrown) {
2700 mathias 449
					if (this.debug) {
1220 jpm 450
						$("#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 451
						reponse = jQuery.parseJSON(jqXHR.responseText);
452
						var erreurMsg = "";
453
						if (reponse != null) {
454
							$.each(reponse, function (cle, valeur) {
455
								erreurMsg += valeur + "<br />";
456
							});
457
						}
2328 jpm 458
 
1220 jpm 459
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
1210 jpm 460
					}
461
			    }
462
			},
463
			error : function(jqXHR, textStatus, errorThrown) {
2700 mathias 464
				if (this.debug) {
2707 mathias 465
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la recherche de la commune.</p>');
1210 jpm 466
					reponse = jQuery.parseJSON(jqXHR.responseText);
467
					var erreurMsg = "";
468
					if (reponse != null) {
469
						$.each(reponse, function (cle, valeur) {
470
							erreurMsg += valeur + "<br />";
471
						});
472
					}
2328 jpm 473
 
1220 jpm 474
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
1210 jpm 475
				}
476
			},
477
			complete : function(jqXHR, textStatus) {
1249 jpm 478
				var debugMsg = extraireEnteteDebug(jqXHR);
479
				if (debugMsg != '') {
2700 mathias 480
					if (this.debug) {
1220 jpm 481
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
1210 jpm 482
					}
483
				}
484
				if ($("#dialogue-erreur .msg").length > 0) {
1220 jpm 485
					$("#dialogue-erreur").show();
1210 jpm 486
				}
487
			}
488
		});
489
	});
2688 mathias 490
};
1249 jpm 491
 
2688 mathias 492
WidgetSaisie.prototype.testerLancementRequeteIdentite = function(event) {
1249 jpm 493
	if (event.which == 13) {
2688 mathias 494
		this.requeterIdentite();
495
		this.event.preventDefault();
496
		this.event.stopPropagation();
1249 jpm 497
	}
2688 mathias 498
};
1249 jpm 499
 
2688 mathias 500
WidgetSaisie.prototype.requeterIdentite = function() {
501
	var lthis = this;
1249 jpm 502
	var courriel = $("#courriel").val();
2701 mathias 503
	var urlAnnuaire = this.serviceAnnuaireIdUrl + courriel;
2709 mathias 504
	if (courriel != '') {
505
		$.ajax({
506
			url : urlAnnuaire,
507
			type : "GET",
508
			success : function(data, textStatus, jqXHR) {
2710 mathias 509
				if (lthis.debug) {
510
					console.log('SUCCESS: '+textStatus);
511
				}
2709 mathias 512
				if (data != undefined && data[courriel] != undefined) {
513
					var infos = data[courriel];
2710 mathias 514
					lthis.surSuccesCompletionCourriel(infos, courriel);
2709 mathias 515
				} else {
516
					lthis.surErreurCompletionCourriel();
517
				}
518
			},
519
			error : function(jqXHR, textStatus, errorThrown) {
2710 mathias 520
				if (lthis.debug) {
521
					console.log('ERREUR: '+textStatus);
522
				}
2688 mathias 523
				lthis.surErreurCompletionCourriel();
2709 mathias 524
			},
525
			complete : function(jqXHR, textStatus) {
2710 mathias 526
				if (lthis.debug) {
527
					console.log('COMPLETE: '+textStatus);
528
				}
2709 mathias 529
				// @TODO harmoniser class="hidden" VS style="display:none;"
530
				$("#zone-prenom-nom").removeClass("hidden").show();
531
				$("#zone-courriel-confirmation").removeClass("hidden").show();
1241 jpm 532
			}
2709 mathias 533
		});
534
	}
2688 mathias 535
};
1210 jpm 536
 
2710 mathias 537
WidgetSaisie.prototype.surSuccesCompletionCourriel = function(infos, courriel) {
538
	$("#id_utilisateur").val(infos.id);
539
	$("#prenom").val(infos.prenom);
540
	$("#nom").val(infos.nom);
541
	$("#courriel_confirmation").val(courriel);
542
	$("#prenom, #nom, #courriel_confirmation").attr('disabled', 'disabled');
543
	this.focusChampFormulaire();
544
	this.masquerPanneau("#dialogue-courriel-introuvable");
545
};
2707 mathias 546
 
2688 mathias 547
WidgetSaisie.prototype.surErreurCompletionCourriel = function() {
1249 jpm 548
	$("#prenom, #nom, #courriel_confirmation").val('');
549
	$("#prenom, #nom, #courriel_confirmation").removeAttr('disabled');
2700 mathias 550
	this.afficherPanneau("#dialogue-courriel-introuvable");
2688 mathias 551
};
2256 aurelien 552
 
2710 mathias 553
WidgetSaisie.prototype.focusChampFormulaire = function() {
554
	$("#date").focus();
555
};
556
 
2688 mathias 557
WidgetSaisie.prototype.chargerInfoObs = function() {
2700 mathias 558
	var urlObs = this.serviceObsUrl + '/' + this.obsId;
2707 mathias 559
	var lthis = this;
2256 aurelien 560
	$.ajax({
561
		url: urlObs,
562
		type: 'GET',
563
		success: function(data, textStatus, jqXHR) {
564
			if (data != undefined && data != "") {
2688 mathias 565
				this.prechargerForm(data);
2707 mathias 566
			} else {
567
				lthis.surErreurChargementInfosObs();
2328 jpm 568
			}
2256 aurelien 569
		},
570
		error: function(jqXHR, textStatus, errorThrown) {
2707 mathias 571
			lthis.surErreurChargementInfosObs();
2256 aurelien 572
		}
573
	});
2688 mathias 574
};
2256 aurelien 575
 
2707 mathias 576
// @TODO faire mieux que ça !
577
WidgetSaisie.prototype.surErreurChargementInfosObs = function() {
578
	alert("Erreur lors du chargement de l'observation");
579
}
580
 
2688 mathias 581
WidgetSaisie.prototype.prechargerForm = function(data) {
2328 jpm 582
 
2256 aurelien 583
	$("#milieu").val(data.milieu);
2328 jpm 584
 
2256 aurelien 585
	$("#carte-recherche").val(data.zoneGeo);
586
	$("#commune-nom").text(data.zoneGeo);
2328 jpm 587
 
2257 aurelien 588
	if(data.hasOwnProperty("codeZoneGeo")) {
589
		// TODO: trouver un moyen qui fonctionne lorsqu'on aura d'autres référentiels que INSEE
590
		$("#commune-code-insee").text(data.codeZoneGeo.replace('INSEE-C:', ''));
591
	}
2328 jpm 592
 
2256 aurelien 593
	if(data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) {
594
		var latLng = new google.maps.LatLng(data.latitude, data.longitude);
2688 mathias 595
		this.mettreAJourMarkerPosition(latLng);
596
		this.marker.setPosition(latLng);
597
		this.map.setCenter(latLng);
598
		this.map.setZoom(16);
2256 aurelien 599
	}
2688 mathias 600
};
2256 aurelien 601
 
2688 mathias 602
WidgetSaisie.prototype.configurerFormValidator = function() {
1210 jpm 603
	$.validator.addMethod(
2328 jpm 604
		"dateCel",
605
		function (value, element) {
606
			return value == "" || (/^[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}$/.test(value));
607
		},
1213 jpm 608
		"Format : jj/mm/aaaa. Date incomplète, utiliser 0, exemple : 00/12/2011.");
1210 jpm 609
	$.extend($.validator.defaults, {
610
		errorClass: "control-group error",
611
		validClass: "control-group success",
612
		errorElement: "span",
1213 jpm 613
		highlight: function(element, errorClass, validClass) {
1210 jpm 614
			if (element.type === 'radio') {
615
				this.findByName(element.name).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
2328 jpm 616
			} else {
1210 jpm 617
				$(element).parent("div").parent("div").removeClass(validClass).addClass(errorClass);
618
			}
619
		},
1213 jpm 620
		unhighlight: function(element, errorClass, validClass) {
1210 jpm 621
			if (element.type === 'radio') {
622
				this.findByName(element.name).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
623
			} else {
1213 jpm 624
				if ($(element).attr('id') == 'taxon') {
1493 aurelien 625
					if ($("#taxon").val() != '') {
626
						// Si le taxon n'est pas lié au référentiel, on vide le data associé
2688 mathias 627
						if ($("#taxon").data("value") != $("#taxon").val()) {
1493 aurelien 628
							$("#taxon").data("numNomSel","");
629
							$("#taxon").data("nomRet","");
630
							$("#taxon").data("numNomRet","");
631
							$("#taxon").data("nt","");
632
							$("#taxon").data("famille","");
1213 jpm 633
						}
1493 aurelien 634
						$("#taxon-input-groupe").removeClass(errorClass).addClass(validClass);
635
						$(element).next(" span.help-inline").remove();
1213 jpm 636
					}
637
				} else {
638
					$(element).parent("div").parent("div").removeClass(errorClass).addClass(validClass);
639
					$(element).next(" span.help-inline").remove();
640
				}
1210 jpm 641
			}
642
		}
643
	});
2688 mathias 644
};
1249 jpm 645
 
2688 mathias 646
WidgetSaisie.prototype.definirReglesFormValidator = function() {
1210 jpm 647
	$("#form-observateur").validate({
648
		rules: {
649
			courriel : {
650
				required : true,
651
				email : true},
652
			courriel_confirmation : {
653
				required : true,
654
				equalTo: "#courriel"}
655
		}
656
	});
657
	$("#form-station").validate({
658
		rules: {
659
			latitude : {
660
				range: [-90, 90]},
661
			longitude : {
662
				range: [-180, 180]}
663
		}
664
	});
665
	$("#form-obs").validate({
666
		rules: {
1213 jpm 667
			date : "dateCel",
1210 jpm 668
			taxon : "required"
669
		}
670
	});
2688 mathias 671
};
1249 jpm 672
 
2707 mathias 673
WidgetSaisie.prototype.configurerDatePicker = function(selector) {
1249 jpm 674
	$.datepicker.setDefaults($.datepicker.regional["fr"]);
2707 mathias 675
	$(selector).datepicker({
1990 jpm 676
		dateFormat: "dd/mm/yy",
677
		maxDate: new Date,
1249 jpm 678
		showOn: "button",
1990 jpm 679
		buttonImageOnly: true,
2700 mathias 680
		buttonImage: this.calendrierIconeUrl,
1249 jpm 681
		buttonText: "Afficher le calendrier pour saisir la date.",
2707 mathias 682
		showButtonPanel: true,
683
		onSelect: function(date) {
684
			$(this).valid();
685
		}
1210 jpm 686
	});
2707 mathias 687
	$(selector + ' + img.ui-datepicker-trigger').appendTo(selector + '-icone.add-on');
2688 mathias 688
};
1249 jpm 689
 
2688 mathias 690
WidgetSaisie.prototype.fermerPanneauAlert = function() {
1249 jpm 691
	$(this).parentsUntil(".zone-alerte", ".alert").hide();
2688 mathias 692
};
1249 jpm 693
 
2688 mathias 694
WidgetSaisie.prototype.formaterNom = function() {
1249 jpm 695
	$(this).val($(this).val().toUpperCase());
2688 mathias 696
};
1249 jpm 697
 
2688 mathias 698
WidgetSaisie.prototype.formaterPrenom = function() {
1249 jpm 699
	var prenom = new Array();
700
	var mots = $(this).val().split(' ');
701
	for (var i = 0; i < mots.length; i++) {
702
		var mot = mots[i];
703
		if (mot.indexOf('-') >= 0) {
704
			var prenomCompose = new Array();
705
			var motsComposes = mot.split('-');
706
		    for (var j = 0; j < motsComposes.length; j++) {
707
		    	var motSimple = motsComposes[j];
708
		    	var motMajuscule = motSimple.charAt(0).toUpperCase() + motSimple.slice(1);
709
		    	prenomCompose.push(motMajuscule);
710
		    }
711
		    prenom.push(prenomCompose.join('-'));
712
		} else {
713
			var motMajuscule = mot.charAt(0).toUpperCase() + mot.slice(1);
714
			prenom.push(motMajuscule);
715
		}
716
	}
717
	$(this).val(prenom.join(' '));
2688 mathias 718
};
1249 jpm 719
 
2688 mathias 720
WidgetSaisie.prototype.basculerAffichageAide = function()  {
1249 jpm 721
	if ($(this).hasClass('btn-warning')) {
2707 mathias 722
		$(".has-tooltip").tooltip('enable');
1249 jpm 723
		$(this).removeClass('btn-warning').addClass('btn-success');
724
		$('#btn-aide-txt', this).text("Désactiver l'aide");
725
	} else {
2707 mathias 726
		$(".has-tooltip").tooltip('disable');
1249 jpm 727
		$(this).removeClass('btn-success').addClass('btn-warning');
728
		$('#btn-aide-txt', this).text("Activer l'aide");
729
	}
2688 mathias 730
};
1249 jpm 731
 
2688 mathias 732
WidgetSaisie.prototype.bloquerCopierCollerCourriel = function() {
2700 mathias 733
	this.afficherPanneau("#dialogue-bloquer-copier-coller");
1249 jpm 734
	return false;
2688 mathias 735
};
1249 jpm 736
 
2688 mathias 737
WidgetSaisie.prototype.basculerAffichageCoord = function() {
1249 jpm 738
	$("a.afficher-coord").toggle();
739
	$("#coordonnees-geo").toggle('slow');
740
	//valeur false pour que le lien ne soit pas suivi
741
	return false;
2688 mathias 742
};
1249 jpm 743
 
2688 mathias 744
/**
745
 * Ajoute une observation saisie dans le formulaire à la liste des observations à transmettre
746
 */
747
WidgetSaisie.prototype.ajouterObs = function() {
2710 mathias 748
	// Fermeture automatique des dialogue de transmission de données
749
	// @WARNING TEST
750
	$('#dialogue-obs-transaction-ko').hide();
751
	$('#dialogue-obs-transaction-ok').hide();
752
 
2688 mathias 753
	if (this.validerFormulaire() == true) {
754
		this.obsNbre = this.obsNbre + 1;
755
		$(".obs-nbre").text(this.obsNbre);
1249 jpm 756
		$(".obs-nbre").triggerHandler('changement');
2688 mathias 757
		this.afficherObs();
758
		this.stockerObsData();
759
		this.supprimerMiniatures();
2700 mathias 760
		if(! this.especeImposee) {
1856 aurelien 761
			$("#taxon").val("");
762
			$("#taxon").data("numNomSel",undefined);
763
		}
2688 mathias 764
		$('#barre-progression-upload').attr('aria-valuemax', this.obsNbre);
765
		$('#barre-progression-upload .sr-only').text('0/'+this.obsNbre+" observations transmises");
1249 jpm 766
	} else {
2700 mathias 767
		this.afficherPanneau('#dialogue-form-invalide');
1249 jpm 768
	}
2688 mathias 769
};
1249 jpm 770
 
2688 mathias 771
/**
772
 * Affiche une observation dans la liste des observations à transmettre
773
 */
774
WidgetSaisie.prototype.afficherObs = function() {
1249 jpm 775
	$("#liste-obs").prepend(
2688 mathias 776
		'<div id="obs'+this.obsNbre+'" class="row-fluid obs obs'+this.obsNbre+'">'+
1249 jpm 777
			'<div class="span12">'+
1253 jpm 778
				'<div class="well">'+
2707 mathias 779
					'<div class="obs-action pull-right has-tooltip" data-placement="bottom" '+
1253 jpm 780
						'title="Supprimer cette observation de la liste à transmettre">'+
2688 mathias 781
						'<button class="btn btn-danger supprimer-obs" value="'+this.obsNbre+'" title="'+this.obsNbre+'">'+
1249 jpm 782
							'<i class="icon-trash icon-white"></i>'+
783
						'</button>'+
2328 jpm 784
					'</div> '+
785
					'<div class="row-fluid">'+
1249 jpm 786
						'<div class="thumbnail span2">'+
2688 mathias 787
						this.ajouterImgMiniatureAuTransfert()+
1240 jpm 788
						'</div>'+
1249 jpm 789
						'<div class="span9">'+
790
							'<ul class="unstyled">'+
791
								'<li>'+
792
									'<span class="nom-sci">'+$("#taxon").val()+'</span> '+
2688 mathias 793
									this.ajouterNumNomSel()+'<span class="referentiel-obs">'+
2700 mathias 794
									($("#taxon").data("numNomSel") == undefined ? '' : '['+ this.nomSciReferentiel +']')+'</span>'+
1249 jpm 795
									' observé à '+
796
									'<span class="commune">'+$('#commune-nom').text()+'</span> '+
797
									'('+$('#commune-code-insee').text()+') ['+$("#latitude").val()+' / '+$("#longitude").val()+']'+
798
									' le '+
799
									'<span class="date">'+$("#date").val()+'</span>'+
800
								'</li>'+
801
								'<li>'+
802
									'<span>Lieu-dit :</span> '+$('#lieudit').val()+' '+
803
									'<span>Station :</span> '+$('#station').val()+' '+
804
									'<span>Milieu :</span> '+$('#milieu').val()+' '+
805
								'</li>'+
806
								'<li>'+
807
									'Commentaires : <span class="discretion">'+$("#notes").val()+'</span>'+
808
								'</li>'+
809
							'</ul>'+
810
						'</div>'+
1237 jpm 811
					'</div>'+
1249 jpm 812
				'</div>'+
813
			'</div>'+
814
		'</div>');
2707 mathias 815
	$('#zone-liste-obs').removeClass("hidden").show();
2688 mathias 816
};
1249 jpm 817
 
2688 mathias 818
WidgetSaisie.prototype.stockerObsData = function() {
819
	var lthis = this;
820
	$("#liste-obs").data('obsId'+this.obsNbre, {
2328 jpm 821
		'date' : $("#date").val(),
2710 mathias 822
		'notes' : $("#notes").val().trim(),
2328 jpm 823
 
1249 jpm 824
		'nom_sel' : $("#taxon").val(),
825
		'num_nom_sel' : $("#taxon").data("numNomSel"),
826
		'nom_ret' : $("#taxon").data("nomRet"),
827
		'num_nom_ret' : $("#taxon").data("numNomRet"),
828
		'num_taxon' : $("#taxon").data("nt"),
829
		'famille' : $("#taxon").data("famille"),
2700 mathias 830
		'referentiel' : ($("#taxon").data("numNomSel") == undefined ? '' : lthis.nomSciReferentiel),
2328 jpm 831
 
1249 jpm 832
		'latitude' : $("#latitude").val(),
833
		'longitude' : $("#longitude").val(),
834
		'commune_nom' : $("#commune-nom").text(),
835
		'commune_code_insee' : $("#commune-code-insee").text(),
1251 jpm 836
		'lieudit' : $("#lieudit").val(),
1249 jpm 837
		'station' : $("#station").val(),
838
		'milieu' : $("#milieu").val(),
2328 jpm 839
 
1249 jpm 840
		//Ajout des champs images
2688 mathias 841
		'image_nom' : lthis.getNomsImgsOriginales(),
2709 mathias 842
		'image_b64' : lthis.getB64ImgsOriginales(),
843
 
844
		// Ajout des champs étendus de l'obs
845
		'obs_etendue': lthis.getObsChpEtendus()
1210 jpm 846
	});
2688 mathias 847
};
1249 jpm 848
 
2709 mathias 849
/**
850
 * Retourne un Array contenant les valeurs des champs étendus
851
 */
852
WidgetSaisie.prototype.getObsChpEtendus = function() {
853
	var champs = [];
854
 
855
	$('.obs-chp-etendu').each(function() {
856
		var valeur = $(this).val(),
857
			cle = $(this).attr('name'),
858
			label = $(this).data('label');
859
		if (valeur != '') {
860
			var chpEtendu = {cle: cle, label: label, valeur: valeur};
861
			champs.push(chpEtendu);
862
		}
863
	});
864
	return champs;
865
}
866
 
2688 mathias 867
WidgetSaisie.prototype.surChangementReferentiel = function() {
2700 mathias 868
	this.nomSciReferentiel = $('#referentiel').val();
1476 aurelien 869
	$('#taxon').val('');
2688 mathias 870
	this.initialiserAutocompleteCommune();
871
	this.initialiserGoogleMap();
872
};
1476 aurelien 873
 
2688 mathias 874
WidgetSaisie.prototype.surChangementNbreObs = function() {
875
	if (this.obsNbre == 0) {
1249 jpm 876
		$("#transmettre-obs").attr('disabled', 'disabled');
877
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 878
	} else if (this.obsNbre > 0 && this.obsNbre < this.obsMaxNbre) {
1249 jpm 879
		$("#transmettre-obs").removeAttr('disabled');
880
		$("#ajouter-obs").removeAttr('disabled');
2700 mathias 881
	} else if (this.obsNbre >= this.obsMaxNbre) {
1249 jpm 882
		$("#ajouter-obs").attr('disabled', 'disabled');
2700 mathias 883
		this.afficherPanneau("#dialogue-bloquer-creer-obs");
1249 jpm 884
	}
2688 mathias 885
};
1249 jpm 886
 
2688 mathias 887
WidgetSaisie.prototype.transmettreObs = function() {
1249 jpm 888
	var observations = $("#liste-obs").data();
2710 mathias 889
	if (this.debug) {
890
		console.log(observations);
891
	}
1249 jpm 892
	if (observations == undefined || jQuery.isEmptyObject(observations)) {
2700 mathias 893
		this.afficherPanneau("#dialogue-zero-obs");
1249 jpm 894
	} else {
2688 mathias 895
		this.nbObsEnCours = 1;
896
		this.nbObsTransmises = 0;
897
		this.totalObsATransmettre = $.map(observations, function(n, i) { return i; }).length;
898
		this.depilerObsPourEnvoi();
2110 aurelien 899
	}
900
	return false;
2688 mathias 901
};
2110 aurelien 902
 
2688 mathias 903
WidgetSaisie.prototype.depilerObsPourEnvoi = function() {
2110 aurelien 904
	var observations = $("#liste-obs").data();
905
	// la boucle est factice car on utilise un tableau
906
	// dont on a besoin de n'extraire que le premier élément
907
	// or javascript n'a pas de méthode cross browsers pour extraire les clés
908
	// TODO: utiliser var.keys quand ça sera plus répandu
909
	// ou bien utiliser un vrai tableau et pas un objet
2328 jpm 910
	for (var obsNum in observations) {
2697 mathias 911
		var obsATransmettre = {
2700 mathias 912
			'projet' : this.tagProjet,
913
			'tag-obs' : this.tagObs,
914
			'tag-img' : this.tagImg
2688 mathias 915
		};
2697 mathias 916
		var utilisateur = {
917
			id_utilisateur : $("#id_utilisateur").val(),
918
			prenom : $("#prenom").val(),
919
			nom : $("#nom").val(),
920
			courriel : $("#courriel").val()
921
		};
2110 aurelien 922
		obsATransmettre['utilisateur'] = utilisateur;
923
		obsATransmettre[obsNum] = observations[obsNum];
924
		var idObsNumerique = obsNum.replace('obsId', '');
925
		if(idObsNumerique != "") {
2688 mathias 926
			this.envoyerObsAuCel(idObsNumerique, obsATransmettre);
2110 aurelien 927
		}
2328 jpm 928
 
2110 aurelien 929
		break;
1249 jpm 930
	}
2688 mathias 931
};
1249 jpm 932
 
2688 mathias 933
WidgetSaisie.prototype.mettreAJourProgression = function() {
934
	this.nbObsTransmises++;
935
	var pct = (this.nbObsTransmises/this.totalObsATransmettre)*100;
936
	$('#barre-progression-upload').attr('aria-valuenow', this.nbObsTransmises);
2110 aurelien 937
	$('#barre-progression-upload').attr('style', "width: "+pct+"%");
2688 mathias 938
	$('#barre-progression-upload .sr-only').text(this.nbObsTransmises+"/"+this.totalObsATransmettre+" observations transmises");
2110 aurelien 939
 
2688 mathias 940
	if(this.obsNbre == 0) {
2110 aurelien 941
		$('.progress').removeClass('active');
942
		$('.progress').removeClass('progress-striped');
943
	}
2688 mathias 944
};
2110 aurelien 945
 
2688 mathias 946
WidgetSaisie.prototype.envoyerObsAuCel = function(idObs, observation) {
947
	var lthis = this;
1249 jpm 948
	var erreurMsg = "";
949
	$.ajax({
2700 mathias 950
		url : lthis.serviceSaisieUrl,
1249 jpm 951
		type : "POST",
2110 aurelien 952
		data : observation,
1249 jpm 953
		dataType : "json",
954
		beforeSend : function() {
1251 jpm 955
			$("#dialogue-obs-transaction-ko").hide();
956
			$("#dialogue-obs-transaction-ok").hide();
2697 mathias 957
			$('.alert-txt').empty();
2709 mathias 958
			$(".alert-txt .msg-erreur").remove();
959
			$(".alert-txt .msg-debug").remove();
1249 jpm 960
			$("#chargement").show();
961
		},
962
		success : function(data, textStatus, jqXHR) {
2110 aurelien 963
			// mise à jour du nombre d'obs à transmettre
964
			// et suppression de l'obs
2688 mathias 965
			lthis.supprimerObsParId(idObs);
2700 mathias 966
			lthis.nbObsEnCours++;
2110 aurelien 967
			// mise à jour du statut
2688 mathias 968
			lthis.mettreAJourProgression();
2700 mathias 969
			if(lthis.obsNbre > 0) {
2110 aurelien 970
				// dépilement de la suivante
2688 mathias 971
				lthis.depilerObsPourEnvoi();
2110 aurelien 972
			}
1249 jpm 973
		},
974
		statusCode : {
975
			500 : function(jqXHR, textStatus, errorThrown) {
976
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
977
		    }
978
		},
979
		error : function(jqXHR, textStatus, errorThrown) {
980
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
981
			try {
982
				reponse = jQuery.parseJSON(jqXHR.responseText);
983
				if (reponse != null) {
984
					$.each(reponse, function (cle, valeur) {
985
						erreurMsg += valeur + "\n";
986
					});
987
				}
988
			} catch(e) {
2700 mathias 989
				erreurMsg += "Erreur inconnue: " + jqXHR.responseText;
1249 jpm 990
			}
991
		},
992
		complete : function(jqXHR, textStatus) {
993
			var debugMsg = extraireEnteteDebug(jqXHR);
2328 jpm 994
 
1249 jpm 995
			if (erreurMsg != '') {
2700 mathias 996
				if (this.debug) {
1249 jpm 997
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-erreur">'+erreurMsg+'</pre>');
998
					$("#dialogue-obs-transaction-ko .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
1210 jpm 999
				}
1901 mathias 1000
				var hrefCourriel = "mailto:cel_remarques@tela-botanica.org?"+
2700 mathias 1001
					"subject=Dysfonctionnement du widget de saisie "+ this.tagProjet +
1902 mathias 1002
					"&body="+erreurMsg+"%0D%0ADébogage :%0D%0A"+debugMsg;
2328 jpm 1003
 
2110 aurelien 1004
				// mise en valeur de l'obs en erreur + scroll vers celle ci en changeant le hash
1005
				$('#obs'+idObs+' div div').addClass('obs-erreur');
1006
				window.location.hash = "obs"+idObs;
2328 jpm 1007
 
1249 jpm 1008
				$('#dialogue-obs-transaction-ko .alert-txt').append($("#tpl-transmission-ko").clone()
1009
					.find('.courriel-erreur')
1010
					.attr('href', hrefCourriel)
1011
					.end()
1012
					.html());
1013
				$("#dialogue-obs-transaction-ko").show();
2110 aurelien 1014
				$("#chargement").hide();
2688 mathias 1015
				lthis.initialiserBarreProgression();
1249 jpm 1016
			} else {
2700 mathias 1017
				if (lthis.debug) {
1249 jpm 1018
					$("#dialogue-obs-transaction-ok .alert-txt").append('<pre class="msg-debug">Débogage : '+debugMsg+'</pre>');
1019
				}
2700 mathias 1020
				if(lthis.obsNbre == 0) {
2110 aurelien 1021
					setTimeout(function() {
1022
						$("#chargement").hide();
1023
						$('#dialogue-obs-transaction-ok .alert-txt').append($('#tpl-transmission-ok').clone().html());
1024
						$("#dialogue-obs-transaction-ok").show();
2117 aurelien 1025
						window.location.hash = "dialogue-obs-transaction-ok";
2688 mathias 1026
						lthis.initialiserObs();
2110 aurelien 1027
					}, 1500);
2328 jpm 1028
 
1029
				}
1251 jpm 1030
			}
1210 jpm 1031
		}
1032
	});
2688 mathias 1033
};
1210 jpm 1034
 
2688 mathias 1035
WidgetSaisie.prototype.validerFormulaire = function() {
1210 jpm 1036
	$observateur = $("#form-observateur").valid();
1037
	$station = $("#form-station").valid();
1038
	$obs = $("#form-obs").valid();
1039
	return ($observateur == true && $station == true && $obs == true) ? true : false;
2688 mathias 1040
};
1210 jpm 1041
 
2688 mathias 1042
WidgetSaisie.prototype.getNomsImgsOriginales = function() {
1524 aurelien 1043
	var noms = new Array();
1044
	$(".miniature-img").each(function() {
1045
		noms.push($(this).attr('alt'));
1046
	});
1047
	return noms;
2688 mathias 1048
};
1524 aurelien 1049
 
2688 mathias 1050
WidgetSaisie.prototype.getB64ImgsOriginales = function() {
1524 aurelien 1051
	var b64 = new Array();
1052
	$(".miniature-img").each(function() {
1053
		if ($(this).hasClass('b64')) {
1054
			b64.push($(this).attr('src'));
1055
		} else if ($(this).hasClass('b64-canvas')) {
1056
			b64.push($(this).data('b64'));
1057
		}
1058
	});
1059
 
1210 jpm 1060
	return b64;
2688 mathias 1061
};
1210 jpm 1062
 
2688 mathias 1063
WidgetSaisie.prototype.supprimerObs = function(selector) {
1064
	var obsId = $(selector).val();
1210 jpm 1065
	// Problème avec IE 6 et 7
1066
	if (obsId == "Supprimer") {
2688 mathias 1067
		obsId = $(selector).attr("title");
1210 jpm 1068
	}
2688 mathias 1069
	this.supprimerObsParId(obsId);
1070
};
2110 aurelien 1071
 
2688 mathias 1072
WidgetSaisie.prototype.supprimerObsParId = function(obsId) {
1073
	this.obsNbre = this.obsNbre - 1;
1074
	$(".obs-nbre").text(this.obsNbre);
1237 jpm 1075
	$(".obs-nbre").triggerHandler('changement');
1215 jpm 1076
	$('.obs'+obsId).remove();
1210 jpm 1077
	$("#liste-obs").removeData('obsId'+obsId);
2688 mathias 1078
};
1210 jpm 1079
 
2688 mathias 1080
WidgetSaisie.prototype.initialiserBarreProgression = function() {
2110 aurelien 1081
	$('#barre-progression-upload').attr('aria-valuenow', 0);
1082
	$('#barre-progression-upload').attr('style', "width: 0%");
1083
	$('#barre-progression-upload .sr-only').text("0/0 observations transmises");
1084
	$('.progress').addClass('active');
1085
	$('.progress').addClass('progress-striped');
2688 mathias 1086
};
2110 aurelien 1087
 
2688 mathias 1088
WidgetSaisie.prototype.initialiserObs = function() {
1089
	this.obsNbre = 0;
1090
	this.nbObsTransmises = 0;
1091
	this.nbObsEnCours = 0;
1092
	this.totalObsATransmettre = 0;
1093
	this.initialiserBarreProgression();
1094
	$(".obs-nbre").text(this.obsNbre);
1249 jpm 1095
	$(".obs-nbre").triggerHandler('changement');
1096
	$("#liste-obs").removeData();
1097
	$('.obs').remove();
1098
	$("#dialogue-bloquer-creer-obs").hide();
2688 mathias 1099
};
1231 jpm 1100
 
2688 mathias 1101
/**
1102
 * Ajoute une boîte de miniatures avec défilement des images,
1103
 * pour une obs de la liste des obs à transmettre
1104
 */
1105
WidgetSaisie.prototype.ajouterImgMiniatureAuTransfert = function() {
1106
	var html = '',
1107
		miniatures = '',
1108
		premiere = true;
1524 aurelien 1109
	if ($("#miniatures img").length >= 1) {
1110
		$("#miniatures img").each(function() {
1111
			var visible = premiere ? 'miniature-selectionnee' : 'miniature-cachee';
1112
			premiere = false;
2688 mathias 1113
			var css = $(this).hasClass('b64') ? 'miniature b64' : 'miniature',
1114
				src = $(this).attr("src"),
1115
				alt = $(this).attr("alt"),
1116
				//miniature = '<img class="'+css+' '+visible+'"  alt="'+alt+'"src="'+src+'" />';
1117
				miniature = '<div class="'+css+' '+visible+'"  alt="'+alt+'" style="background-image: url('+src+')" ></div>';
1524 aurelien 1118
			miniatures += miniature;
1119
		});
1120
		visible = ($("#miniatures img").length > 1) ? '' : 'defilement-miniatures-cache';
2328 jpm 1121
		var html =
1524 aurelien 1122
			'<div class="defilement-miniatures">'+
1123
				'<a href="#" class="defilement-miniatures-gauche '+visible+'">&#60;</a>'+
1124
				miniatures+
1125
				'<a href="#" class="defilement-miniatures-droite '+visible+'">&#62;</a>'+
1126
			'</div>';
1237 jpm 1127
	} else {
2700 mathias 1128
		html = '<img class="miniature" alt="Aucune photo"src="'+ this.pasDePhotoIconeUrl +'" />';
1210 jpm 1129
	}
1524 aurelien 1130
	return html;
2688 mathias 1131
};
1210 jpm 1132
 
2688 mathias 1133
WidgetSaisie.prototype.defilerMiniatures = function(element) {
2328 jpm 1134
 
2688 mathias 1135
	var miniatureSelectionne = element.siblings("div.miniature-selectionnee");
1524 aurelien 1136
	miniatureSelectionne.removeClass('miniature-selectionnee');
1137
	miniatureSelectionne.addClass('miniature-cachee');
1138
	var miniatureAffichee = miniatureSelectionne;
2328 jpm 1139
 
1524 aurelien 1140
	if(element.hasClass('defilement-miniatures-gauche')) {
1141
		if(miniatureSelectionne.prev('.miniature').length != 0) {
1142
			miniatureAffichee = miniatureSelectionne.prev('.miniature');
1143
		} else {
1144
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").last();
1145
		}
1146
	} else {
1147
		if(miniatureSelectionne.next('.miniature').length != 0) {
1148
			miniatureAffichee = miniatureSelectionne.next('.miniature');
1149
		} else {
1150
			miniatureAffichee = miniatureSelectionne.siblings(".miniature").first();
1151
		}
1152
	}
1822 aurelien 1153
	//console.log(miniatureAffichee);
1524 aurelien 1154
	miniatureAffichee.addClass('miniature-selectionnee');
1155
	miniatureAffichee.removeClass('miniature-cachee');
2688 mathias 1156
};
1524 aurelien 1157
 
2688 mathias 1158
WidgetSaisie.prototype.ajouterNumNomSel = function() {
1240 jpm 1159
	var nn = '';
1160
	if ($("#taxon").data("numNomSel") == undefined) {
1161
		nn = '<span class="alert-error">[non lié au référentiel]</span>';
1162
	} else {
1163
		nn = '<span class="nn">[nn'+$("#taxon").data("numNomSel")+']</span>';
1164
	}
1165
	return nn;
2688 mathias 1166
};
1240 jpm 1167
 
2688 mathias 1168
WidgetSaisie.prototype.ajouterAutocompletionNoms = function() {
1169
	var lthis = this;
1210 jpm 1170
	$('#taxon').autocomplete({
2328 jpm 1171
		source: function(requete, add){
1210 jpm 1172
			// la variable de requête doit être vidée car sinon le parametre "term" est ajouté
1173
			requete = "";
2343 aurelien 1174
			if($("#referentiel").val() != "autre") {
2688 mathias 1175
				var url = lthis.getUrlAutocompletionNomsSci();
2343 aurelien 1176
				$.getJSON(url, requete, function(data) {
2688 mathias 1177
					var suggestions = lthis.traiterRetourNomsSci(data);
2343 aurelien 1178
					add(suggestions);
1179
	            });
1180
			}
1210 jpm 1181
        },
1182
        html: true
1183
	});
2328 jpm 1184
 
1213 jpm 1185
	$( "#taxon" ).bind("autocompleteselect", function(event, ui) {
1215 jpm 1186
		$("#taxon").data(ui.item);
1187
		if (ui.item.retenu == true) {
1188
			$("#taxon").addClass('ns-retenu');
1189
		} else {
1190
			$("#taxon").removeClass('ns-retenu');
1191
		}
1213 jpm 1192
	});
2688 mathias 1193
};
1210 jpm 1194
 
2688 mathias 1195
WidgetSaisie.prototype.getUrlAutocompletionNomsSci = function() {
1215 jpm 1196
	var mots = $('#taxon').val();
2700 mathias 1197
	var url = this.serviceAutocompletionNomSciUrlTpl.replace('{referentiel}', this.nomSciReferentiel);
1476 aurelien 1198
	url = url.replace('{masque}', mots);
1210 jpm 1199
	return url;
2688 mathias 1200
};
1210 jpm 1201
 
2688 mathias 1202
WidgetSaisie.prototype.traiterRetourNomsSci = function(data) {
2328 jpm 1203
	var suggestions = [];
1210 jpm 1204
	if (data.resultat != undefined) {
1205
		$.each(data.resultat, function(i, val) {
1206
			val.nn = i;
2328 jpm 1207
			var nom = {label : '', value : '', nt : '', nomSel : '', nomSelComplet : '', numNomSel : '',
1215 jpm 1208
				nomRet : '', numNomRet : '', famille : '', retenu : false
1209
			};
2700 mathias 1210
			if (suggestions.length >= this.autocompletionElementsNbre) {
1213 jpm 1211
				nom.label = "...";
1212
				nom.value = $('#taxon').val();
1213
				suggestions.push(nom);
1214
				return false;
1215
			} else {
1231 jpm 1216
				nom.label = val.nom_sci_complet;
1217
				nom.value = val.nom_sci_complet;
1215 jpm 1218
				nom.nt = val.num_taxonomique;
1219
				nom.nomSel = val.nom_sci;
1220
				nom.nomSelComplet = val.nom_sci_complet;
1221
				nom.numNomSel = val.nn;
1237 jpm 1222
				nom.nomRet = val.nom_retenu_complet;
1220 jpm 1223
				nom.numNomRet = val["nom_retenu.id"];
1231 jpm 1224
				nom.famille = val.famille;
2243 mathias 1225
				// Tester dans ce sens, permet de considérer "absent" comme "false" => est-ce opportun ?
1226
				// en tout cas c'est harmonisé avec le CeL
1227
				nom.retenu = (val.retenu == 'true') ? true : false;
2328 jpm 1228
 
1213 jpm 1229
				suggestions.push(nom);
2328 jpm 1230
			}
1210 jpm 1231
		});
1232
	}
2328 jpm 1233
 
1210 jpm 1234
	return suggestions;
2688 mathias 1235
};
1210 jpm 1236
 
2700 mathias 1237
WidgetSaisie.prototype.afficherPanneau = function(selecteur) {
1238
	$(selecteur).fadeIn("slow").delay(this.dureeMessage).fadeOut("slow");
2701 mathias 1239
};
2700 mathias 1240
 
2701 mathias 1241
WidgetSaisie.prototype.masquerPanneau = function(selecteur) {
1242
	$(selecteur).hide();
1243
};
1244
 
2697 mathias 1245
// lib hors objet --
1246
 
1247
/**
1248
* Stope l'évènement courant quand on clique sur un lien.
1249
* Utile pour Chrome, Safari...
1250
*/
1251
function arreter(evenement) {
1252
	if (evenement.stopPropagation) {
1253
		evenement.stopPropagation();
1254
	}
1255
	if (evenement.preventDefault) {
1256
		evenement.preventDefault();
1257
	}
1258
	return false;
1259
}
1260
 
1261
/**
1262
 * Extrait les données de désinsectisation d'une requête AJAX de jQuery
1263
 * @param jqXHR
1264
 * @returns {String}
1265
 */
1266
function extraireEnteteDebug(jqXHR) {
1267
	var msgDebug = '';
1268
	if (jqXHR.getResponseHeader("X-DebugJrest-Data") != '') {
1269
		var debugInfos = jQuery.parseJSON(jqXHR.getResponseHeader("X-DebugJrest-Data"));
1270
		if (debugInfos != null) {
1271
			$.each(debugInfos, function (cle, valeur) {
1272
				msgDebug += valeur + "\n";
1273
			});
1274
		}
1275
	}
1276
	return msgDebug;
1277
}
1278
 
1210 jpm 1279
/*
1280
 * jQuery UI Autocomplete HTML Extension
1281
 *
1282
 * Copyright 2010, Scott González (http://scottgonzalez.com)
1283
 * Dual licensed under the MIT or GPL Version 2 licenses.
1284
 *
1285
 * http://github.com/scottgonzalez/jquery-ui-extensions
2328 jpm 1286
 *
1210 jpm 1287
 * Adaptation par Aurélien Peronnet pour la mise en gras des noms de taxons valides
1288
 */
1289
(function( $ ) {
1215 jpm 1290
	var proto = $.ui.autocomplete.prototype,
1291
		initSource = proto._initSource;
2328 jpm 1292
 
2688 mathias 1293
	WidgetSaisie.prototype.filter = function( array, term ) {
1215 jpm 1294
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1295
		return $.grep( array, function(value) {
1296
			return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1297
		});
1298
	}
2328 jpm 1299
 
1215 jpm 1300
	$.extend( proto, {
1301
		_initSource: function() {
1302
			if ( this.options.html && $.isArray(this.options.source) ) {
1303
				this.source = function( request, response ) {
1304
					response( filter( this.options.source, request.term ) );
1305
				};
1306
			} else {
1307
				initSource.call( this );
1308
			}
1309
		},
1310
		_renderItem: function( ul, item) {
1311
			if (item.retenu == true) {
1312
				item.label = "<strong>"+item.label+"</strong>";
1313
			}
2328 jpm 1314
 
1215 jpm 1315
			return $( "<li></li>" )
1316
				.data( "item.autocomplete", item )
1317
				.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1318
				.appendTo( ul );
1319
		}
1210 jpm 1320
	});
1321
})( jQuery );