Subversion Repositories eFlore/Applications.cel

Rev

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