Subversion Repositories eFlore/Applications.cel

Rev

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

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