Subversion Repositories eFlore/Applications.cel

Rev

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