Subversion Repositories eFlore/Applications.cel

Rev

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