Subversion Repositories eFlore/Applications.cel

Rev

Rev 3987 | Rev 3989 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 3987 Rev 3988
1
function WidgetPhotoPopup( proprietes ) {
1
function WidgetPhotoPopup( proprietes ) {
2
	if( this.valOk( proprietes ) ) {
2
	if( this.valOk( proprietes ) ) {
3
		this.urlWidget                    = proprietes.urlWidget;
3
		this.urlWidget                    = proprietes.urlWidget;
4
		this.urls                         = proprietes.urls;
4
		this.urls                         = proprietes.urls;
5
		this.infosImages                  = proprietes.infosImages;
5
		this.infosImages                  = proprietes.infosImages;
6
		this.urlImage                     = proprietes.urlImage;
6
		this.urlImage                     = proprietes.urlImage;
7
		this.indexPremiereImage           = proprietes.indexPremiereImage;
7
		this.indexPremiereImage           = proprietes.indexPremiereImage;
8
		this.indexImage                   = this.indexPremiereImage;
8
		this.indexImage                   = this.indexPremiereImage;
9
		this.tailleMax                    = proprietes.tailleMax;
9
		this.tailleMax                    = proprietes.tailleMax;
10
		this.popupUrl                     = proprietes.popupUrl;
10
		this.popupUrl                     = proprietes.popupUrl;
11
		this.urlBaseTelechargement        = proprietes.urlBaseTelechargement;
11
		this.urlBaseTelechargement        = proprietes.urlBaseTelechargement;
12
		this.urlServiceRegenererMiniature = proprietes.urlServiceRegenererMiniature;
12
		this.urlServiceRegenererMiniature = proprietes.urlServiceRegenererMiniature;
13
		this.userId       				  = proprietes.userId;
13
		this.userId       				  = proprietes.userId;
14
		this.token						  = proprietes.token;
14
		this.token						  = proprietes.token;
15
		this.protocoles					  = proprietes.protocoles;
15
		this.protocoles					  = proprietes.protocoles;
16
		this.urlServiceDel				  = proprietes.urlServiceDel;
16
		this.urlServiceDel				  = proprietes.urlServiceDel;
17
		this.urlServiceNewCel			  = proprietes.urlServiceNewCel;
17
		this.urlServiceNewCel			  = proprietes.urlServiceNewCel;
18
	}
18
	}
19
	this.protocole = null;
19
	this.protocole = null;
20
	this.voteId = null;
20
	this.voteId = null;
21
	this.votes = null;
21
	this.votes = null;
22
	this.mettreAJourInfosImage();
22
	this.mettreAJourInfosImage();
23
	// console.log(proprietes)
-
 
24
}
23
}
25
 
24
 
26
WidgetPhotoPopup.prototype = new WidgetPhotoCommun();
25
WidgetPhotoPopup.prototype = new WidgetPhotoCommun();
27
 
26
 
28
WidgetPhotoPopup.prototype.initTpl = function() {
27
WidgetPhotoPopup.prototype.initTpl = function() {
29
	this.redimensionnerGalerie();
28
	this.redimensionnerGalerie();
30
	$( '#info-img-galerie' ).find( '.active' ).removeClass( 'active' );
29
	$( '#info-img-galerie' ).find( '.active' ).removeClass( 'active' );
31
	$( '#img-cadre-' + this.indexImage + ',#indicateur-img-' + this.indexImage ).addClass( 'active' );
30
	$( '#img-cadre-' + this.indexImage + ',#indicateur-img-' + this.indexImage ).addClass( 'active' );
32
 
31
 
33
	this.mettreAJourPopup();
32
	this.mettreAJourPopup();
34
 
33
 
35
	this.redimentionnerModaleCarousel();
34
	this.redimentionnerModaleCarousel();
36
};
35
};
37
 
36
 
38
WidgetPhotoPopup.prototype.initEvts = function() {
37
WidgetPhotoPopup.prototype.initEvts = function() {
39
	const lthis = this;
38
	const lthis = this;
40
 
39
 
41
	this.initEvtsDefilerImage();
40
	this.initEvtsDefilerImage();
42
	// this.initEvtsContact();
41
	// this.initEvtsContact();
43
	$( window ).on( 'resize', lthis.redimentionnerModaleCarousel.bind( lthis ) );
42
	$( window ).on( 'resize', lthis.redimentionnerModaleCarousel.bind( lthis ) );
44
	this.initEvtsFonctionsPhoto();
43
	this.initEvtsFonctionsPhoto();
45
	this.initEvtsRetourGalerieResponsive();
44
	this.initEvtsRetourGalerieResponsive();
46
};
45
};
47
 
46
 
48
WidgetPhotoPopup.prototype.mettreAJourPopup = function() {
47
WidgetPhotoPopup.prototype.mettreAJourPopup = function() {
49
	this.mettreAJourInfosImage();
48
	this.mettreAJourInfosImage();
50
	this.afficherTitreImage();
49
	this.afficherTitreImage();
51
	this.traiterMetas();
50
	this.traiterMetas();
52
	this.regenererMiniature();
51
	this.regenererMiniature();
53
	this.fournirLienIdentiplante();
52
	this.fournirLienIdentiplante();
54
	this.pivoterImage();
53
	this.pivoterImage();
55
	this.initEvtsProtocole();
54
	this.initEvtsProtocole();
56
	this.initEvtsTagsPF();
55
	this.initEvtsTagsPF();
57
	this.initEvtsTagsCel();
56
	this.initEvtsTagsCel();
58
};
57
};
59
 
58
 
60
WidgetPhotoPopup.prototype.mettreAJourInfosImage = function() {
59
WidgetPhotoPopup.prototype.mettreAJourInfosImage = function() {
61
	this.item          = this.infosImages[this.urls[this.indexImage]];
60
	this.item          = this.infosImages[this.urls[this.indexImage]];
62
	this.titreImage    = this.item['titre'];
61
	this.titreImage    = this.item['titre'];
63
	this.urlLienEflore = this.item['lien'];
62
	this.urlLienEflore = this.item['lien'];
64
	this.idImage       = this.item['id_photo'];
63
	this.idImage       = this.item['id_photo'];
65
 
64
 
66
	// If last caract of the url is a ',' we remove it
65
	// If last caract of the url is a ',' we remove it
67
	const lastCaractUrlImage = this.item['url_photo'].slice(-1);
66
	const lastCaractUrlImage = this.item['url_photo'].slice(-1);
68
	if (lastCaractUrlImage === ','){
67
	if (lastCaractUrlImage === ','){
69
		this.item['url_photo'] = this.item['url_photo'].replace(/.$/,'');
68
		this.item['url_photo'] = this.item['url_photo'].replace(/.$/,'');
70
	}
69
	}
71
 
70
 
72
	this.urlThisImage  = this.item['url_photo']+'.jpg';
71
	this.urlThisImage  = this.item['url_photo']+'.jpg';
73
	this.obs           = this.item['obs'];
72
	this.obs           = this.item['obs'];
74
	this.nn            = '[nn' + this.obs['nom_sel_nn']+']';
73
	this.nn            = '[nn' + this.obs['nom_sel_nn']+']';
75
	this.urlIP         = this.obs['url_ip'];
74
	this.urlIP         = this.obs['url_ip'];
76
	this.tagsImage     = this.tagsToArray( this.item['tags_photo'] );
75
	this.tagsImage     = this.tagsToArray( this.item['tags_photo'] );
77
	this.tagsObs       = this.tagsToArray( this.obs['tags_obs'] );
76
	this.tagsObs       = this.tagsToArray( this.obs['tags_obs'] );
78
	let auteurMail = this.item['utilisateur']['mail_utilisateur'].split("@")[0];
77
	let auteurMail = this.item['utilisateur']['mail_utilisateur'].split("@")[0];
79
	this.auteur        = this.item["utilisateur"]["nom_utilisateur"] ? this.item["utilisateur"]["nom_utilisateur"] : auteurMail;
78
	this.auteur        = this.item["utilisateur"]["nom_utilisateur"] ? this.item["utilisateur"]["nom_utilisateur"] : auteurMail;
80
	this.date          = this.item['date'];
79
	this.date          = this.item['date'];
81
	this.urlTpl 	   = this.item['url_tpl'];
80
	this.urlTpl 	   = this.item['url_tpl'];
82
};
81
};
83
 
82
 
84
WidgetPhotoPopup.prototype.tagsToArray = function( tags ) {
83
WidgetPhotoPopup.prototype.tagsToArray = function( tags ) {
85
	if(!this.valOk(tags)) {
84
	if(!this.valOk(tags)) {
86
		return [];
85
		return [];
87
	}
86
	}
88
	tags = tags.replace( new RegExp('\\.'), '' ).split( ',' );
87
	tags = tags.replace( new RegExp('\\.'), '' ).split( ',' );
89
 
88
 
90
	let cleanTags       = [],
89
	let cleanTags       = [],
91
		nbTags          = tags.length,
90
		nbTags          = tags.length,
92
		tag             = '',
91
		tag             = '',
93
		tagsSansEspaces = '',
92
		tagsSansEspaces = '',
94
		cleanTagIndex   = 0;
93
		cleanTagIndex   = 0;
95
 
94
 
96
	for(let i = 0; i < nbTags; i++) {
95
	for(let i = 0; i < nbTags; i++) {
97
		tag = tags[i];
96
		tag = tags[i];
98
		tagsSansEspaces = tag.replace( ' ', '');
97
		tagsSansEspaces = tag.replace( ' ', '');
99
		if( '' !== tagsSansEspaces ) {
98
		if( '' !== tagsSansEspaces ) {
100
			cleanTags.push( tag.trim() );
99
			cleanTags.push( tag.trim() );
101
		}
100
		}
102
	}
101
	}
103
 
102
 
104
	return cleanTags;
103
	return cleanTags;
105
};
104
};
106
 
105
 
107
WidgetPhotoPopup.prototype.initEvtsDefilerImage = function() {
106
WidgetPhotoPopup.prototype.initEvtsDefilerImage = function() {
108
	const lthis = this;
107
	const lthis = this;
109
 
108
 
110
	$( '#precedent, #suivant' ).off('click');
109
	$( '#precedent, #suivant' ).off('click');
111
 
110
 
112
	$( '#precedent, #suivant' ).on( 'click', function() {
111
	$( '#precedent, #suivant' ).on( 'click', function() {
113
		lthis.defilerImage( this.id );
112
		lthis.defilerImage( this.id );
114
		lthis.initEvtsTagsPF();
113
		lthis.initEvtsTagsPF();
115
	});
114
	});
116
 
115
 
117
	$( '#print_content:not(saisir-tag)' ).on( 'keydown', function( event ) {
116
	$( '#print_content:not(saisir-tag)' ).on( 'keydown', function( event ) {
118
 
117
 
119
		const determinerSens = function( enventKey, left, right ) {
118
		const determinerSens = function( enventKey, left, right ) {
120
			switch ( enventKey ) {
119
			switch ( enventKey ) {
121
				case left:
120
				case left:
122
					return 'suivant';
121
					return 'suivant';
123
				case right:
122
				case right:
124
					return 'precedent';
123
					return 'precedent';
125
				default:
124
				default:
126
					break;
125
					break;
127
			}
126
			}
128
 
127
 
129
			return;
128
			return;
130
		}
129
		}
131
 
130
 
132
		event = (event || window.event);
131
		event = (event || window.event);
133
		// event.keyCode déprécié, on tente d'abord event.key
132
		// event.keyCode déprécié, on tente d'abord event.key
134
		let sens = ( 'key' in event ) ? determinerSens( event.key, 'ArrowLeft', 'ArrowRight' ) : determinerSens( event.keyCode, 37, 39 );;
133
		let sens = ( 'key' in event ) ? determinerSens( event.key, 'ArrowLeft', 'ArrowRight' ) : determinerSens( event.keyCode, 37, 39 );;
135
console.log(sens);
134
console.log(sens);
136
		if ( lthis.valOk( sens ) ) {
135
		if ( lthis.valOk( sens ) ) {
137
			lthis.defilerImage( sens );
136
			lthis.defilerImage( sens );
138
		}
137
		}
139
	});
138
	});
140
};
139
};
141
 
140
 
142
// WidgetPhotoPopup.prototype.initEvtsContact = function() {
141
// WidgetPhotoPopup.prototype.initEvtsContact = function() {
143
// 	const lthis = this;
142
// 	const lthis = this;
144
//
143
//
145
// 	$( '#bloc-infos-img' ).on( 'click', '.lien_contact', function( event ) {
144
// 	$( '#bloc-infos-img' ).on( 'click', '.lien_contact', function( event ) {
146
// 		event.preventDefault();
145
// 		event.preventDefault();
147
// 		lthis.chargerContenuModale( this.href );
146
// 		lthis.chargerContenuModale( this.href );
148
// 	});
147
// 	});
149
// };
148
// };
150
 
149
 
151
WidgetPhotoPopup.prototype.initEvtsFonctionsPhoto = function() {
150
WidgetPhotoPopup.prototype.initEvtsFonctionsPhoto = function() {
152
	const lthis = this;
151
	const lthis = this;
153
 
152
 
154
	$( '#boutons-footer #bloc-fct a, #retour-metas' ).on( 'click', function( event ){
153
	$( '#boutons-footer #bloc-fct a, #retour-metas' ).on( 'click', function( event ){
155
		event.preventDefault();
154
		event.preventDefault();
156
		var voletAOuvrir = $( this ).data( 'volet' ),
155
		var voletAOuvrir = $( this ).data( 'volet' ),
157
			voletAFermer = $( '.bloc-volet:not(.hidden)' ).data( 'volet' );
156
			voletAFermer = $( '.bloc-volet:not(.hidden)' ).data( 'volet' );
158
 
157
 
159
		lthis.ouvrirVoletFct( voletAOuvrir, voletAFermer );
158
		lthis.ouvrirVoletFct( voletAOuvrir, voletAFermer );
160
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
159
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
161
			$( '#info-img-galerie' ).addClass( 'hidden' );
160
			$( '#info-img-galerie' ).addClass( 'hidden' );
162
			$( '#volet, #retour-galerie' ).removeClass( 'hidden' );
161
			$( '#volet, #retour-galerie' ).removeClass( 'hidden' );
163
		}
162
		}
164
	});
163
	});
165
};
164
};
166
 
165
 
167
WidgetPhotoPopup.prototype.initEvtsRetourGalerieResponsive = function() {
166
WidgetPhotoPopup.prototype.initEvtsRetourGalerieResponsive = function() {
168
	$( '#retour-galerie' ).on( 'click', function( event ) {
167
	$( '#retour-galerie' ).on( 'click', function( event ) {
169
		event.preventDefault();
168
		event.preventDefault();
170
		$( '#info-img-galerie' ).removeClass( 'hidden' );
169
		$( '#info-img-galerie' ).removeClass( 'hidden' );
171
		$( this ).addClass( 'hidden' );
170
		$( this ).addClass( 'hidden' );
172
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
171
		if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
173
			$( '#volet' ).addClass( 'hidden' );
172
			$( '#volet' ).addClass( 'hidden' );
174
			$( '.bouton-fct.actif' ).removeClass( 'actif' );
173
			$( '.bouton-fct.actif' ).removeClass( 'actif' );
175
		}
174
		}
176
	});
175
	});
177
};
176
};
178
 
177
 
179
WidgetPhotoPopup.prototype.initEvtsTagsCel = function(){
178
WidgetPhotoPopup.prototype.initEvtsTagsCel = function(){
180
	const lthis = this;
179
	const lthis = this;
181
	$( '#tags-cel' ).html('');
180
	$( '#tags-cel' ).html('');
182
 
181
 
183
	$( '#tags-cel' ).append(
182
	$( '#tags-cel' ).append(
184
		"<p>"+ lthis.item['tags_photo']+"</p>"
183
		"<p>"+ lthis.item['tags_photo']+"</p>"
185
	)
184
	)
186
}
185
}
187
 
186
 
188
WidgetPhotoPopup.prototype.initEvtsTagsPF = function() {
187
WidgetPhotoPopup.prototype.initEvtsTagsPF = function() {
189
	const tagsPfDiv = $('#tags-pf');
188
	const tagsPfDiv = $('#tags-pf');
190
	tagsPfDiv.html('');
189
	tagsPfDiv.html('');
191
	tagsPfDiv.append('<a id="port" class="btn tag">Port</a>' +
190
	tagsPfDiv.append('<a id="port" class="btn tag">Port</a>' +
192
		'<a id="fleur" class="btn tag">Fleur</a>' +
191
		'<a id="fleur" class="btn tag">Fleur</a>' +
193
		'<a id="fruit" class="btn tag">Fruit</a>' +
192
		'<a id="fruit" class="btn tag">Fruit</a>' +
194
		'<a id="feuille" class="btn tag">Feuille</a>' +
193
		'<a id="feuille" class="btn tag">Feuille</a>' +
195
		'<a id="ecorce" class="btn tag">Ecorce</a>' +
194
		'<a id="ecorce" class="btn tag">Ecorce</a>' +
196
		'<a id="rameau" class="btn tag">Rameau</a>' +
195
		'<a id="rameau" class="btn tag">Rameau</a>' +
197
		'<a id="planche" class="btn tag">Planche</a>' +
196
		'<a id="planche" class="btn tag">Planche</a>' +
198
		'<a id="rosette" class="btn tag">Rosette</a>' +
197
		'<a id="rosette" class="btn tag">Rosette</a>' +
199
		'<a id="pousse" class="btn tag">Pousse</a>');
198
		'<a id="pousse" class="btn tag">Pousse</a>');
200
 
199
 
201
	this.tagsPf();
200
	this.tagsPf();
202
	this.tagsPfCustom();
201
	this.tagsPfCustom();
203
 
202
 
204
	$( '#bloc-tags' ).off('click');
203
	$( '#bloc-tags' ).off('click');
205
 
204
 
206
	$( '#bloc-tags' ).on( 'click', '.tag', function( event ) {
205
	$( '#bloc-tags' ).on( 'click', '.tag', function( event ) {
207
		event.preventDefault();
206
		event.preventDefault();
208
		$( this ).toggleClass( 'actif' );
207
		$( this ).toggleClass( 'actif' );
209
 
208
 
210
		var motCleClique = '';
209
		var motCleClique = '';
211
		motCleClique = $(this).attr('id');
210
		motCleClique = $(this).attr('id');
212
 
211
 
213
		// Utiliser la méthode findIndex pour obtenir l'index de l'élément dans le tableau
212
		// Utiliser la méthode findIndex pour obtenir l'index de l'élément dans le tableau
214
		var indexElementTrouve = lthis.item['tags_pf'].findIndex(function (tag) {
213
		var indexElementTrouve = lthis.item['tags_pf'].findIndex(function (tag) {
215
			return tag['mot_cle'] === motCleClique;
214
			return tag['mot_cle'] === motCleClique;
216
		});
215
		});
217
 
216
 
218
		// Vérifier si l'élément a été trouvé
217
		// Vérifier si l'élément a été trouvé
219
		if (indexElementTrouve !== -1) {
218
		if (indexElementTrouve !== -1) {
220
			//supprimer tag dans DEL
219
			//supprimer tag dans DEL
221
			if (lthis.item['tags_pf'][indexElementTrouve].hasOwnProperty('id_mot_cle') && lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle'] != ''){
220
			if (lthis.item['tags_pf'][indexElementTrouve].hasOwnProperty('id_mot_cle') && lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle'] != ''){
222
				let url = lthis.urlServiceDel + 'mots-cles/' + lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle']
221
				let url = lthis.urlServiceDel + 'mots-cles/' + lthis.item['tags_pf'][indexElementTrouve]['id_mot_cle']
223
 
222
 
224
				lthis.envoyerVersService('DELETE', url)
223
				lthis.envoyerVersService('DELETE', url)
225
			}
224
			}
226
 
225
 
227
			// Supprimer l'élément de this.item['tags_pf'] à l'index trouvé
226
			// Supprimer l'élément de this.item['tags_pf'] à l'index trouvé
228
			lthis.item['tags_pf'].splice(indexElementTrouve, 1);
227
			lthis.item['tags_pf'].splice(indexElementTrouve, 1);
229
		} else {
228
		} else {
230
			//Ajout tag dans le DEL
229
			//Ajout tag dans le DEL
231
			let url = lthis.urlServiceDel + 'mots-cles';
230
			let url = lthis.urlServiceDel + 'mots-cles';
232
			let donnees = {
231
			let donnees = {
233
				"image" : lthis.idImage,
232
				"image" : lthis.idImage,
234
				"mot_cle" : motCleClique,
233
				"mot_cle" : motCleClique,
235
				"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
234
				"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
236
			}
235
			}
237
 
236
 
238
			lthis.envoyerVersService('PUT', url, null, JSON.stringify(donnees), function (erreur, tagId) {
237
			lthis.envoyerVersService('PUT', url, null, JSON.stringify(donnees), function (erreur, tagId) {
239
				if (erreur) {
238
				if (erreur) {
240
					console.error("Erreur lors de la requête :", erreur);
239
					console.error("Erreur lors de la requête :", erreur);
241
				} else {
240
				} else {
242
					console.log('tag : ' + motCleClique + ' ajouté');
241
					console.log('tag : ' + motCleClique + ' ajouté');
243
					lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : motCleClique})
242
					lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : motCleClique})
244
				}
243
				}
245
			});
244
			});
246
		}
245
		}
247
		//TODO post vers le del
-
 
248
	});
246
	});
249
	/* //@TODO est-ce qu'on garde cette croix?
247
	/* //@TODO est-ce qu'on garde cette croix?
250
	$( '#bloc-tags' ).on( 'click', '.custom-tag.actif .fermer', function( event ) {
248
	$( '#bloc-tags' ).on( 'click', '.custom-tag.actif .fermer', function( event ) {
251
		event.preventDefault();
249
		event.preventDefault();
252
		//			Supprimer un custom-tag
250
		//			Supprimer un custom-tag
253
		//	_OPTIONS
251
		//	_OPTIONS
254
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
252
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
255
		// 	_paramètres
253
		// 	_paramètres
256
		// L'id du tag à la fin de l'url
254
		// L'id du tag à la fin de l'url
257
		//	_DELETE
255
		//	_DELETE
258
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
256
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
259
		// 	_réponse:
257
		// 	_réponse:
260
		// ""
258
		// ""
261
		// 			Mettre à jour les mots cles
259
		// 			Mettre à jour les mots cles
262
		//	_OPTIONS
260
		//	_OPTIONS
263
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
261
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
264
		//	_GET
262
		//	_GET
265
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
263
		// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
266
		$( this ).parent( '.custom-tag' ).remove();
264
		$( this ).parent( '.custom-tag' ).remove();
267
	});
265
	});
268
	*/
266
	*/
269
/*
267
/*
270
	$( '#bloc-tags' ).on( 'keyup', '.custom-tag.actif', function( event ) {
268
	$( '#bloc-tags' ).on( 'keyup', '.custom-tag.actif', function( event ) {
271
		let supprimerTag = false;
269
		let supprimerTag = false;
272
 
270
 
273
		event = ( event || window.event );
271
		event = ( event || window.event );
274
		// event.keyCode déprécié, on tente d'abord event.key
272
		// event.keyCode déprécié, on tente d'abord event.key
275
		if ( 'key' in event ) {
273
		if ( 'key' in event ) {
276
			supprimerTag = ( 'Delete' === event.key || 'Backspace' === event.key );
274
			supprimerTag = ( 'Delete' === event.key || 'Backspace' === event.key );
277
		} else {
275
		} else {
278
			supprimerTag = ( 46 === event.keyCode || 8 === event.keyCode );
276
			supprimerTag = ( 46 === event.keyCode || 8 === event.keyCode );
279
		}
277
		}
280
		if ( supprimerTag ) {
278
		if ( supprimerTag ) {
281
			//			Supprimer un custom-tag
279
			//			Supprimer un custom-tag
282
			//	_OPTIONS
280
			//	_OPTIONS
283
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
281
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
284
			// 	_paramètres
282
			// 	_paramètres
285
			// L'id du tag à la fin de l'url
283
			// L'id du tag à la fin de l'url
286
			//	_DELETE
284
			//	_DELETE
287
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
285
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles/38368
288
			// 	_réponse:
286
			// 	_réponse:
289
			// ""
287
			// ""
290
			// 			Mettre à jour les mots cles
288
			// 			Mettre à jour les mots cles
291
			//	_OPTIONS
289
			//	_OPTIONS
292
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
290
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
293
			//	_GET
291
			//	_GET
294
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
292
			// https://api-test.tela-botanica.org/service:del:0.1/mots-cles?image=197938
295
			$( this ).parent( '.custom-tag' ).remove();
293
			$( this ).parent( '.custom-tag' ).remove();
296
		}
294
		}
297
	});
295
	});
298
 */
296
 */
299
};
297
};
300
 
298
 
301
WidgetPhotoPopup.prototype.defilerImage = function( sens ) {
299
WidgetPhotoPopup.prototype.defilerImage = function( sens ) {
302
	if ( 'suivant' === sens ) {
300
	if ( 'suivant' === sens ) {
303
		this.indexImage++ ;
301
		this.indexImage++ ;
304
		if( this.indexImage >= this.urls.length ) {
302
		if( this.indexImage >= this.urls.length ) {
305
			this.indexImage = 0;
303
			this.indexImage = 0;
306
		}
304
		}
307
	} else if ( 'precedent' === sens ) {
305
	} else if ( 'precedent' === sens ) {
308
		this.indexImage--;
306
		this.indexImage--;
309
		if( this.indexImage < 0 ) {
307
		if( this.indexImage < 0 ) {
310
			this.indexImage = this.urls.length -1;
308
			this.indexImage = this.urls.length -1;
311
		}
309
		}
312
	}
310
	}
313
	// @TODO: Modifier l'attr content de 'meta[property=og:image]' et y mettre l'url de l'image
311
	// @TODO: Modifier l'attr content de 'meta[property=og:image]' et y mettre l'url de l'image
314
	this.mettreAJourPopup();
312
	this.mettreAJourPopup();
315
};
313
};
316
 
314
 
317
WidgetPhotoPopup.prototype.afficherTitreImage = function() {
315
WidgetPhotoPopup.prototype.afficherTitreImage = function() {
318
	let lienContact  =
316
	let lienContact  =
319
			this.urlWidget +'?mode=contact&nn=' + this.nn +
317
			this.urlWidget +'?mode=contact&nn=' + this.nn +
320
			'&nom_sci=' + this.obs['nom_sel'] +
318
			'&nom_sci=' + this.obs['nom_sel'] +
321
			'&date=' + this.date +
319
			'&date=' + this.date +
322
			'&localisation=' + this.obs['localisation'] +
320
			'&localisation=' + this.obs['localisation'] +
323
			'&id_image=' + this.idImage +
321
			'&id_image=' + this.idImage +
324
			'&auteur=' + this.auteur;
322
			'&auteur=' + this.auteur;
325
 
323
 
326
	if ( this.valOk( this.popupUrl ) ) {
324
	if ( this.valOk( this.popupUrl ) ) {
327
		if (! this.popupUrl.match( new RegExp( 'img:' + this.idImage ) ) ) {
325
		if (! this.popupUrl.match( new RegExp( 'img:' + this.idImage ) ) ) {
328
			this.popupUrl = this.actualiserPopupUrl( this.popupUrl, this.urlThisImage );
326
			this.popupUrl = this.actualiserPopupUrl( this.popupUrl, this.urlThisImage );
329
		}
327
		}
330
		lienContact += '&popup_url=' + encodeURIComponent( this.popupUrl );
328
		lienContact += '&popup_url=' + encodeURIComponent( this.popupUrl );
331
	}
329
	}
332
 
330
 
333
	$( '#bloc-infos-img' ).html(
331
	$( '#bloc-infos-img' ).html(
334
		this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] )+
332
		this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] )+
335
		' par '+
333
		' par '+
336
		'<a class="lien_contact" href="' + this.item['urlProfil'] + '" target="_blank" title="Afficher le profil">' + this.auteur + '</a> '+
334
		'<a class="lien_contact" href="' + this.item['urlProfil'] + '" target="_blank" title="Afficher le profil">' + this.auteur + '</a> '+
337
		' le ' + this.date + ' - ' + this.obs['localisation']
335
		' le ' + this.date + ' - ' + this.obs['localisation']
338
	);
336
	);
339
};
337
};
340
 
338
 
341
WidgetPhotoPopup.prototype.actualiserPopupUrl = function( queryString, remplacement ) {
339
WidgetPhotoPopup.prototype.actualiserPopupUrl = function( queryString, remplacement ) {
342
	let queryStringParsee = queryString.substring(1).split('&');
340
	let queryStringParsee = queryString.substring(1).split('&');
343
 
341
 
344
	$.each( queryStringParsee,  function( i, param ) {
342
	$.each( queryStringParsee,  function( i, param ) {
345
		if( /url_image/.test( param ) ) {
343
		if( /url_image/.test( param ) ) {
346
			queryString = queryString.replace( param, 'url_image=' + remplacement );
344
			queryString = queryString.replace( param, 'url_image=' + remplacement );
347
			return false;
345
			return false;
348
		}
346
		}
349
	});
347
	});
350
	return queryString;
348
	return queryString;
351
};
349
};
352
 
350
 
353
WidgetPhotoPopup.prototype.redimentionnerModaleCarousel = function() {
351
WidgetPhotoPopup.prototype.redimentionnerModaleCarousel = function() {
354
	this.redimensionnerGalerie();
352
	this.redimensionnerGalerie();
355
	if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
353
	if ( window.matchMedia( '(max-width: 991px)' ).matches ) {
356
		$( '#volet, #retour-galerie' ).addClass( 'hidden' );
354
		$( '#volet, #retour-galerie' ).addClass( 'hidden' );
357
		$( '#info-img-galerie' ).removeClass( 'hidden' );
355
		$( '#info-img-galerie' ).removeClass( 'hidden' );
358
		$( '.bouton-fct.actif' ).removeClass( 'actif' );
356
		$( '.bouton-fct.actif' ).removeClass( 'actif' );
359
		$( '.nettoyage-volet.haut' ).text( $( '#bloc-infos-img' ).text() );
357
		$( '.nettoyage-volet.haut' ).text( $( '#bloc-infos-img' ).text() );
360
		$( '#boutons-footer, #info-img-galerie' ).removeClass( 'col-lg-8' );
358
		$( '#boutons-footer, #info-img-galerie' ).removeClass( 'col-lg-8' );
361
		$( '#bloc-infos-img, #volet' ).removeClass( 'col-lg-4' );
359
		$( '#bloc-infos-img, #volet' ).removeClass( 'col-lg-4' );
362
	} else {
360
	} else {
363
		$( '#volet, #info-img-galerie' ).removeClass( 'hidden' );
361
		$( '#volet, #info-img-galerie' ).removeClass( 'hidden' );
364
		if ( this.valOk( $( '.bloc-volet:not(.hidden)' ) ) ) {
362
		if ( this.valOk( $( '.bloc-volet:not(.hidden)' ) ) ) {
365
			$( '.bouton-fct.' + $( '.bloc-volet:not(.hidden)' ).data( 'volet' ) ).addClass( 'actif' );
363
			$( '.bouton-fct.' + $( '.bloc-volet:not(.hidden)' ).data( 'volet' ) ).addClass( 'actif' );
366
		}
364
		}
367
		$( '.nettoyage-volet.bas' ).text( $( '#bloc-infos-img' ).text() );
365
		$( '.nettoyage-volet.bas' ).text( $( '#bloc-infos-img' ).text() );
368
		$( '#boutons-footer, #info-img-galerie' ).addClass( 'col-lg-8' );
366
		$( '#boutons-footer, #info-img-galerie' ).addClass( 'col-lg-8' );
369
		$( '#bloc-infos-img, #volet' ).addClass( 'col-lg-4' );
367
		$( '#bloc-infos-img, #volet' ).addClass( 'col-lg-4' );
370
		$( '#retour-galerie' ).addClass( 'hidden' );
368
		$( '#retour-galerie' ).addClass( 'hidden' );
371
	}
369
	}
372
};
370
};
373
 
371
 
374
WidgetPhotoPopup.prototype.redimensionnerGalerie = function() {
372
WidgetPhotoPopup.prototype.redimensionnerGalerie = function() {
375
	var maxSize = ( $( window ).width() / $( window ).height() ) < 1 ? $( window ).width() : $( window ).height();
373
	var maxSize = ( $( window ).width() / $( window ).height() ) < 1 ? $( window ).width() : $( window ).height();
376
 
374
 
377
	maxSize -= 30;
375
	maxSize -= 30;
378
	$( '.carousel-item img' ).each( function( index, image ) {
376
	$( '.carousel-item img' ).each( function( index, image ) {
379
		var proportion  = image.dataset.width / image.dataset.height,
377
		var proportion  = image.dataset.width / image.dataset.height,
380
			cssResize   = {};
378
			cssResize   = {};
381
 
379
 
382
		if ( proportion >= 1 ) {
380
		if ( proportion >= 1 ) {
383
			cssResize['width'] = maxSize;
381
			cssResize['width'] = maxSize;
384
		}
382
		}
385
		if ( proportion <= 1) {
383
		if ( proportion <= 1) {
386
			cssResize['height'] = maxSize;
384
			cssResize['height'] = maxSize;
387
		}
385
		}
388
		$( image ).css( cssResize );
386
		$( image ).css( cssResize );
389
	});
387
	});
390
};
388
};
391
 
389
 
392
WidgetPhotoPopup.prototype.ouvrirVoletFct = function( voletAOuvrir, voletAFermer ) {
390
WidgetPhotoPopup.prototype.ouvrirVoletFct = function( voletAOuvrir, voletAFermer ) {
393
	if( voletAOuvrir !== voletAFermer ) {
391
	if( voletAOuvrir !== voletAFermer ) {
394
		$( '#boutons-footer  .' + voletAFermer ).removeClass( 'actif' );
392
		$( '#boutons-footer  .' + voletAFermer ).removeClass( 'actif' );
395
		$( '#boutons-footer  .' + voletAOuvrir ).addClass( 'actif' );
393
		$( '#boutons-footer  .' + voletAOuvrir ).addClass( 'actif' );
396
		$( '#bloc-' + voletAFermer ).addClass( 'hidden' );
394
		$( '#bloc-' + voletAFermer ).addClass( 'hidden' );
397
		$( '#bloc-' + voletAOuvrir ).removeClass( 'hidden' );
395
		$( '#bloc-' + voletAOuvrir ).removeClass( 'hidden' );
398
		$( '#volet' ).scrollTop(0);
396
		$( '#volet' ).scrollTop(0);
399
		$( '#retour-metas' ).removeClass( 'hidden', 'meta' === voletAOuvrir );
397
		$( '#retour-metas' ).removeClass( 'hidden', 'meta' === voletAOuvrir );
400
	}
398
	}
401
};
399
};
402
 
400
 
403
WidgetPhotoPopup.prototype.tagsPf = function () {
401
WidgetPhotoPopup.prototype.tagsPf = function () {
404
	const lthis = this;
402
	const lthis = this;
405
	$('#tags-pf-supp').html('');
403
	$('#tags-pf-supp').html('');
406
 
404
 
407
	lthis.item['tags_pf'].forEach(tag => {
405
	lthis.item['tags_pf'].forEach(tag => {
408
		const tagElement = document.getElementById(tag['mot_cle']);
406
		const tagElement = document.getElementById(tag['mot_cle']);
409
 
407
 
410
		// Vérifier si l'élément existe
408
		// Vérifier si l'élément existe
411
		if (tagElement) {
409
		if (tagElement) {
412
			// Ajouter la classe 'active' à l'élément <a>
410
			// Ajouter la classe 'active' à l'élément <a>
413
			tagElement.classList.add('actif');
411
			tagElement.classList.add('actif');
414
		} else {
412
		} else {
415
			$('#tags-pf-supp').append('<a id="'+tag['mot_cle']+'" class="btn tag custom-tag actif">' + tag['mot_cle'] + '&nbsp;' +
413
			$('#tags-pf-supp').append('<a id="'+tag['mot_cle']+'" class="btn tag custom-tag actif">' + tag['mot_cle'] + '&nbsp;' +
416
				// '<i class="fas fa-times-circle fermer"></i>' +
414
				// '<i class="fas fa-times-circle fermer"></i>' +
417
				'</a>')
415
				'</a>')
418
		}
416
		}
419
	});
417
	});
420
}
418
}
421
 
419
 
422
WidgetPhotoPopup.prototype.tagsPfCustom = function() {
420
WidgetPhotoPopup.prototype.tagsPfCustom = function() {
423
	const lthis = this;
421
	const lthis = this;
424
 
422
 
425
	$( '#saisir-tag' ).on( 'blur keyup', function( event ) {
423
	$( '#saisir-tag' ).on( 'blur keyup', function( event ) {
426
		event = ( event || window.event );
424
		event = ( event || window.event );
427
 
425
 
428
		var ajouterTag = ( 'blur' === event.type );
426
		var ajouterTag = ( 'blur' === event.type );
429
 
427
 
430
		// event.keyCode déprécié, on tente d'abord event.key
428
		// event.keyCode déprécié, on tente d'abord event.key
431
		if ( 'key' in event  ) {
429
		if ( 'key' in event  ) {
432
			if ( 'Enter' === event.key ) {
430
			if ( 'Enter' === event.key ) {
433
				ajouterTag = true;
431
				ajouterTag = true;
434
			}
432
			}
435
		} else if ( 13 === event.keyCode ) {
433
		} else if ( 13 === event.keyCode ) {
436
			ajouterTag = true;
434
			ajouterTag = true;
437
		}
435
		}
438
		if	( ajouterTag ) {
436
		if	( ajouterTag ) {
439
			var nouveauTag     = $( this ).val(),
437
			var nouveauTag     = $( this ).val(),
440
				nouveauTagAttr = lthis.chaineValableAttributsHtml( nouveauTag.toLowerCase() );
438
				nouveauTagAttr = lthis.chaineValableAttributsHtml( nouveauTag.toLowerCase() );
441
 
439
 
442
			if( lthis.valOk( nouveauTagAttr ) && !lthis.valOk( $( '#' + nouveauTagAttr + '.tag' ) ) ) {
440
			if( lthis.valOk( nouveauTagAttr ) && !lthis.valOk( $( '#' + nouveauTagAttr + '.tag' ) ) ) {
443
				$( '#tags-pf-supp' ).append(
441
				$( '#tags-pf-supp' ).append(
444
					'<a id="' + nouveauTagAttr + '" class="btn tag custom-tag actif">' +
442
					'<a id="' + nouveauTagAttr + '" class="btn tag custom-tag actif">' +
445
						nouveauTag + '&nbsp;' +
443
						nouveauTag + '&nbsp;' +
446
					// '<i class="fas fa-times-circle fermer"></i>' +
444
					// '<i class="fas fa-times-circle fermer"></i>' +
447
					'</a>'
445
					'</a>'
448
				);
446
				);
449
 
447
 
450
				let url = lthis.urlServiceDel + 'mots-cles';
448
				let url = lthis.urlServiceDel + 'mots-cles';
451
				let donnees = {
449
				let donnees = {
452
					"image" : lthis.idImage,
450
					"image" : lthis.idImage,
453
					"mot_cle" : nouveauTagAttr,
451
					"mot_cle" : nouveauTagAttr,
454
					"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
452
					"auteur.id" : lthis.item["utilisateur"]["id_utilisateur"]
455
				}
453
				}
456
 
454
 
457
				// Envoie du nouveau tag dans le DEL
455
				// Envoie du nouveau tag dans le DEL
458
				lthis.envoyerVersService('PUT', url, null, JSON.stringify(donnees), function (erreur, tagId) {
456
				lthis.envoyerVersService('PUT', url, null, JSON.stringify(donnees), function (erreur, tagId) {
459
					if (erreur) {
457
					if (erreur) {
460
						console.error("Erreur lors de la requête :", erreur);
458
						console.error("Erreur lors de la requête :", erreur);
461
					} else {
459
					} else {
462
						console.log('tag : ' + nouveauTagAttr + ' ajouté');
460
						console.log('tag : ' + nouveauTagAttr + ' ajouté');
463
						lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : nouveauTagAttr})
461
						lthis.item['tags_pf'].push({'id_mot_cle' : tagId['id'][0], 'mot_cle' : nouveauTagAttr})
464
					}
462
					}
465
				});
463
				});
466
 
464
 
467
				// $( '#form-tags-auteur' )[0].reset();
465
				// $( '#form-tags-auteur' )[0].reset();
468
				$( this ).val( '' );
466
				$( this ).val( '' );
469
			}
467
			}
470
		}
468
		}
471
	});
469
	});
472
};
470
};
473
 
471
 
474
WidgetPhotoPopup.prototype.traiterMetas = function() {
472
WidgetPhotoPopup.prototype.traiterMetas = function() {
475
	this.afficherMetas();
473
	this.afficherMetas();
476
	this.afficherPopupLocalisation();
474
	this.afficherPopupLocalisation();
477
	this.afficherMetasPlus();
475
	this.afficherMetasPlus();
478
	this.fournirLienTelechargement();
476
	this.fournirLienTelechargement();
479
};
477
};
480
 
478
 
481
WidgetPhotoPopup.prototype.afficherMetas = function() {
479
WidgetPhotoPopup.prototype.afficherMetas = function() {
482
	const lthis         = this;
480
	const lthis         = this;
483
	const META_CONTENUS = {
481
	const META_CONTENUS = {
484
		'nom' : this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] ),
482
		'nom' : this.afficherLien( this.urlLienEflore, this.obs['nom_sel'] ),
485
		'localisation' : this.obs['localisation'],
483
		'localisation' : this.obs['localisation'],
486
		'auteur' : this.auteur,
484
		'auteur' : this.auteur,
487
		'date-obs' : this.date,
485
		'date-obs' : this.date,
488
		'commentaire' : this.obs['commentaire'],
486
		'commentaire' : this.obs['commentaire'],
489
		'certitude' : this.obs['certitude'],
487
		'certitude' : this.obs['certitude'],
490
		'fiabilite' : this.obs['fiabilite'],
488
		'fiabilite' : this.obs['fiabilite'],
491
		'num-photo' : this.idImage,
489
		'num-photo' : this.idImage,
492
		'titre-original' : this.item['nom_original'],
490
		'titre-original' : this.item['nom_original'],
493
		'date-photo' : this.formaterDate( this.item['date_photo'] ),
491
		'date-photo' : this.formaterDate( this.item['date_photo'] ),
494
		'attribution-copy' : this.item['attribution'],
492
		'attribution-copy' : this.item['attribution'],
495
		'url-copy' : this.urlThisImage
493
		'url-copy' : this.urlThisImage
496
	};
494
	};
497
 
495
 
498
	$.each( META_CONTENUS, function( attrId, contenu ) {
496
	$.each( META_CONTENUS, function( attrId, contenu ) {
499
		let $metaContainer = $( '#bloc-meta #'+attrId );
497
		let $metaContainer = $( '#bloc-meta #'+attrId );
500
 
498
 
501
		if ( lthis.valOk( contenu ) ) {
499
		if ( lthis.valOk( contenu ) ) {
502
			switch( attrId ) {
500
			switch( attrId ) {
503
				case 'attribution-copy' :
501
				case 'attribution-copy' :
504
				case 'url-copy' :
502
				case 'url-copy' :
505
					$metaContainer.val( contenu );
503
					$metaContainer.val( contenu );
506
					lthis.copieAutoChamp( $metaContainer );
504
					lthis.copieAutoChamp( $metaContainer );
507
					break;
505
					break;
508
				case 'nom' :
506
				case 'nom' :
509
					$( '.contenu', $metaContainer ).html( contenu );
507
					$( '.contenu', $metaContainer ).html( contenu );
510
					$( '.bouton', $metaContainer ).attr( 'href', lthis.urlLienEflore );
508
					$( '.bouton', $metaContainer ).attr( 'href', lthis.urlLienEflore );
511
					break;
509
					break;
512
				case 'auteur' :
510
				case 'auteur' :
513
					$( '.bouton', $metaContainer ).attr( 'href', lthis.item['urlProfil'] );
511
					$( '.bouton', $metaContainer ).attr( 'href', lthis.item['urlProfil'] );
514
				default:
512
				default:
515
					$( '.contenu', $metaContainer ).text( contenu );
513
					$( '.contenu', $metaContainer ).text( contenu );
516
					break;
514
					break;
517
			}
515
			}
518
		}
516
		}
519
	});
517
	});
520
};
518
};
521
 
519
 
522
WidgetPhotoPopup.prototype.copieAutoChamp = function( $champACopier ) {
520
WidgetPhotoPopup.prototype.copieAutoChamp = function( $champACopier ) {
523
	$champACopier.off( 'click' ).on( 'click', function() {
521
	$champACopier.off( 'click' ).on( 'click', function() {
524
		$( '#attribution-copy, #url-copy' ).removeClass( 'hidden' )
522
		$( '#attribution-copy, #url-copy' ).removeClass( 'hidden' )
525
			.find( '.copy-message' ).remove();
523
			.find( '.copy-message' ).remove();
526
 
524
 
527
		$( this ).select();
525
		$( this ).select();
528
		document.execCommand( 'copy' );
526
		document.execCommand( 'copy' );
529
 
527
 
530
		$( this ).after(
528
		$( this ).after(
531
			'<p class="copy-message alert-success" style="width: 100%; height:' + $( this ).outerHeight() + 'px; margin: 0; display:flex;">'+
529
			'<p class="copy-message alert-success" style="width: 100%; height:' + $( this ).outerHeight() + 'px; margin: 0; display:flex;">'+
532
				'<span style="margin:auto; font-size:1rem;">Copié dans le presse papier</span>'+
530
				'<span style="margin:auto; font-size:1rem;">Copié dans le presse papier</span>'+
533
			'</p>'
531
			'</p>'
534
		).addClass( 'hidden' );
532
		).addClass( 'hidden' );
535
 
533
 
536
		setTimeout( function() {
534
		setTimeout( function() {
537
			$( '.copy-message' ).remove();
535
			$( '.copy-message' ).remove();
538
			$champACopier.removeClass( 'hidden' );
536
			$champACopier.removeClass( 'hidden' );
539
		}, 1000 );
537
		}, 1000 );
540
	});
538
	});
541
};
539
};
542
 
540
 
543
WidgetPhotoPopup.prototype.afficherMetasPlus = function() {
541
WidgetPhotoPopup.prototype.afficherMetasPlus = function() {
544
	const lthis         = this;
542
	const lthis         = this;
545
	const META_LABELS  = {
543
	const META_LABELS  = {
546
		'id_obs' : 'observation n°',
544
		'id_obs' : 'observation n°',
547
		'projet' : 'projet',
545
		'projet' : 'projet',
548
		'nom_referentiel' : 'réferentiel',
546
		'nom_referentiel' : 'réferentiel',
549
		'date_obs' : 'date d´observation',
547
		'date_obs' : 'date d´observation',
550
		'nom_sel': 'nom scientifique',
548
		'nom_sel': 'nom scientifique',
551
		'nom_sel_nn' : 'nom scientifique n°',
549
		'nom_sel_nn' : 'nom scientifique n°',
552
		'nom_ret' : 'nom retenu',
550
		'nom_ret' : 'nom retenu',
553
		'nom_ret_nn' : 'nom retenu n°',
551
		'nom_ret_nn' : 'nom retenu n°',
554
		'famille' : 'famille',
552
		'famille' : 'famille',
555
		'tags_obs' : 'tags de l´observation',
553
		'tags_obs' : 'tags de l´observation',
556
		'lieudit' : 'lieu dit',
554
		'lieudit' : 'lieu dit',
557
		'station' : 'station',
555
		'station' : 'station',
558
		'milieu' : 'milieu',
556
		'milieu' : 'milieu',
559
		'latitude' : 'latitude',
557
		'latitude' : 'latitude',
560
		'longitude' : 'longitude',
558
		'longitude' : 'longitude',
561
		'altitude' : 'altitude',
559
		'altitude' : 'altitude',
562
		'localisation_precision': 'précision de la localisation',
560
		'localisation_precision': 'précision de la localisation',
563
		'code_insee' : 'code insee de la commune',
561
		'code_insee' : 'code insee de la commune',
564
		'dept' : 'département',
562
		'dept' : 'département',
565
		'pays' : 'pays',
563
		'pays' : 'pays',
566
		'est_ip_valide' : 'validée sur identiplante',
564
		'est_ip_valide' : 'validée sur identiplante',
567
		'score_ip' : 'score identiplante',
565
		'score_ip' : 'score identiplante',
568
		'url_ip' : 'url identiplante',
566
		'url_ip' : 'url identiplante',
569
		'abondance' : 'abondance',
567
		'abondance' : 'abondance',
570
		'phenologie' : 'phénologie',
568
		'phenologie' : 'phénologie',
571
		'spontaneite' : 'spontaneite',
569
		'spontaneite' : 'spontaneite',
572
		'type_donnees' : 'type de donnees',
570
		'type_donnees' : 'type de donnees',
573
		'biblio' : 'bibliographie',
571
		'biblio' : 'bibliographie',
574
		'source' : 'source',
572
		'source' : 'source',
575
		'herbier' : 'herbier',
573
		'herbier' : 'herbier',
576
		'observateur' : 'observateur',
574
		'observateur' : 'observateur',
577
		'observateur_structure' : 'structure'
575
		'observateur_structure' : 'structure'
578
	};
576
	};
579
 
577
 
580
	const $contenuPlusMeta  = $( '#contenu-meta-plus' );
578
	const $contenuPlusMeta  = $( '#contenu-meta-plus' );
581
	let degres = $contenuPlusMeta.is( ':visible' ) ? '180' : '0';
579
	let degres = $contenuPlusMeta.is( ':visible' ) ? '180' : '0';
582
 
580
 
583
	this.rotationFleche( degres );
581
	this.rotationFleche( degres );
584
	$contenuPlusMeta.empty();
582
	$contenuPlusMeta.empty();
585
 
583
 
586
	$.each( META_LABELS, function( cle, label ) {
584
	$.each( META_LABELS, function( cle, label ) {
587
		let idAttr = cle.replace( '_', '-' ),
585
		let idAttr = cle.replace( '_', '-' ),
588
			contenu = lthis.obs[cle];
586
			contenu = lthis.obs[cle];
589
 
587
 
590
		switch( cle ) {
588
		switch( cle ) {
591
			case 'nom_sel':
589
			case 'nom_sel':
592
				contenu = lthis.afficherLien( lthis.urlLienEflore, contenu );
590
				contenu = lthis.afficherLien( lthis.urlLienEflore, contenu );
593
				break;
591
				break;
594
 
592
 
595
			case 'nom_ret':
593
			case 'nom_ret':
596
				let urlEfloreNomRetenu = lthis.urlLienEflore.replace( lthis.obs['nom_sel_nn'], lthis.obs['nom_ret_nn'] );
594
				let urlEfloreNomRetenu = lthis.urlLienEflore.replace( lthis.obs['nom_sel_nn'], lthis.obs['nom_ret_nn'] );
597
 
595
 
598
				contenu = lthis.afficherLien( urlEfloreNomRetenu, contenu );
596
				contenu = lthis.afficherLien( urlEfloreNomRetenu, contenu );
599
				break;
597
				break;
600
 
598
 
601
			case 'url_ip':
599
			case 'url_ip':
602
				contenu = lthis.afficherLien( contenu, contenu );
600
				contenu = lthis.afficherLien( contenu, contenu );
603
				break;
601
				break;
604
 
602
 
605
			case 'est_ip_valide':
603
			case 'est_ip_valide':
606
			case 'herbier':
604
			case 'herbier':
607
				if( '0' === contenu ) {
605
				if( '0' === contenu ) {
608
					contenu = 'non';
606
					contenu = 'non';
609
				}
607
				}
610
				break;
608
				break;
611
 
609
 
612
			case 'date_obs':
610
			case 'date_obs':
613
				contenu = lthis.formaterDate( contenu );
611
				contenu = lthis.formaterDate( contenu );
614
				break;
612
				break;
615
 
613
 
616
			case 'tags_obs':
614
			case 'tags_obs':
617
				let tagsObsLength = lthis.tagsObs.length;
615
				let tagsObsLength = lthis.tagsObs.length;
618
				contenu = lthis.tagsObs.join( '<br>' );
616
				contenu = lthis.tagsObs.join( '<br>' );
619
				break;
617
				break;
620
 
618
 
621
			default:
619
			default:
622
				break;
620
				break;
623
		}
621
		}
624
 
622
 
625
		if ( lthis.valOk( contenu ) ) {
623
		if ( lthis.valOk( contenu ) ) {
626
			$contenuPlusMeta.append(
624
			$contenuPlusMeta.append(
627
				'<li id="' + idAttr + '-meta-plus" class="row">'+
625
				'<li id="' + idAttr + '-meta-plus" class="row">'+
628
					'<div class="col-5 label">' + label.charAt( 0 ).toUpperCase() + label.slice( 1 ) + '</div>'+
626
					'<div class="col-5 label">' + label.charAt( 0 ).toUpperCase() + label.slice( 1 ) + '</div>'+
629
					'<div class="col-7 contenu">' + contenu + '</div>'+
627
					'<div class="col-7 contenu">' + contenu + '</div>'+
630
				'</li>'
628
				'</li>'
631
			);
629
			);
632
		}
630
		}
633
	});
631
	});
634
 
632
 
635
	if( !$contenuPlusMeta.hasClass( 'actif' ) ) {
633
	if( !$contenuPlusMeta.hasClass( 'actif' ) ) {
636
		$contenuPlusMeta.hide();
634
		$contenuPlusMeta.hide();
637
	}
635
	}
638
 
636
 
639
	let estVisible = false;
637
	let estVisible = false;
640
 
638
 
641
	$( '#plus-meta' ).off( 'click' ).on( 'click', function( event ) {
639
	$( '#plus-meta' ).off( 'click' ).on( 'click', function( event ) {
642
		event.preventDefault();
640
		event.preventDefault();
643
		$contenuPlusMeta.toggle( 200, function() {
641
		$contenuPlusMeta.toggle( 200, function() {
644
			estVisible = $contenuPlusMeta.is( ':visible' );
642
			estVisible = $contenuPlusMeta.is( ':visible' );
645
			degres     = estVisible ? '180' : '0';
643
			degres     = estVisible ? '180' : '0';
646
			$( this ).toggleClass( 'actif', estVisible );
644
			$( this ).toggleClass( 'actif', estVisible );
647
			lthis.rotationFleche( degres );
645
			lthis.rotationFleche( degres );
648
		});
646
		});
649
	});
647
	});
650
};
648
};
651
 
649
 
652
WidgetPhotoPopup.prototype.rotationFleche = function( degres ) {
650
WidgetPhotoPopup.prototype.rotationFleche = function( degres ) {
653
	$( '#plus-meta i' ).css({
651
	$( '#plus-meta i' ).css({
654
		'-webkit-transform' : 'rotate('+ degres +'deg)',
652
		'-webkit-transform' : 'rotate('+ degres +'deg)',
655
		'-moz-transform' : 'rotate('+ degres +'deg)',
653
		'-moz-transform' : 'rotate('+ degres +'deg)',
656
		'-ms-transform' : 'rotate('+ degres +'deg)',
654
		'-ms-transform' : 'rotate('+ degres +'deg)',
657
		'transform' : 'rotate('+ degres +'deg)'
655
		'transform' : 'rotate('+ degres +'deg)'
658
	});
656
	});
659
};
657
};
660
 
658
 
661
WidgetPhotoPopup.prototype.fournirLienTelechargement = function() {
659
WidgetPhotoPopup.prototype.fournirLienTelechargement = function() {
662
	const lthis = this;
660
	const lthis = this;
663
 
661
 
664
	$( '#formats' ).on( 'change', function() {
662
	$( '#formats' ).on( 'change', function() {
665
		let format             = ( $( this ).val() || 'O' ),
663
		let format             = ( $( this ).val() || 'O' ),
666
			lienTelechargement = lthis.urlBaseTelechargement + lthis.idImage + '?methode=telecharger&format=' + format;
664
			lienTelechargement = lthis.urlBaseTelechargement + lthis.idImage + '?methode=telecharger&format=' + format;
667
 
665
 
668
		$( '#telecharger' ).attr( 'href', lienTelechargement );
666
		$( '#telecharger' ).attr( 'href', lienTelechargement );
669
	});
667
	});
670
 
668
 
671
	$( '#formats' ).trigger( 'change' );
669
	$( '#formats' ).trigger( 'change' );
672
};
670
};
673
 
671
 
674
 
672
 
675
WidgetPhotoPopup.prototype.afficherPopupLocalisation = function() {
673
WidgetPhotoPopup.prototype.afficherPopupLocalisation = function() {
676
	const lthis = this;
674
	const lthis = this;
677
 
675
 
678
	$( '#localisation a.bouton' ).on( 'click', function( event ){
676
	$( '#localisation a.bouton' ).on( 'click', function( event ){
679
		event.preventDefault();
677
		event.preventDefault();
680
 
678
 
681
		$( this ).after(
679
		$( this ).after(
682
			'<div id="localisation-map-container">'+
680
			'<div id="localisation-map-container">'+
683
				'<button id="map-close" type="button" class="bouton btn btn-sm btn-outline-secondary" aria-label="Close">'+
681
				'<button id="map-close" type="button" class="bouton btn btn-sm btn-outline-secondary" aria-label="Close">'+
684
					'<span aria-hidden="true">×</span>'+
682
					'<span aria-hidden="true">×</span>'+
685
				'</button>'+
683
				'</button>'+
686
				'<div id="localisation-map"></div>'+
684
				'<div id="localisation-map"></div>'+
687
			'</div>'
685
			'</div>'
688
		);
686
		);
689
 
687
 
690
		let lat = lthis.obs['latitude'],
688
		let lat = lthis.obs['latitude'],
691
			lng = lthis.obs['longitude'],
689
			lng = lthis.obs['longitude'],
692
			map = L.map( 'localisation-map', {
690
			map = L.map( 'localisation-map', {
693
				zoomControl: true,
691
				zoomControl: true,
694
				dragging: false,
692
				dragging: false,
695
				scrollWheelZoom: 'center'
693
				scrollWheelZoom: 'center'
696
			} ).setView( [lat, lng], 12 );
694
			} ).setView( [lat, lng], 12 );
697
 
695
 
698
		map.markers = [];
696
		map.markers = [];
699
 
697
 
700
		L.tileLayer(
698
		L.tileLayer(
701
			// 'https://osm.tela-botanica.org/tuiles/osmfr/{z}/{x}/{y}.png',
699
			// 'https://osm.tela-botanica.org/tuiles/osmfr/{z}/{x}/{y}.png',
702
			'https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png',
700
			'https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png',
703
			{
701
			{
704
				attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
702
				attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
705
				maxZoom: 18
703
				maxZoom: 18
706
			}
704
			}
707
		).addTo( map );
705
		).addTo( map );
708
 
706
 
709
		map.addLayer( new L.FeatureGroup() );
707
		map.addLayer( new L.FeatureGroup() );
710
 
708
 
711
		let marker = new L.Marker(
709
		let marker = new L.Marker(
712
			{
710
			{
713
				'lat': lat,
711
				'lat': lat,
714
				'lng': lng
712
				'lng': lng
715
			},
713
			},
716
			{
714
			{
717
				draggable: false,
715
				draggable: false,
718
			}
716
			}
719
		);
717
		);
720
 
718
 
721
 
719
 
722
		map.addLayer( marker );
720
		map.addLayer( marker );
723
		map.markers.push( marker );
721
		map.markers.push( marker );
724
 
722
 
725
		$( '#map-close' ).on( 'click', function( event ){
723
		$( '#map-close' ).on( 'click', function( event ){
726
			$( '#localisation-map-container' ).remove();
724
			$( '#localisation-map-container' ).remove();
727
		});
725
		});
728
	});
726
	});
729
 
727
 
730
	$( '#fenetre-modal' ).on( 'click', function( event ) {
728
	$( '#fenetre-modal' ).on( 'click', function( event ) {
731
		if(
729
		if(
732
			!$( event.target ).closest( '#localisation-map-container' ).length
730
			!$( event.target ).closest( '#localisation-map-container' ).length
733
			&& !$( event.target ).closest( '#obs-localisation' ).length
731
			&& !$( event.target ).closest( '#obs-localisation' ).length
734
		) {
732
		) {
735
			$( '#localisation-map-container' ).remove();
733
			$( '#localisation-map-container' ).remove();
736
		}
734
		}
737
	});
735
	});
738
};
736
};
739
 
737
 
740
 
738
 
741
WidgetPhotoPopup.prototype.regenererMiniature = function() {
739
WidgetPhotoPopup.prototype.regenererMiniature = function() {
742
	const lthis = this;
740
	const lthis = this;
743
	$( '#regenerer-miniature' ).off( 'click' ).on( 'click', function( event ) {
741
	$( '#regenerer-miniature' ).off( 'click' ).on( 'click', function( event ) {
744
		event.preventDefault();
742
		event.preventDefault();
745
 
743
 
746
		let url = lthis.urlServiceRegenererMiniature + lthis.idImage;
744
		let url = lthis.urlServiceRegenererMiniature + lthis.idImage;
747
		$.get( url, function( data ) {
745
		$.get( url, function( data ) {
748
				console.log( data );
746
				console.log( data );
749
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
747
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
750
			}
748
			}
751
		).fail( function() {
749
		).fail( function() {
752
			console.log( 'La régénération d´image ne s´est pas faite' );
750
			console.log( 'La régénération d´image ne s´est pas faite' );
753
		});
751
		});
754
	});
752
	});
755
};
753
};
756
 
754
 
757
WidgetPhotoPopup.prototype.formaterDate = function( sqlDate ) {
755
WidgetPhotoPopup.prototype.formaterDate = function( sqlDate ) {
758
	dateFormatee = sqlDate
756
	dateFormatee = sqlDate
759
		.substring( 0, 10 )
757
		.substring( 0, 10 )
760
		.split( '-' )
758
		.split( '-' )
761
		.reverse()
759
		.reverse()
762
		.join('/');
760
		.join('/');
763
 
761
 
764
	return dateFormatee;
762
	return dateFormatee;
765
};
763
};
766
 
764
 
767
WidgetPhotoPopup.prototype.afficherLien = function( url, nom ) {
765
WidgetPhotoPopup.prototype.afficherLien = function( url, nom ) {
768
	if( !/https?:\/\//.test( url ) ) {
766
	if( !/https?:\/\//.test( url ) ) {
769
		url = 'https://' + url;
767
		url = 'https://' + url;
770
	}
768
	}
771
	return '<a href="' + url + '" target="_blank">' + nom + '</a> ';
769
	return '<a href="' + url + '" target="_blank">' + nom + '</a> ';
772
};
770
};
773
 
771
 
774
WidgetPhotoPopup.prototype.fournirLienIdentiplante = function() {
772
WidgetPhotoPopup.prototype.fournirLienIdentiplante = function() {
775
	const lthis = this;
773
	const lthis = this;
776
	$( '.signaler-erreur-obs' ).each( function() {
774
	$( '.signaler-erreur-obs' ).each( function() {
777
		$( this ).attr( 'href', 'https://' + lthis.urlIP );
775
		$( this ).attr( 'href', 'https://' + lthis.urlIP );
778
	});
776
	});
779
};
777
};
780
 
778
 
781
WidgetPhotoPopup.prototype.initEvtsProtocole = function() {
779
WidgetPhotoPopup.prototype.initEvtsProtocole = function() {
782
	const lthis = this;
780
	const lthis = this;
783
	$('#bloc-notes-protocole').addClass('hidden');
781
	$('#bloc-notes-protocole').addClass('hidden');
784
	lthis.votes = null
782
	lthis.votes = null
785
	//On transforme la promesse en array
783
	//On transforme la promesse en array
786
	const PROTOCOLES_ARRAY = Object.values(lthis.protocoles);
784
	const PROTOCOLES_ARRAY = Object.values(lthis.protocoles);
787
 
785
 
788
	const $select = $('#protocole');
786
	const $select = $('#protocole');
789
	$select.empty(); // Clear existing options
787
	$select.empty(); // Clear existing options
790
 
788
 
791
	// Add the default hidden option
789
	// Add the default hidden option
792
	$select.append('<option value="" selected hidden>Choix du protocole</option>');
790
	$select.append('<option value="" selected hidden>Choix du protocole</option>');
793
 
791
 
794
	PROTOCOLES_ARRAY.forEach(protocoleData => {
792
	PROTOCOLES_ARRAY.forEach(protocoleData => {
795
		$select.append(`<option id="protocole_${protocoleData['protocole.id']}" value="protocole_${protocoleData['protocole.id']}">${protocoleData['protocole.intitule']}</option>`);
793
		$select.append(`<option id="protocole_${protocoleData['protocole.id']}" value="protocole_${protocoleData['protocole.id']}">${protocoleData['protocole.intitule']}</option>`);
796
	})
794
	})
797
 
795
 
798
	$( '#protocole').on( 'change', function( event ){
796
	$( '#protocole').on( 'change', function( event ){
799
		event.preventDefault();
797
		event.preventDefault();
800
		lthis.votes = null
798
		lthis.votes = null
801
 
799
 
802
		var id = $(this).children(":selected").attr("id");
800
		var id = $(this).children(":selected").attr("id");
803
		var protocole = id.split("_")[1];
801
		var protocole = id.split("_")[1];
804
 
802
 
805
		$('#bloc-notes-protocole').removeClass('hidden');
803
		$('#bloc-notes-protocole').removeClass('hidden');
806
 
804
 
807
		// Find the object corresponding to the selected id (protocole.id)
805
		// Find the object corresponding to the selected id (protocole.id)
808
		var selectedProtocoleData = PROTOCOLES_ARRAY.find(protocoleData => protocoleData['protocole.id'] === protocole);
806
		var selectedProtocoleData = PROTOCOLES_ARRAY.find(protocoleData => protocoleData['protocole.id'] === protocole);
809
 
807
 
810
		lthis.protocole = selectedProtocoleData['protocole.id'];
808
		lthis.protocole = selectedProtocoleData['protocole.id'];
811
		const message = selectedProtocoleData['protocole.descriptif'];
809
		const message = selectedProtocoleData['protocole.descriptif'];
812
 
810
 
813
		$('#message-protocole').html('<p>' + message + '</p>');
811
		$('#message-protocole').html('<p>' + message + '</p>');
814
 
812
 
815
		// On envoie le protocole sélectionné à la partie "vote"
813
		// On envoie le protocole sélectionné à la partie "vote"
816
		// On récupère tous les votes de l'image depuis pictoflora
814
		// On récupère tous les votes de l'image depuis pictoflora
817
		lthis.votes = lthis.getVotes(lthis.protocole)
815
		lthis.votes = lthis.getVotes(lthis.protocole)
818
 
816
 
819
		// Si l'utilisateur est connect, on vérifie s'il a déjà voté pour cette image et on affiche les étoiles
817
		// Si l'utilisateur est connect, on vérifie s'il a déjà voté pour cette image et on affiche les étoiles
820
		// correspondantes
818
		// correspondantes
821
		if(lthis.userId){
819
		if(lthis.userId){
822
			lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
820
			lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
823
		} else {
821
		} else {
824
			lthis.voteId = null;
822
			lthis.voteId = null;
825
			lthis.removeVoteStars()
823
			lthis.removeVoteStars()
826
		}
824
		}
827
 
825
 
828
		// Remove any previous click event listeners on rating stars
826
		// Remove any previous click event listeners on rating stars
829
		for (let i=1; i<=5; i++){
827
		for (let i=1; i<=5; i++){
830
			$("#rating-star-"+i).off("click");
828
			$("#rating-star-"+i).off("click");
831
		}
829
		}
832
 
830
 
833
		// Si l'utilisateur vote, on affiche les étoiles correspondantes et on l'envoie vers pictoflora
831
		// Si l'utilisateur vote, on affiche les étoiles correspondantes et on l'envoie vers pictoflora
834
		lthis.traiterVote();
832
		lthis.traiterVote();
835
	});
833
	});
836
}
834
}
837
 
835
 
838
WidgetPhotoPopup.prototype.traiterVote = function () {
836
WidgetPhotoPopup.prototype.traiterVote = function () {
839
	const lthis = this;
837
	const lthis = this;
840
	let starSelected = 0
838
	let starSelected = 0
841
	let mode = '';
839
	let mode = '';
842
 
840
 
843
	$("#note").attr("value", -1);
841
	$("#note").attr("value", -1);
844
 
842
 
845
	// Traitement du bouton suppression du vote
843
	// Traitement du bouton suppression du vote
846
	$("#note-remove").click(function (){
844
	$("#note-remove").click(function (){
847
		lthis.removeVoteStars();
845
		lthis.removeVoteStars();
848
		mode = 'DELETE';
846
		mode = 'DELETE';
849
		// On n'envoie le vote que si l'utilisateur est connecté
847
		// On n'envoie le vote que si l'utilisateur est connecté
850
		if (lthis.userId) {
848
		if (lthis.userId) {
851
			lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode, lthis.voteId);
849
			lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode, lthis.voteId);
852
		}
850
		}
853
	})
851
	})
854
 
852
 
855
	// Si l'utilisateur a déjà voté pour cette image on affiche son vote et on passe en mode modification
853
	// Si l'utilisateur a déjà voté pour cette image on affiche son vote et on passe en mode modification
856
	let userAVoter = lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
854
	let userAVoter = lthis.checkUserVote(lthis.userId, lthis.protocole, lthis.votes);
857
	userAVoter ? mode = 'POST' : mode = 'PUT';
855
	userAVoter ? mode = 'POST' : mode = 'PUT';
858
 
856
 
859
	// Affichage du nombre d'étoiles sélectionnées et envoi du vote
857
	// Affichage du nombre d'étoiles sélectionnées et envoi du vote
860
	for (let i=1; i<=5; i++){
858
	for (let i=1; i<=5; i++){
861
		$("#rating-star-"+i).click(function () {
859
		$("#rating-star-"+i).click(function () {
862
			starSelected = i
860
			starSelected = i
863
			lthis.displayVote(starSelected);
861
			lthis.displayVote(starSelected);
864
			$("#note").attr("value", starSelected);
862
			$("#note").attr("value", starSelected);
865
			// On n'envoie le vote que si l'utilisateur est connecté
863
			// On n'envoie le vote que si l'utilisateur est connecté
866
			if (lthis.userId){
864
			if (lthis.userId){
867
				lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode);
865
				lthis.sendVote(lthis.userId, lthis.protocole, starSelected, mode);
868
			}
866
			}
869
		});
867
		});
870
	}
868
	}
871
};
869
};
872
 
870
 
873
// Envoi du vote vers la fonction sendVote() du fichier php
871
// Envoi du vote vers la fonction sendVote() du fichier php
874
WidgetPhotoPopup.prototype.sendVote = function (userId, protocole, note, mode, voteId){
872
WidgetPhotoPopup.prototype.sendVote = function (userId, protocole, note, mode, voteId){
875
	const lthis = this;
873
	const lthis = this;
876
 
874
 
877
	var xhttp = new XMLHttpRequest();
875
	var xhttp = new XMLHttpRequest();
878
	xhttp.onreadystatechange = function() {
876
	xhttp.onreadystatechange = function() {
879
		if (this.readyState == 4 && this.status == 200) {
877
		if (this.readyState == 4 && this.status == 200) {
-
 
878
			let votesUrl = lthis.urlServiceDel + 'images/' + lthis.idImage + '/votes';
-
 
879
			// Récupération des données et maj de l'affichage
-
 
880
			lthis.envoyerVersService('GET', votesUrl, null, null, function (erreur, data) {
-
 
881
				if (erreur) {
-
 
882
					console.error("Erreur lors de la requête :", erreur);
-
 
883
				} else {
-
 
884
					lthis.item["votes"] = Object.values(data['resultats']);
-
 
885
					lthis.getVotes(protocole)
880
 
886
				}
-
 
887
			});
881
			console.log('vote envoyé')
888
			console.log('vote envoyé')
882
		}
889
		}
883
	};
890
	};
884
 
891
 
885
	var url = "../widget:cel:photo/";
892
	var url = "../widget:cel:photo/";
886
 
893
 
887
	// Convertir les données en une chaîne JSON pour les envoyer dans le corps de la requête
894
	// Convertir les données en une chaîne JSON pour les envoyer dans le corps de la requête
888
	var data = {
895
	var data = {
889
		idImage: this.idImage,
896
		idImage: this.idImage,
890
		mode: mode,
897
		mode: mode,
891
		user: userId,
898
		user: userId,
892
		protocole: protocole,
899
		protocole: protocole,
893
		vote: note,
900
		vote: note,
894
		voteId: voteId
901
		voteId: voteId
895
	}
902
	}
896
	var jsonData = JSON.stringify(data);
903
	var jsonData = JSON.stringify(data);
897
 
904
 
898
	xhttp.open("POST", url+"?action=send_pf_vote", true);
905
	xhttp.open("POST", url+"?action=send_pf_vote", true);
899
	xhttp.setRequestHeader("Content-Type", "application/json");
906
	xhttp.setRequestHeader("Content-Type", "application/json");
900
	xhttp.send(jsonData);
907
	xhttp.send(jsonData);
901
}
908
}
902
 
909
 
903
WidgetPhotoPopup.prototype.getVotes = function (protocoleId){
910
WidgetPhotoPopup.prototype.getVotes = function (protocoleId){
904
	let votes = Object.values(this.item["votes"]);
911
	let votes = Object.values(this.item["votes"]);
905
	let noteMoyenne = 0;
912
	let noteMoyenne = 0;
906
	let nombreVotes= 0;
913
	let nombreVotes= 0;
907
	let noteTotal = 0;
914
	let noteTotal = 0;
908
	let itemVotes = [];
915
	let itemVotes = [];
909
 
916
 
910
	votes.forEach(vote => {
917
	votes.forEach(vote => {
911
		if (vote["protocole.id"] == protocoleId){
918
		if (vote["protocole.id"] == protocoleId){
912
			nombreVotes++
919
			nombreVotes++
913
			noteTotal += parseInt(vote["vote"]);
920
			noteTotal += parseInt(vote["vote"]);
914
			noteMoyenne = (noteTotal / nombreVotes).toFixed(1)
921
			noteMoyenne = (noteTotal / nombreVotes).toFixed(1)
915
			itemVotes.push(vote);
922
			itemVotes.push(vote);
916
		}
923
		}
917
	})
924
	})
918
 
925
 
919
	let elementNoteMoyenne = $("#note-moyenne .contenu");
926
	let elementNoteMoyenne = $("#note-moyenne .contenu");
920
	elementNoteMoyenne.text(noteMoyenne);
927
	elementNoteMoyenne.text(noteMoyenne);
921
 
928
 
922
	let elementNoteCount = $("#note-count .contenu");
929
	let elementNoteCount = $("#note-count .contenu");
923
	elementNoteCount.text(nombreVotes);
930
	elementNoteCount.text(nombreVotes);
924
 
931
 
925
	return itemVotes;
932
	return itemVotes;
926
}
933
}
927
 
934
 
928
WidgetPhotoPopup.prototype.displayVote = function (note){
935
WidgetPhotoPopup.prototype.displayVote = function (note){
929
	lthis.removeVoteStars();
936
	lthis.removeVoteStars();
930
 
937
 
931
	for (let i=1; i<=5; i++){
938
	for (let i=1; i<=5; i++){
932
		for (let j=1; j<=note; j++){
939
		for (let j=1; j<=note; j++){
933
			$("#rating-star-"+j).removeClass('far').addClass('fa').css("color", "#c3d45d");
940
			$("#rating-star-"+j).removeClass('far').addClass('fa').css("color", "#c3d45d");
934
		}
941
		}
935
	}
942
	}
936
}
943
}
937
 
944
 
938
WidgetPhotoPopup.prototype.removeVoteStars = function (){
945
WidgetPhotoPopup.prototype.removeVoteStars = function (){
939
	$(".notation-star").removeClass('fa').addClass('far').css("color", "grey");
946
	$(".notation-star").removeClass('fa').addClass('far').css("color", "grey");
940
	$("#note").attr("value", -1);
947
	$("#note").attr("value", -1);
941
}
948
}
942
 
949
 
943
WidgetPhotoPopup.prototype.checkUserVote = function (userId, protocoleId, votes){
950
WidgetPhotoPopup.prototype.checkUserVote = function (userId, protocoleId, votes){
944
	let userVote = null;
951
	let userVote = null;
945
 
952
 
946
	votes.forEach(vote => {
953
	votes.forEach(vote => {
947
		if (vote["protocole.id"] == protocoleId && vote["auteur.id"] == userId){
954
		if (vote["protocole.id"] == protocoleId && vote["auteur.id"] == userId){
948
			userVote = vote;
955
			userVote = vote;
949
		}
956
		}
950
	})
957
	})
951
 
958
 
952
	if (userVote){
959
	if (userVote){
953
		this.displayVote(userVote['vote']);
960
		this.displayVote(userVote['vote']);
954
		// this.traiterVote()
961
		// this.traiterVote()
955
		this.voteId = userVote['vote.id'];
962
		this.voteId = userVote['vote.id'];
956
 
963
 
957
		return true
964
		return true
958
	} else {
965
	} else {
959
		this.voteId = null;
966
		this.voteId = null;
960
		this.removeVoteStars()
967
		this.removeVoteStars()
961
	}
968
	}
962
}
969
}
963
 
970
 
964
WidgetPhotoPopup.prototype.pivoterImage = function() {
971
WidgetPhotoPopup.prototype.pivoterImage = function() {
965
	lthis = this;
972
	lthis = this;
966
 
973
 
967
	let newCel = lthis.urlServiceNewCel + "photo_rotations?photoId=" + lthis.idImage + "&degrees=";
974
	let newCel = lthis.urlServiceNewCel + "photo_rotations?photoId=" + lthis.idImage + "&degrees=";
968
	let url = '';
975
	let url = '';
969
 
976
 
970
	$( '#pivoter-droite' ).off( 'click' ).on( 'click', function( event ) {
977
	$( '#pivoter-droite' ).off( 'click' ).on( 'click', function( event ) {
971
		event.preventDefault();
978
		event.preventDefault();
972
 
979
 
973
		url = "";
980
		url = "";
974
		lthis.pivoter('droite');
981
		lthis.pivoter('droite');
975
		url = newCel + "-90";
982
		url = newCel + "-90";
976
		// lthis.envoyerVersService('GET', url, lthis.token )
983
		// lthis.envoyerVersService('GET', url, lthis.token )
977
 
984
 
978
		lthis.envoyerVersService('GET', url, lthis.token, null, function (erreur, cb) {
985
		lthis.envoyerVersService('GET', url, lthis.token, null, function (erreur, cb) {
979
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
986
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
980
		});
987
		});
981
 
988
 
982
		// lthis.forcerMajImage(lthis.urlThisImage);
989
		// lthis.forcerMajImage(lthis.urlThisImage);
983
	});
990
	});
984
 
991
 
985
	$( '#pivoter-gauche' ).off( 'click' ).on( 'click', function( event ) {
992
	$( '#pivoter-gauche' ).off( 'click' ).on( 'click', function( event ) {
986
		event.preventDefault();
993
		event.preventDefault();
987
 
994
 
988
		url = "";
995
		url = "";
989
		lthis.pivoter('gauche');
996
		lthis.pivoter('gauche');
990
		url = newCel + "90";
997
		url = newCel + "90";
991
		lthis.envoyerVersService('GET', url, lthis.token, null, function (erreur, cb) {
998
		lthis.envoyerVersService('GET', url, lthis.token, null, function (erreur, cb) {
992
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
999
			lthis.forcerMajImage(lthis.urlThisImage, lthis.urlTpl);
993
		});
1000
		});
994
	});
1001
	});
995
};
1002
};
996
 
1003
 
997
WidgetPhotoPopup.prototype.pivoter = function(direction) {
1004
WidgetPhotoPopup.prototype.pivoter = function(direction) {
998
	let imageSelected = $('img[src="' + lthis.urlThisImage + '"]').attr('id');
1005
	let imageSelected = $('img[src="' + lthis.urlThisImage + '"]').attr('id');
999
	let angle = $('#' + imageSelected).data('angle');
1006
	let angle = $('#' + imageSelected).data('angle');
1000
 
1007
 
1001
	if (angle == 360 || angle == (-360) || angle == undefined){
1008
	if (angle == 360 || angle == (-360) || angle == undefined){
1002
		angle = 0
1009
		angle = 0
1003
	}
1010
	}
1004
	if (direction == 'droite'){
1011
	if (direction == 'droite'){
1005
		angle += 90;
1012
		angle += 90;
1006
	} else {
1013
	} else {
1007
		angle -= 90;
1014
		angle -= 90;
1008
	}
1015
	}
1009
 
1016
 
1010
	$('#' + imageSelected).css("transform", "rotate(" + angle + "deg) ");
1017
	$('#' + imageSelected).css("transform", "rotate(" + angle + "deg) ");
1011
	$('#' + imageSelected).data('angle', angle);
1018
	$('#' + imageSelected).data('angle', angle);
1012
}
1019
}
1013
 
1020
 
1014
WidgetPhotoPopup.prototype.forcerMajImage = function (urlImage, urlTpl){
1021
WidgetPhotoPopup.prototype.forcerMajImage = function (urlImage, urlTpl){
1015
	var indexPourcentage = urlTpl.indexOf('%');
1022
	var indexPourcentage = urlTpl.indexOf('%');
1016
	urlTpl = urlTpl.substring(0, indexPourcentage);
1023
	urlTpl = urlTpl.substring(0, indexPourcentage);
1017
 
1024
 
1018
	// Sélectionne l'élément img avec l'attribut src égal à this.urlImage
1025
	// Sélectionne l'élément img avec l'attribut src égal à this.urlImage
1019
	var $image = $('img[src^="' +  urlTpl + '"]');
1026
	var $image = $('img[src^="' +  urlTpl + '"]');
1020
 
1027
 
1021
	// Ajoute un paramètre unique à l'URL pour éviter le cache
1028
	// Ajoute un paramètre unique à l'URL pour éviter le cache
1022
	var newSrc = urlImage + '?timestamp=' + new Date().getTime();
1029
	var newSrc = urlImage + '?timestamp=' + new Date().getTime();
1023
 
1030
 
1024
	// Met à jour l'attribut 'src' de l'image avec la nouvelle URL
1031
	// Met à jour l'attribut 'src' de l'image avec la nouvelle URL
1025
	$image.attr('src', newSrc);
1032
	$image.attr('src', newSrc);
1026
}
1033
}