Subversion Repositories eFlore/Applications.cel

Rev

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