Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
1244 jpm 1
//+----------------------------------------------------------------------------------------------------------+
2
// Initialisation de Jquery mobile
1733 isa 3
$(document).on('mobileinit', function() {
1552 isa 4
	$.mobile.defaultPageTransition = 'fade';
1244 jpm 5
});
1552 isa 6
$(document).on('online', function(event) {
7
	console.log('online');
8
	miseAJourObs();
9
});
1733 isa 10
 
11
function changerPage(id, event) {
12
	$.mobile.changePage(id);
13
	event.stopPropagation();
14
	event.preventDefault();
15
}
1244 jpm 16
//+----------------------------------------------------------------------------------------------------------+
1552 isa 17
// Gestion des paramètres URL
1733 isa 18
var modal_recherche = false;
1552 isa 19
$.urlParam = function(name){
20
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
1829 isa 21
	return (results == null) ? 0 : decodeURIComponent(results[1]);
1552 isa 22
}
23
function recupererParametresUrl() {
1829 isa 24
	$('#referentiel').val(($.urlParam('ref') == 0) ? NOM_SCI_REFERENTIEL : $.urlParam('ref'));
25
	$('#nom').html(($.urlParam('nom_sci') == 0) ? '' : $.urlParam('nom_sci'));
26
	$('#nom-sci-select').val(($.urlParam('nom_sci') == 0) ? '' : $.urlParam('nom_sci'));
27
	$('#num-nom-select').val(($.urlParam('num_nom') == 0) ? 0 : $.urlParam('num_nom'));
1552 isa 28
}
1244 jpm 29
$(document).ready(function() {
1733 isa 30
	$('#geolocaliser').on('vclick', obtenirPosition);
31
 
32
	$('body').on('pagebeforeshow', '#infos', obtenirDate);
1552 isa 33
	$('body').on('pageshow', '#saisie', function(event) {
1733 isa 34
		if (!modal_recherche) {
35
			obtenirPosition(event);
36
			recupererParametresUrl();
37
		} else {
38
			modal_recherche = false;
39
		}
1552 isa 40
	});
1733 isa 41
	$('body').on('pagehide', '#saisie-popup', function() {
42
		modal_recherche = true;
43
	});
1244 jpm 44
});
1733 isa 45
 
1552 isa 46
//+----------------------------------------------------------------------------------------------------------+
47
// Géolocalisation et date du jour
48
var gps = navigator.geolocation;
1244 jpm 49
 
1552 isa 50
function obtenirPosition(event) {
51
	event.stopImmediatePropagation();
52
	event.stopPropagation();
53
	event.preventDefault();
54
 
55
	obtenirDate();
56
	geolocaliser();
57
}
58
function geolocaliser() {
1244 jpm 59
	if (gps) {
60
	    navigator.geolocation.getCurrentPosition(surSuccesGeoloc, surErreurGeoloc);
61
	} else {
1552 isa 62
	    var erreur = {code:'0', message: 'Géolocalisation non supportée par le navigateur'};
1244 jpm 63
	    surErreurGeoloc(erreur);
64
	}
65
}
66
function surSuccesGeoloc(position){
1552 isa 67
	if (position) {
68
		var lat = position.coords.latitude;
69
		var lng = position.coords.longitude;
70
		$('#lat').html(lat);
71
		$('#lng').html(lng);
72
 
73
		console.log('Geolocation SUCCESS');
74
		var url_service = SERVICE_NOM_COMMUNE_URL;
75
		var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
1733 isa 76
		$.ajax({
77
			url : urlNomCommuneFormatee,
78
			type : 'GET',
79
			dataType : 'jsonp',
80
			success : function(data) {
81
				console.log('NOM_COMMUNE found.');
82
				$('#location').html(data['nom']);
83
				$('#code-insee').val(data['codeINSEE']);
84
			},
85
			complete : function() {
86
				var texte = ($('#location').html() == '') ? TEXTE_HORS_LIGNE : $('#location').html();
87
				$('#location').html(texte);
88
			}
89
		});
1552 isa 90
	}
1244 jpm 91
}
92
function surErreurGeoloc(error){
1552 isa 93
	alert('Echec de la géolocalisation, code: ' + error.code + ' message: '+ error.message);
1244 jpm 94
}
1552 isa 95
 
96
function obtenirDate() {
97
	var d = new Date();
98
	var jour = d.getDate();
99
	var mois = d.getMonth()+1;
100
	var annee = d.getFullYear();
101
	var aujourdhui =
102
		( (''+jour).length < 2 ? '0' : '') + jour + '/' +
103
		( (''+mois).length < 2 ? '0' : '') + mois + '/' +
104
		annee;
1733 isa 105
	$('#date').html(aujourdhui);
1552 isa 106
	$('#annee').html(annee);
107
}
1244 jpm 108
//+----------------------------------------------------------------------------------------------------------+
109
// Local Storage
110
$(document).ready(function() {
111
	$('#sauver-obs').on('click', ajouterObs);
1733 isa 112
	$('#valider-photos').on('click', ajoutPhoto);
1244 jpm 113
	$('body').on('pageshow', '#liste', chargerListeObs);
1552 isa 114
	$('body').on('pageshow', '#transmission', miseAJourObs);
1244 jpm 115
});
116
 
1552 isa 117
var bdd = window.localStorage,
118
	index_obs = (bdd.getItem('index_obs') == null) ? 1 : bdd.getItem('index_obs'),
119
	index_photos = (bdd.getItem('index_photos') == null) ? 1 : bdd.getItem('index_photos');
120
//bdd.clear();
121
 
1733 isa 122
 
123
var db;
124
function initOpenDB() {
125
	try {
126
		if (!window.openDatabase) {
1829 isa 127
			//alert("L'ajout de photos n'est pas supporté.");
1733 isa 128
		} else {
129
			var shortName = 'CEL';
130
			var version = '1.0';
131
			var displayName = 'TB | CEL web';
132
			var maxSize = 1024 * 1024;
133
			db = openDatabase(shortName, version, displayName, maxSize);
134
			console.log(displayName + ' ' + maxSize);
135
			return db;
136
		}
137
	} catch (e) {
138
		if (e == 2) {
1829 isa 139
			//alert("Invalid database version.");
1733 isa 140
		} else {
1829 isa 141
			//alert("Unknown error " + e + ".");
1733 isa 142
		}
143
		return;
144
	}
145
}
146
initOpenDB();
1831 isa 147
if (db !== undefined) {
1829 isa 148
	db.transaction(function(tx) {
149
		//tx.executeSql('DROP TABLE IMG');
150
		tx.executeSql('CREATE TABLE IF NOT EXISTS IMG (id unique, num unique, nom, parent, base64, miniature)');
151
	});
152
}
1733 isa 153
 
1552 isa 154
console.log(bdd);
1244 jpm 155
function ajouterObs(event) {
1733 isa 156
	if ($('#nom').html() != '') {
1552 isa 157
		var obs = {
158
			num:TEXTE_OBS,
159
			maj:0,
160
			date:'',
161
			referentiel:'',
162
			lat:'', lng:'',
163
			commune:'', code_insee: 0,
164
			nom:'',
1733 isa 165
			nom_sci_select:'',
1552 isa 166
			nn_select:'',
167
			nom_sci_retenu:'',
168
			nn_retenu:'',
169
			num_taxon:'',
170
			famille:''
171
		};
172
 
173
		obs.num += index_obs++;
1733 isa 174
		obs.date = $('#date').html();
1552 isa 175
		obs.referentiel = $('#referentiel').val();
176
		obs.lat = $('#lat').html();
177
		obs.lng = $('#lng').html();
178
		obs.commune = $('#location').html();
1733 isa 179
		obs.code_insee = $('#code-insee').val();
180
		obs.nom = $('#nom').html();
1552 isa 181
		obs.referentiel = $('#referentiel').val();
1733 isa 182
		obs.nom_sci_select = $('#nom-sci-select').val();
183
		obs.nn_select = $('#num-nom-select').val();
1552 isa 184
 
185
		var cle = obs.num;
186
		sauvegarderObs(cle, obs);
187
		bdd.setItem('index_obs', index_obs);
188
		effacerFormulaire();
1733 isa 189
		changerPage('#liste', event);
1552 isa 190
	} else {
1829 isa 191
		var txt = 'Aucune espèce saisie !';
192
		$('#obs-saisie-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">' + txt + '</p>')
193
			.fadeIn(0)
194
			.delay(1600)
195
			.fadeOut('slow');
1733 isa 196
		changerPage('#saisie', event);
1552 isa 197
	}
198
}
199
 
200
function sauvegarderObs(cle, obs) {
1733 isa 201
	var val = JSON.stringify(obs),
202
		poids = JSON.stringify(bdd).length + val.length;
203
	if (poids > 2621940) {
204
		$('#cache-plein').popup('open');
205
	}
1244 jpm 206
	bdd.setItem(cle, val);
1552 isa 207
}
208
 
209
function effacerFormulaire() {
1733 isa 210
    $('#lat').html('');
211
    $('#lng').html('');
212
    $('#location').html('');
1552 isa 213
}
214
 
215
function chargerListeObs() {
1733 isa 216
	$('#liste-obs').empty();
1244 jpm 217
 
1552 isa 218
	var nbre = bdd.length;
219
	for (var i = 0; i < nbre; i++) {
220
		var cle = bdd.key(i);
221
		if (cle.indexOf(TEXTE_OBS) !== -1) {
222
			var obs = JSON.parse(bdd.getItem(cle));
223
			console.log(obs);
1733 isa 224
			$('#liste-obs').prepend(
1552 isa 225
				'<li>'+
1733 isa 226
					'<a href="#" onclick="detailsObs(this);" data-split-icon="next" data-split-theme="a" title="Voir la fiche" data-obs-num="' + obs.num + '">' +
227
						'<strong>' + obs.nom + '</strong> <br />' + obs.date +
228
						((obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') ? '' :  (' à ' + obs.commune)) +
1552 isa 229
					'</a>'+
230
					'<a href="#" onclick="supprimerObs(this);" title="Supprimer l\'observation" ' +
1733 isa 231
						'data-obs-num="' + obs.num + '">' +
1552 isa 232
						'Supprimer'+
233
					'</a>'+
234
				'</li>'
235
			);
236
		}
1733 isa 237
		$('#liste-obs').listview('refresh');
1552 isa 238
	}
239
}
240
 
241
function supprimerObs(data) {
242
	var cle_obs = data.getAttribute('data-obs-num'),
243
		obs = JSON.parse(bdd.getItem(cle_obs)),
244
		nbre = bdd.length,
245
		a_supprimer = new Array();
1829 isa 246
 
1831 isa 247
	if (db !== undefined) {
1829 isa 248
		db.transaction(function(tx) {
249
			tx.executeSql('DELETE FROM IMG WHERE parent LIKE ?', [cle_obs]);
250
		});
251
	}
1552 isa 252
	bdd.removeItem(cle_obs);
253
 
1733 isa 254
	var txt = 'Observation n°' + obs.num.substring(TEXTE_OBS.length) + ' supprimée.';
255
	$('#obs-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">' + txt + '</p>')
1552 isa 256
		.fadeIn(0)
1248 jpm 257
		.delay(1600)
1552 isa 258
		.fadeOut('slow');
1248 jpm 259
 
1552 isa 260
	chargerListeObs();
1244 jpm 261
}
262
 
1552 isa 263
function detailsObs(data) {
1831 isa 264
	if (db !== undefined) {
1829 isa 265
		var num_obs = data.getAttribute('data-obs-num');
266
		var obs = JSON.parse(bdd.getItem(num_obs));
267
		$('#id-obs').html(obs.num);
268
 
269
		var texte = '<strong>' + obs.nom + '</strong> vue le ' + obs.date;
270
		texte += (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') ? '' :  ' à ' + obs.commune;
271
		$('#details-obs').html(texte);
272
		$.mobile.changePage('#observation');
273
		afficherPhotos(obs.num);
274
	} else {
275
		var texte ='L\'accès à l\'ajout de photos n\'est pas supporté.';
276
		$('#obs-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">' + texte + '</p>')
277
			.fadeIn(0)
278
			.delay(1600)
279
			.fadeOut('slow');
280
	}
1552 isa 281
}
282
 
283
function ajoutPhoto() {
1733 isa 284
	var id_obs = $('#id-obs').html();
1552 isa 285
	if (id_obs != '') {
286
		$.each($('#pic').get(0).files, function(index, valeur) {
1733 isa 287
			//*
288
			var reader = new FileReader();
289
			reader.addEventListener('loadend', function () {
290
				var photo_nom = valeur.name,
291
					arr_nom = photo_nom.split("."),
292
					dernier = arr_nom.length - 1;
293
				if (arr_nom[dernier].toUpperCase() != "JPG" && arr_nom[dernier].toUpperCase() != "JPEG") {
294
					$('#pic').val('');
295
					var txt = 'Seuls les fichiers .JPG ou .JPEG sont acceptés.';
296
					$('#photo-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">' + txt + '</p>')
297
						.fadeIn(0)
298
						.delay(1600)
299
						.fadeOut('slow');
300
				} else {
301
					var photo = {
302
						num: TEXTE_PHOTO,
303
						nom: '',
304
						parent: '',
305
						base64: 0,
306
						miniature: ''
307
					};
308
					photo.num += index_photos++;
309
					photo.nom = photo_nom;
310
					photo.parent = id_obs;
311
					photo.base64 = reader.result;
312
					bdd.setItem('index_photos', index_photos);
313
 
314
					var img = new Image(),
315
						miniature = null;
316
					img.src = photo.base64;
317
					img.alt = photo.nom;
318
					img.onload = function() {
319
						miniature = transformerImgEnCanvas(this, 100, 100, false, 'white');
320
 
321
						db.transaction(function(tx) {
322
							tx.executeSql('SELECT * FROM IMG', [], function(tx, results) {
323
								var taille = results.rows.length + 1;
324
								tx.executeSql(
325
									'INSERT INTO IMG'
326
									+ ' (id, parent, nom, base64, num, miniature)'
327
									+ ' VALUES (?, ?, ?, ?, ?, ?)',
328
									[taille, photo.parent, photo.nom, photo.base64, photo.num, miniature]);
329
							});
330
						});
331
						afficherPhotos(id_obs);
332
					}
333
				}
1552 isa 334
			}, false);
1733 isa 335
			reader.readAsDataURL(valeur);
1552 isa 336
		});
337
	}
338
}
339
 
340
function afficherPhotos(num_obs) {
341
	$('#pic').val('');
1733 isa 342
	$('#photos-obs').empty();
1552 isa 343
	if (num_obs != '') {
1733 isa 344
		db.readTransaction(function(tx) {
345
			tx.executeSql('SELECT * FROM IMG WHERE parent LIKE ?', [num_obs], function(tx, results) {
346
				var nbre = results.rows.length;
347
				for (var i = 0; i < nbre; i++) {
348
					photo = results.rows.item(i);
349
					$('#photos-obs').prepend(
1552 isa 350
						'<li>'+
1733 isa 351
							'<a href="#" onclick="afficherVue(this);" data-ajax="false" data-role="button" data-inline="true" data-photo-num="' + photo.num + '">' +
352
								'<img src="' + photo.miniature + '" />' +
1552 isa 353
								photo.nom +
354
							'</a>' +
355
							'<a href="#" onclick="supprimerPhoto(this);" title="Supprimer la photo" ' +
1733 isa 356
								'data-icon="delete" data-photo-num="' + photo.num + '" data-photo-parent="' + num_obs + '"' +
357
								'data-theme="c">' +
358
								'Supprimer cette photo' +
359
							'</a>' +
1552 isa 360
						'</li>'
361
					);
362
				}
1733 isa 363
				$('#photos-obs').listview('refresh');
364
			}, null);
365
		});
1552 isa 366
	}
367
}
368
 
1733 isa 369
function afficherVue(data) {
370
	var cle_photo = data.getAttribute('data-photo-num');
371
	db.readTransaction(function(tx) {
372
		tx.executeSql('SELECT * FROM IMG WHERE num LIKE ?', [cle_photo], function(tx, results) {
373
			var photo = results.rows.item(0);
374
			$('#photo-zoom-infos').html('<img class="photo-popup" width="80%" src="' + photo.base64 + '" />');
375
			$('#photo-zoom')
376
				.popup('open')
377
				.on('popupafterclose', function(event) {
378
					event.stopImmediatePropagation();
379
					event.stopPropagation();
380
					event.preventDefault();
381
				});
382
		});
383
	});
1552 isa 384
}
385
 
386
function supprimerPhoto(data) {
387
	var cle_photo = data.getAttribute('data-photo-num'),
1733 isa 388
		parent = data.getAttribute('data-photo-parent');
389
	db.transaction(function(tx) {
390
		tx.executeSql('DELETE FROM IMG WHERE num LIKE ?', [cle_photo]);
391
	});
392
/*
1552 isa 393
	var txt = photo.num + ' supprimée.';
394
	$('#photo-suppression-infos').html('<p class="reponse ui-btn-inner ui-btn-corner-all">'+txt+'</p>')
395
		.fadeIn(0)
1248 jpm 396
		.delay(1600)
1552 isa 397
		.fadeOut('slow');
1733 isa 398
*/
1552 isa 399
	afficherPhotos(parent);
1248 jpm 400
}
401
 
1552 isa 402
function miseAJourObs() {
403
	console.log('majObs');
1244 jpm 404
	var nbre = bdd.length;
405
	for (var i = 0; i < nbre; i++) {
1552 isa 406
		var cle = bdd.key(i);
407
		if (cle.indexOf(TEXTE_OBS) !== -1) {
408
			var obs = JSON.parse(bdd.getItem(cle));
409
 
410
			if (obs.maj == 0) {
411
				var maj = 1;
412
 
413
				if (obs.commune == TEXTE_HORS_LIGNE ||  obs.commune == '') {
414
					var url_service = SERVICE_NOM_COMMUNE_URL;
415
					var urlNomCommuneFormatee = url_service.replace('{lat}', lat).replace('{lon}', lng);
416
					jQuery.ajax({
417
						url: urlNomCommuneFormatee,
1733 isa 418
						type : 'GET',
419
						dataType : 'jsonp',
1552 isa 420
						success: function(data) {
421
							obs.commune = data['nom'];
422
							obs.code_insee = data['codeINSEE'];
423
						 },
424
						 error: function() {
425
							 maj = 0;
426
						 },
427
						async: false
428
				   });
429
				}
430
 
431
				if (obs.nom_sci_retenu == '') {
432
					jQuery.ajax({
433
						url:	'/service:eflore:0.1/' + obs.referentiel + '/noms?'
434
								 + 'masque.nn=' + obs.nn_select
435
								 + '&retour.champs=num_taxonomique',
436
						success: function(data) {
437
							var cle = '',
438
								compteur = 0;
439
							for (name in data['resultat']) {
440
								if (compteur == 0) {
441
									cle = name;
442
								}
443
								compteur++;
444
							}
445
							obs.num_taxon = data['resultat'][cle]['num_taxonomique'];
446
							jQuery.ajax({
447
								url: 	'/service:eflore:0.1/' + obs.referentiel + '/noms?'
448
										 + 'masque.nt=' + obs.num_taxon
449
										 + '&retour.champs=famille'
450
										 + '&retour.tri=retenu',
1733 isa 451
								type : 'GET',
452
								dataType : 'jsonp',
1552 isa 453
								success: function(data) {
1733 isa 454
									var cle = '';
1552 isa 455
									for (name in data['resultat']) {
1733 isa 456
										if (data['resultat'][name]['retenu'] == 'true') {
1552 isa 457
											cle = name;
1733 isa 458
											break;
1552 isa 459
										}
460
									}
461
									obs.famille = data['resultat'][cle]['famille'];
462
									obs.nom_sci_retenu = data['resultat'][cle]['nom_sci'];
463
									obs.nn_retenu = cle;
464
								 },
465
								 error: function() {
466
									 maj = 0;
467
								 },
468
								async:   false
469
							});
470
						 },
471
						async:   false
472
					});
473
				}
474
 
475
				obs.maj = maj;
476
			}
477
 
478
			sauvegarderObs(obs.num, obs);
479
		}
1244 jpm 480
	}
481
}
482
 
1733 isa 483
//+----------------------------------------------------------------------------------------------------------+
484
// Gestion des photos
485
function transformerImgEnCanvas(img, thumbwidth, thumbheight, crop, background) {
486
	var canvas = document.getElementById('photo-canvas');
487
	canvas.width = thumbwidth;
488
	canvas.height = thumbheight;
489
	var dimensions = calculerDimensions(img.width, img.height, thumbwidth, thumbheight);
490
	if (crop) {
491
		canvas.width = dimensions.w;
492
		canvas.height = dimensions.h;
493
		dimensions.x = 0;
494
		dimensions.y = 0;
495
	}
496
	cx = canvas.getContext('2d');
497
	cx.clearRect(0, 0, thumbwidth, thumbheight);
498
	if (background !== 'transparent') {
499
		cx.fillStyle = background;
500
		cx.fillRect(0, 0, thumbwidth, thumbheight);
501
	}
502
 
503
	cx.drawImage(img, dimensions.x, dimensions.y, dimensions.w, dimensions.h);
504
	return afficherMiniature(canvas);
505
}
506
 
507
function calculerDimensions(imagewidth, imageheight, thumbwidth, thumbheight) {
508
	var w = 0, h = 0, x = 0, y = 0, zoom = 1,
509
	    widthratio = imagewidth / thumbwidth,
510
	    heightratio = imageheight / thumbheight,
511
	    maxratio = Math.max(widthratio, heightratio);
512
 
513
	if (maxratio > 1) {
514
	    w = imagewidth / maxratio;
515
	    h = imageheight / maxratio;
516
	} else {
517
	    w = imagewidth;
518
	    h = imageheight;
519
	}
520
	x = (thumbwidth - w) / 2;
521
	y = (thumbheight - h) / 2;
522
 
523
	zoom = (maxratio > 10) ? (2.6*(maxratio / 10)) : 1;
524
	h *= zoom;
525
 
526
	return {w:w, h:h, x:x, y:y};
527
}
528
 
529
function afficherMiniature(canvas) {
530
	return canvas.toDataURL('image/jpeg' , 0.8);
531
}
532
 
533
//+----------------------------------------------------------------------------------------------------------+
534
// Autocomplétion des noms latins
535
var recherche = '';
536
$(document).on('pageinit', '#saisie', function() {
537
    $('#liste-noms-latins').on('listviewbeforefilter', function(e, data) {
538
        var $input = $(data.input);
539
        recherche = $input.val();
540
 
541
		$input.keyup(function() {
542
			clearTimeout($.data(this, 'timer'));
543
			var wait = setTimeout(lancerRecherche, DELAI_RECHERCHE);
544
			$(this).data('timer', wait);
545
		});
546
    });
547
});
548
 
549
function lancerRecherche() {
550
	var $ul = $('#liste-noms-latins'),
551
		html = '';
552
    $ul.html('');
553
 
554
	if (recherche && recherche.length > 2) {
555
		afficherChargement();
556
		$ul.html('<li><div class="ui-loader"><span class="ui-icon ui-icon-loading"></span></div></li>');
557
		$ul.listview('refresh');
558
		$.ajax({ })
559
		.then(function() {
560
			for (index in BDTFX) {
561
				var espece = BDTFX[index],
562
					nom_sci = espece['nom_sci'],
563
					num_nom = espece['num_nom'],
564
					auteur = espece['auteur'],
565
					annee = espece['annee'],
566
					nom_sci_complet = nom_sci + ((auteur == '' || auteur == null) ? '' : (' ' + auteur)) + ((annee == '' || annee == null) ? '' : (' (' + annee + ')'));
567
 
568
				if (nom_sci !== '') {
569
					var arr_nom_sci = nom_sci.split(' '),
570
						arr_recherche = recherche.split(' ');
571
 
572
					if (arr_nom_sci[1] !== undefined) {
573
						nom_sci_recherche = arr_nom_sci[1];
574
 
575
						if (arr_nom_sci[1].toLowerCase() == 'x') {
576
							nom_sci_recherche = arr_nom_sci[2];
577
						}
578
					} else {
579
						nom_sci_recherche = arr_nom_sci[0];
580
					}
581
 
582
					if ((arr_nom_sci[0].toLowerCase().substring(0, arr_recherche[0].length)) == arr_recherche[0].toLowerCase()) {
583
						var flag = true;
584
						if (arr_recherche[1] !== undefined) {
585
							flag = ( (nom_sci_recherche.toLowerCase().substring(0, arr_recherche[1].length)) == arr_recherche[1].toLowerCase() );
586
						}
587
 
588
						if (flag) {
589
							html += '<li>'
590
									+ '<a href="#" data-nom-sci="' + nom_sci + '" data-num-nom="' + num_nom + '" '
591
										+ ' data-auteur="' + auteur + '" data-nom-sci-complet="' + nom_sci_complet
2325 aurelien 592
										+ '" data-nom-sci-referentiel="bdtfx"'
1733 isa 593
										+ '" class="noms-latins" >'
594
									+ nom_sci_complet
595
									+ '</a>'
596
								+ '</li>';
597
						}
598
					}
599
				}
600
			}
601
			$.mobile.loading('hide');
602
			$ul.html(html);
603
			$ul.listview('refresh');
604
			$ul.trigger('updatelayout');
605
			$('.noms-latins').on('click', choisirEspece);
606
		});
607
	}
608
}
609
 
610
function afficherChargement() {
611
	var $this = $('#recherche-chargement'),
612
		theme = $this.jqmData('theme') || $.mobile.loader.prototype.options.theme,
613
		msg = $this.jqmData('msgtext') || $.mobile.loader.prototype.options.text,
614
		textVisible = $this.jqmData('textvisible') || $.mobile.loader.prototype.options.textVisible,
615
		textonly = !!$this.jqmData('textonly');
616
		html = $this.jqmData('html') || '';
617
 
618
	$.mobile.loading('show', {
619
		text: msg,
620
		textVisible: textVisible,
621
		theme: theme,
622
		textonly: textonly,
623
		html: html
624
	});
625
 }
626
 
627
function choisirEspece(event) {
628
	var espece = event.currentTarget,
629
		auteur = espece.getAttribute('data-auteur'),
2325 aurelien 630
		referentiel = espece.getAttribute('data-nom-sci-referentiel'),
1733 isa 631
		nom_sci = espece.getAttribute('data-nom-sci'),
632
		nom_sci_complet = espece.getAttribute('data-nom-sci-complet')
633
		num_nom = espece.getAttribute('data-num-nom');
634
 
635
	$('#nom').html(nom_sci_complet);
2325 aurelien 636
	$('#referentiel').val(referentiel);
1733 isa 637
	$('#nom-sci-select').val(nom_sci);
638
	$('#num-nom-select').val(num_nom);
639
	$('#liste-noms-latins').html('');
640
	$('#saisie-popup').dialog('close');
641
}
642
 
643
//+----------------------------------------------------------------------------------------------------------+
644
// Manifest Cache
645
var appCache = window.applicationCache;
646
appCache.addEventListener('updateready', function() {
647
	if (appCache.status === appCache.UPDATEREADY) {
648
		surMiseAJourCache();
649
	}
650
});
651
 
652
function surMiseAJourCache() {
653
	appCache.swapCache();
654
	if (confirm('Une nouvelle version de ce site est disponible. Mettre à jour ?')) {
655
	  window.location.reload();
656
	}
657
}
658
 
659
//+----------------------------------------------------------------------------------------------------------+
660
//Transmission données
661
$(document).ready(function() {
662
	$('#transmettre-obs').on('click', transmettreObs);
663
});
664
 
1552 isa 665
function transmettreObs() {
1733 isa 666
	var msg = '';
667
	if (recupererStatutIdentite() == 'true') {
668
		if (verifierConnexion()) {
669
			var nbre = bdd.length;
670
			for (var i = 0; i < nbre; i++) {
671
				var cle = bdd.key(i);
672
				if (cle.indexOf('obs') !== -1) {
673
					var obs = JSON.parse(bdd.getItem(cle));
674
					stockerObsData(obs);
675
				}
1552 isa 676
			}
1733 isa 677
 
678
			var observations = $('#details-obs').data();
679
			if (observations == undefined || jQuery.isEmptyObject(observations)) {
680
				msg = 'Aucune observation à transmettre.';
681
			} else {
682
				msg = 'Transmission en cours...';
683
				observations['projet'] = TAG_PROJET;
684
				observations['tag-obs'] = '';
685
				observations['tag-img'] = '';
686
 
687
				var utilisateur = new Object();
688
				utilisateur.id_utilisateur = ($('#id-utilisateur').val() == '') ? bdd.getItem('utilisateur.id') : $('#id-utilisateur').val();
689
				utilisateur.prenom = ($('#prenom-utilisateur').val() == '') ? bdd.getItem('utilisateur.prenom') : $('#prenom-utilisateur').val();
690
				utilisateur.nom = ($('#nom-utilisateur').val() == '') ? bdd.getItem('utilisateur.nom') : $('#nom-utilisateur').val();
691
				utilisateur.courriel = ($('#courriel').val() == '') ? bdd.getItem('utilisateur.courriel') : $('#courriel').val();
692
				observations['utilisateur'] = utilisateur;
693
				envoyerObsAuCel(observations);
694
			}
1552 isa 695
		} else {
1733 isa 696
			msg = 'Aucune connexion disponible. Merci de réessayer ultérieurement.';
1552 isa 697
		}
1733 isa 698
	} else {
699
		msg = 'Merci de vérifier et de confirmer votre adresse e-mail avant de transmettre vos observations.';
1552 isa 700
	}
1733 isa 701
 
702
	if (msg != '') {
703
		$('#identification-infos').html('<p class="reponse">' + msg + '</p>')
704
			.fadeIn(0)
705
			.delay(2000)
706
			.fadeOut('slow');
707
	}
1552 isa 708
}
1244 jpm 709
 
1733 isa 710
function verifierConnexion() {
711
	return ( ('onLine' in navigator) && (navigator.onLine));
712
}
713
 
1552 isa 714
function stockerObsData(obs) {
1733 isa 715
	var img_noms = new Array(),
1552 isa 716
		img_codes = new Array();
1831 isa 717
	if (db !== undefined) {
718
		db.transaction(function(tx) {
719
			tx.executeSql('SELECT * FROM IMG WHERE parent LIKE ?', [obs.num], function(tx, results) {
720
				var nbre = results.rows.length;
721
				for (var i = 0; i < nbre; i++) {
722
					photo = results.rows.item(i);
723
					img_noms.push(photo.nom);
724
					img_codes.push(photo.base64);
725
				}
726
			}, null);
727
		});
728
	}
1733 isa 729
 
730
	$('#details-obs').data(obs.num, {
1552 isa 731
		'date' : obs.date,
732
		'notes' : '',
733
 
734
		'nom_sel' : obs.nom,
735
		'num_nom_sel' : obs.nn_select,
736
		'nom_ret' : obs.nom_sci_retenu,
737
		'num_nom_ret' : obs.nn_retenu,
738
		'num_taxon' : obs.num_taxon,
739
		'famille' : obs.famille,
740
		'referentiel' : obs.referentiel,
741
 
742
		'latitude' : obs.lat,
743
		'longitude' : obs.lng,
744
		'commune_nom' : obs.commune,
745
		'commune_code_insee' : obs.code_insee,
746
		'lieudit' : '',
747
		'station' : '',
748
		'milieu' : '',
749
 
750
		//Ajout des champs images
751
		'image_nom' : img_noms,
752
		'image_b64' : img_codes
753
	});
754
}
755
 
756
 
757
function envoyerObsAuCel(observations) {
1829 isa 758
	//console.log(observations);
1552 isa 759
	var erreurMsg = "";
760
	$.ajax({
761
		url : SERVICE_SAISIE_URL,
762
		type : "POST",
763
		data : observations,
764
		dataType : "json",
765
		beforeSend : function() {
1733 isa 766
			console.log('before send');
1552 isa 767
		},
768
		success : function(data, textStatus, jqXHR) {
1733 isa 769
			console.log('Transmission SUCCESS.');
1552 isa 770
		},
771
		statusCode : {
772
			500 : function(jqXHR, textStatus, errorThrown) {
773
				erreurMsg += "Erreur 500 :\ntype : "+textStatus+' '+errorThrown+"\n";
774
		    }
775
		},
776
		error : function(jqXHR, textStatus, errorThrown) {
777
			erreurMsg += "Erreur Ajax :\ntype : "+textStatus+' '+errorThrown+"\n";
778
			try {
779
				reponse = jQuery.parseJSON(jqXHR.responseText);
780
				if (reponse != null) {
781
					$.each(reponse, function (cle, valeur) {
782
						erreurMsg += valeur + "\n";
783
					});
784
				}
785
			} catch(e) {
786
				erreurMsg += "L'erreur n'était pas en JSON.";
787
			}
788
		},
789
		complete : function(jqXHR, textStatus) {
1733 isa 790
			console.log('complete');
791
			console.log(jqXHR);
1552 isa 792
		}
793
	});
794
}
795
 
796
//+---------------------------------------------------------------------------------------------------------+
797
//IDENTITÉ
798
$(document).ready(function() {
799
	$('#courriel').on('blur', requeterIdentite);
800
	$('#courriel').on('keypress', function(event) {
801
		if (event.which == 13) {
2325 aurelien 802
			requeterIdentite(event);
1552 isa 803
		}
804
	});
1733 isa 805
 
806
	$('body').on('pagebeforeshow', '#transmission', completerCompte);
807
	$('body').on('pagebeforeshow', '#identification-popup', testerLancementRequeteIdentite);
808
 
809
	$('#valider-courriel').on('vmousedown', requeterIdentite);
810
	$('#valider-identification').on('vmousedown', confirmerIdentification);
1552 isa 811
});
812
 
1733 isa 813
function completerCompte() {
814
	if (bdd.getItem('utilisateur.courriel') != null) {
815
		var courriel = bdd.getItem('utilisateur.courriel');
816
		$('#identification-texte').html(TEXTE_OUI_COMPTE);
817
		$('#utilisateur-compte').html(courriel);
818
		$('#identification-btn * .ui-btn-text').html('Modifier le compte');
819
	} else {
820
		$('#identification-texte').html(TEXTE_NON_COMPTE);
821
		$('#identification-btn * .ui-btn-text').html('Ajouter un compte');
822
	}
823
}
824
 
1552 isa 825
function testerLancementRequeteIdentite(event) {
1733 isa 826
	if (bdd.getItem('utilisateur.courriel') != null) {
827
		var courriel = bdd.getItem('utilisateur.courriel');
828
		$('#courriel').val(courriel);
829
 
830
		if (recupererStatutIdentite() == 'true') {
831
			$('#courriel-confirmation').val(courriel);
832
		}
1552 isa 833
	}
1733 isa 834
	if (bdd.getItem('utilisateur.nom') != null) {
835
		$('#nom-utilisateur').val(bdd.getItem('utilisateur.nom'));
836
	}
837
	if (bdd.getItem('utilisateur.prenom') != null) {
838
		$('#prenom-utilisateur').val(bdd.getItem('utilisateur.prenom'));
839
	}
840
	if (bdd.getItem('utilisateur.id') != null) {
841
		$('#id-utilisateur').val(bdd.getItem('utilisateur.id'));
842
	}
1552 isa 843
 
844
	event.preventDefault();
845
	event.stopPropagation();
846
}
847
 
1733 isa 848
function recupererStatutIdentite() {
849
	return bdd.getItem('utilisateur.identite');
850
}
851
 
852
function confirmerIdentification(event) {
853
	confirmerCourriel();
854
	changerPage('#transmission', event);
855
}
856
 
857
function confirmerCourriel() {
858
	bdd.setItem('utilisateur.identite', false);
859
	if (validerCourriel($('#courriel').val())) {
860
		if ($('#courriel').val() == $('#courriel-confirmation').val()) {
861
			bdd.setItem('utilisateur.identite', true);
862
		}
863
	} else  {
864
		$('#identification-infos').html('<p class="reponse">Adresse e-mail invalide.</p>')
865
			.fadeIn(0)
866
			.delay(2000)
867
			.fadeOut('slow');
868
	}
869
}
870
 
871
function requeterIdentite(event) {
1552 isa 872
	var courriel = $('#courriel').val();
1733 isa 873
	if (validerCourriel(courriel)) {
1552 isa 874
		miseAJourCourriel();
1733 isa 875
		var urlAnnuaire = SERVICE_ANNUAIRE + courriel;
1552 isa 876
		$.ajax({
877
			url : urlAnnuaire,
878
			type : 'GET',
879
			success : function(data, textStatus, jqXHR) {
880
				console.log('Annuaire SUCCESS : ' + textStatus);
881
				if (data != undefined && data[courriel] != undefined) {
882
					var infos = data[courriel];
1733 isa 883
					$('#id-utilisateur').val(infos.id);
884
					$('#prenom-utilisateur').val(infos.prenom);
885
					$('#nom-utilisateur').val(infos.nom);
886
					$('#courriel-confirmation').val(courriel);
887
					$('#prenom-utilisateur, #nom-utilisateur, #courriel-confirmation').attr('disabled', 'disabled');
888
 
889
					if ($('#courriel-memoire').is(':checked')) {
890
						bdd.setItem('utilisateur.prenom',  $("#prenom-utilisateur").val());
891
						bdd.setItem('utilisateur.nom',  $("#nom-utilisateur").val());
892
						bdd.setItem('utilisateur.id',  $("#id-utilisateur").val());
893
					}
1552 isa 894
				} else {
895
					surErreurCompletionCourriel();
896
				}
897
			},
898
			error : function(jqXHR, textStatus, errorThrown) {
899
				console.log('Annuaire ERREUR : ' + textStatus);
900
				surErreurCompletionCourriel();
901
			},
902
			complete : function(jqXHR, textStatus) {
903
				console.log('Annuaire COMPLETE : ' + textStatus);
1733 isa 904
				$('#zone-prenom-nom').removeClass('hidden');
905
				$('#zone-courriel-confirmation').removeClass('hidden');
1552 isa 906
			}
907
		});
908
	}
1733 isa 909
 
910
	event.preventDefault();
911
	event.stopPropagation();
1552 isa 912
}
913
 
1733 isa 914
function validerCourriel(email) {
915
    var regex = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i),
916
		flag = regex.test(email);
917
 
918
    console.log('Valid email ? (', email, ') : ', flag);
919
    return flag;
920
}
1552 isa 921
 
922
function miseAJourCourriel() {
1733 isa 923
	if ($('#courriel-memoire').is(':checked')) {
924
		bdd.setItem('utilisateur.courriel',  $("#courriel").val());
1552 isa 925
	}
926
}
1733 isa 927
 
928
function surErreurCompletionCourriel() {
929
	$('#id-utilisateur').val('');
930
	$('#prenom-utilisateur, #nom-utilisateur, #courriel-confirmation').removeAttr('disabled');
931
}