Subversion Repositories eFlore/Applications.cel

Rev

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

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