'use strict';

/**
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */

/**
 * Trigger a callback when 'this' image is loaded:
 * @param {Function} callback
 * @source https://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached/3877079
 */
(function($)
{
    $.fn.imgLoad = function(callback)
	{
        return this.each(function()
		{
            if (callback)
			{
                if (this.complete || /*for IE 10-*/ $(this).height() > 0)
				{
                    callback.apply(this);
                }
                else
				{
                    $(this).on('load', function()
					{
                        callback.apply(this);
                    });
                }
            }
        });
    };
})(jQuery);

// Identifiant des fichiers sélectionnés en mode "grille".
var selected_group_id;

// Réinitilisation de la date de publication.
function change_reset_item_pubdt(val, id)
{
	if (val == '0')
	{
		$(id).prop('disabled', true).parents('p').addClass('disabled');
	}
	else
	{
		$(id).prop('disabled', false).parents('p').removeClass('disabled');
	}
}

// Échape les caractères spéciaux pour la recherche.
function search_escape(str)
{
	str = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
	str = str.replace(/\s+/g, '\\s+');
	str = str.replace(/[aäâàáåã]/gi, "[aäâàáåã]");
	str = str.replace(/[cç]/gi, "[cç]");
	str = str.replace(/[eéèêë]/gi, "[eéèêë]");
	str = str.replace(/[iïîìí]/gi, "[iïîìí]");
	str = str.replace(/[nñ]/gi, "[nñ]");
	str = str.replace(/[oöôóòõ]/gi, "[oöôóòõ]");
	str = str.replace(/[uüûùú]/gi, "[uüûùú]");
	str = str.replace(/[yÿý]/gi, "[yÿý]");
	return str;
}

// Décode les entités HTML.
function htmldecode(str)
{
	return new DOMParser().parseFromString(str, 'text/html').documentElement.textContent;
}

// Messages de rapport.
var timeout_report;
function report()
{
	if ($('#report').length)
	{
		timeout_report = setTimeout(function()
		{
			$('#report:not(#scan_report,.error)').hide();
		}, 3400);
	}
	if ($('#report').length)
	{
		var direction = $('#report').css('bottom') == '0px' ? 'down' : 'left';
	}
	$('#report:not(#scan_report) .report_msg').click(function()
	{
		$(this).hide('slide', { direction: direction }, 200);
	});
}

// Montre ou cache un élément selon son état.
function showhide(sel)
{
	if ($(sel).is(':hidden'))
	{
		$(sel).show();
	}
	else
	{
		$(sel).hide();
	}
}

// Objets : (dé)coche une case à cocher.
function select(e, type)
{
	if (e.prop('disabled'))
	{
		return;
	}
	var select = function(e)
	{
		if (!e.prop('checked'))
		{
			e.prop('checked', true);
			e.parents('.selectable_class').addClass('selected').removeClass('unselected');
		}
	};
	var unselect = function(e)
	{
		if (e.prop('checked'))
		{
			e.prop('checked', false);
			e.parents('.selectable_class').addClass('unselected').removeClass('selected');
		}
	};
	switch (type)
	{
		case 'all' :
			select(e);
			break;

		case 'invert' :
			if (e.prop('checked'))
			{
				unselect(e);
			}
			else
			{
				select(e);
			}
			break;

		case 'none' :
			unselect(e);
			break;
	}
	$('#select_num').text($('.selectable_class.selected').length);
}

// Selectionne tous les objets.
function select_all()
{
	$('.selectable').each(function()
	{
		select($(this), 'all');
	});
	return false;
}

// Déselectionne tous les objets.
function select_none()
{
	$('.selectable').each(function()
	{
		select($(this), 'none');
	});
	return false;
}

// Inverse la sélection des objets.
function select_invert()
{
	$('.selectable').each(function()
	{
		select($(this), 'invert');
	});
	return false;
}

// Montre les details de tous les objets.
function show_all()
{
	if ($('#show_items').length)
	{
		var sel = $('#show_items :selected').val();
		$('.show_parts a' + (sel == 'obj_fold' ? '' : '[data-id^="' + sel + '"]'))
			.addClass('show');
		$('.' + sel).addClass('show');
	}
	else
	{
		$('.show_parts a,.obj_fold').addClass('show');
		$('.obj_mini_edit').show();
	}
	return false;
}

// Cache les details de tous les objets.
function hide_all()
{
	if ($('#show_items').length)
	{
		var sel = $('#show_items :selected').val();
		$('.show_parts a' + (sel == 'obj_fold' ? '' : '[data-id^="' + sel + '"]'))
			.removeClass('show');
		$('.' + sel).removeClass('show');
	}
	else
	{
		$('.show_parts a,.obj_fold').removeClass('show');
		$('.obj_mini_edit').hide();
	}
	return false;
}

// Informations complémentaires de boite.
function box_info(box_id)
{
	$(box_id + ' li:not([disabled])').mouseenter(function()
	{
		var i = cat_list_infos($(this));
		var path = [];
		if (i.id > 1)
		{
			i.parents.split('.').forEach(function(id)
			{
				path.push($(box_id + ' li[id*="{' + id + '}"] b').text());
			});
		}
		path.push($(this).find('b').text());
		$(box_id + ' .box_info').text(path.join(' / '));
	});
	$(box_id + ' li:not([disabled])').mouseleave(function()
	{
		$(box_id + ' .box_info').html('<span>&nbsp;</span>');
	});
	$(box_id + ' .box_info').show().html('<span>&nbsp;</span>');
}

// Création d'un viewer pour l'affichage d'une image ou d'une vidéo.
function viewer(source)
{
	if (!source)
	{
		return;
	}

	page_scrollbar_hide();

	var html = '<div id="viewer">';
	var ext = source.replace(/^.+\.([^/]+)$/, '$1', source).toLowerCase();
	if (ext == 'mp4' || ext == 'webm')
	{
		html += '<video autoplay controls>';
		html += '<source src="' + source + '&' + Math.random() + '" type="video/' + ext + '">';
		html += '</video>';
	}
	else
	{
		source += source.search(/\?/, source) == -1 ? '?' : '&';
		html += '<img src="' + source + Math.random() + '">';
	}
	html += '</div>';
	var resize = function()
	{
		var margin = parseInt($('#viewer').css('paddingLeft')) * 2;
		$('#viewer').css({
			'width': ($(window).width() - margin) + 'px',
			'height': ($(window).height() - margin) + 'px'
		});
	};
	$('main').append(html);
	$('#viewer video').prop('volume', 0.5);
	resize();
	$(window).resize(function()
	{
		if ($('#viewer').is('div'))
		{
			resize();
		}
	});
	$('body').on('click', '#viewer', function()
	{
		$(this).remove();
		page_scrollbar_show();
	});
	$(window).keyup(function(e)
	{
		if ($('#viewer').is('div') && e.keyCode == 27)
		{
			$('#viewer').click();
		}
	});
}



/**
 * Gestion des listes de catégories.
 *
 */
function cat_list_infos(e)
{
	var i = e.attr('id').split(/[\{\}]/);
	return { level: i[0].replace(/\D+/, ''), id: i[1], parents: i[2] };
}
function cat_list_current(list_id)
{
	var e = $(list_id + ' li[id*="c"]');
	if (!e.length)
	{
		return;
	}
	var cat_infos = cat_list_infos(e);
	if (cat_infos.id > 1 && cat_infos.parents)
	{
		var id, parents = cat_infos.parents + '.' + cat_infos.id;
		while (parents.match(/\./))
		{
			parents = parents.replace(/\.\d+$/, '');
			id = parents.replace(/^.*\.(\d+)$/, '$1');
			$(list_id + ' li[id$="}' + parents + '"]')
				.each(function()
				{
					$(this).attr('id', 'v' + $(this).attr('id').replace('v', ''));
				})
				.css('display', 'flex');
			if (id == 1 && cat_infos.level > 1 || id != 1)
			{
				$(list_id + ' li[id*="{' + id + '}"] > i').text('-');
			}
		}
	}
}
function cat_list_subcats(e)
{
	var i = cat_list_infos(e.parents('li'));
	var parents = i.parents + '.' + i.id;
	if (i.id == '1')
	{
		if (e.text() == '-')
		{
			e.parents('.cat_list').find('li:not([id*=":0{"]):not([id*=":1{"])')
				.each(function()
				{
					$(this).attr('id', $(this).attr('id').replace('v', ''));
				})
				.css('display', 'none');
			e.parents('.cat_list').find('li > i').text('+');
			e.text('+');
		}
		else
		{
			e.parents('.cat_list').find('li:not([id*=":0{"]):not([id*=":1{"])')
				.each(function()
				{
					$(this).attr('id', 'v' + $(this).attr('id').replace('v', ''));
				})
				.css('display', 'flex');
			e.parents('.cat_list').find('li > i').text('-');
			e.text('-');
		}
	}
	else
	{
		if (e.text() == '-')
		{
			e.parents('.cat_list').find('li[id$="}' + parents + '"], li[id*="}' + parents + '."]')
				.each(function()
				{
					$(this).attr('id', $(this).attr('id').replace('v', ''));
				})
				.css('display', 'none');
			e.parents('.cat_list').find('li[id*="}' + parents + '"] > i').text('+');
			e.text('+');
			if (e.parents('.cat_list').find('li:not([id*="{1}"]) > i:contains("-")').length < 1)
			{
				e.parents('.cat_list').find('li[id*="{1}"] > i').text('+');
			}
		}
		else
		{
			e.parents('.cat_list').find('li[id$="}' + parents + '"]')
				.each(function()
				{
					$(this).attr('id', 'v' + $(this).attr('id').replace('v', ''));
				})
				.css('display', 'flex');
			e.text('-');
			e.parents('.cat_list').find('li[id*="{1}"] > i').text('-');
		}
	}
	e.parents('.cat_list').find('input[type="text"]').focus();
}
function get_select_categories(type)
{
	var html = '';
	$(`#browse li${type == 'album' ? '' : '[id*="t"]'}`).each(function()
	{
		var i = cat_list_infos($(this));
		var is_sub = type == 'album'
			? $(this).find('> i')
			: $(`#browse li[id$=".${i.id}"][id*="t"]`);
		var disabled = type == 'album' && $(this).attr('id').match('t') ? ' disabled' : '';
		var id = 'o' + (is_sub.length ? 's' : '') + (i.level > 1 ? '' : 'v')
			+ $(this).attr('id').replace(/[cv]/g, '');
		var title = $(this).find('b').html();
		var indent = ' '.repeat(parseInt(id.replace(/^.+:(\d+)\{.+$/, '$1')) * 4);
		html += `<option${disabled} id="${id}" value="${i.id}">${indent}${title}</option>`;
	});
	return type != 'album' && html.match('<option id="os')
		? html.replace(/(<option id=")([^"]+" value="1")/, '$1s$2')
		: html;
}



/**
 * Gestion de la scrollbar de la page.
 *
 */
var page_overflow;
function page_scrollbar_show()
{
	$('body').css(
	{
		'overflow': page_overflow.body,
		'padding': 0
	});

	if ($('#obj_grid').length && $('#obj_grid').hasClass('extend'))
	{
		$('#scrollbar_blank').remove();
		$('#obj_grid').css('right', 0);
	}
}
function page_scrollbar_hide()
{
	page_overflow =
	{
		body: $('body').css('overflow')
	};
	var width_before = $(window).width();
	$('body').css('overflow', 'hidden');
	var diff = ($(window).width() - width_before);
	$('body').css('padding-right', diff + 'px');

	if ($('#obj_grid').length && $('#obj_grid').hasClass('extend'))
	{
		$('main').append('<div id="scrollbar_blank"></div>');
		$('#scrollbar_blank').css({
			'position': 'absolute',
			'top': 0,
			'right': 0,
			'height': '200px',
			'width': diff + 'px',
			'background': 'white'
		});
		$('#obj_grid').css('right', diff + 'px');
	}
}



/**
 * Géolocalisation.
 *
 */
function Worldmap(prefix, callback)
{
	this.esri;
	this.map;
	this.marker;
	this.markerActive = false;
	this.markerZoom = 12;
	this.osm;

	var self = this;


	this.addMarker = function(latlng)
	{
		self.markerActive = true;
		self.marker = L.marker(latlng, {draggable: true, autoPan: true}).addTo(self.map);

		self.setLatlongFields();
		self.marker.on('drag', function()
		{
			self.setLatlongFields();
			self.resetCatList();
		});

		$('#' + prefix + '_marker')
			.attr('class', 'icon icon_marker_delete')
			.find('a').text(text_marker_delete);
	};

	this.deleteMarker = function()
	{
		if (!self.markerActive)
		{
			return;
		}

		self.markerActive = false;
		self.marker.remove();

		$('#' + prefix + '_latitude').val('');
		$('#' + prefix + '_longitude').val('');

		$('#' + prefix + '_marker')
			.attr('class', 'icon icon_marker_add')
			.find('a').text(text_marker_add);
	};

	// Retourne une coordonnée correctement formatée.
	this.getCoord = function(coord)
	{
		var regexp = /^(\d+(?:\.\d+)?)E\-(\d+)$/i;
		var match = regexp.exec(coord);
		if (match)
		{
			coord = '0.' + '0'.repeat(match[2] - 1) + match[1].replace('.', '');
		}
		return coord;
	};

	this.loadFile = function(url, integrity, type, id)
	{
		var element = document.createElement(type);
		element.setAttribute('id', id);
		element.setAttribute('crossorigin', '');
		element.setAttribute('integrity', integrity);
		if (type == 'script')
		{
			element.setAttribute('type', 'text/javascript');
			element.setAttribute('src', url);
		}
		else
		{
			element.setAttribute('rel', 'stylesheet');
			element.setAttribute('href', url);
		}
		document.getElementsByTagName('head')[0].appendChild(element);
	};

	this.resetCatList = function()
	{
		$('#' + prefix + '_latitude, #' + prefix + '_longitude').prop('disabled', false);
		$('#' + prefix + '_cat_coords option').prop('selected', false);
		$('#' + prefix + '_cat_coords option[value="0"]').prop('selected', true);
	};

	this.setLatlongFields = function()
	{
		$('#' + prefix + '_latitude').val(self.getCoord(self.marker.getLatLng().lat));
		$('#' + prefix + '_longitude').val(self.getCoord(self.marker.getLatLng().lng));
	};

	this.setMarker = function(latlng)
	{
		self.deleteMarker();
		self.resetCatList();
		self.addMarker(latlng);
		self.map.setView(latlng, self.markerZoom);
	};

	this.setMap = function()
	{
		if (!$('#' + prefix + '_worldmap').length)
		{
			return;
		}

		self.map = L.map(prefix + '_worldmap',
		{
			center: [
				$('#' + prefix + '_worldmap').attr('data-lat'),
				$('#' + prefix + '_worldmap').attr('data-long')
			],
			zoom: $('#' + prefix + '_worldmap').attr('data-marker') == 1
				? self.markerZoom
				: $('#' + prefix + '_worldmap').attr('data-zoom')
		});
		var url = $('html').attr('lang') == 'fr'
			? 'https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
			: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
		self.osm = L.tileLayer(url,
		{
			attribution: '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
		});

		self.esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/'
			+ 'services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
		{
			attribution: '<a href="https://www.esri.com/">Esri</a>'
		});

		if ($('#' + prefix + '_worldmap').attr('data-layer') == 'satellite')
		{
			self.esri.addTo(self.map);
		}
		else
		{
			self.osm.addTo(self.map);
		}

		var layers = {};
		layers[leaflet_map_text] = self.osm;
		layers[leaflet_satellite_text] = self.esri;
		L.control.layers(layers, {}, {position: 'bottomleft'}).addTo(self.map);

		// Moteur de recherche.
		self.loadFile(leaflet_search_css_file,
			leaflet_search_css_file_integrity, 'link', 'leaflet_search_css');
		self.loadFile(leaflet_search_js_file,
			leaflet_search_js_file_integrity, 'script', 'leaflet_search_js');
		document.getElementById('leaflet_search_js').addEventListener('load', (event) =>
		{
			self.map.addControl(new GeoSearch.GeoSearchControl(
			{
				provider: new GeoSearch.OpenStreetMapProvider(),
				style: 'bar',
				autoClose: true,
				searchLabel: ' '
			}));
		});

		// Ajout du marqueur.
		if ($('#' + prefix + '_worldmap').attr('data-marker') == 1)
		{
			setTimeout(function(){self.addMarker(self.map.getCenter());}, 150);
		}

		if (typeof callback == 'function')
		{
			setTimeout(function(){callback();}, 150);
		}
	};

	// Ajout/suppresion du marqueur.
	$('body').on('click', '#' + prefix + '_marker', function()
	{
		// Suppression du marqueur.
		if (self.markerActive)
		{
			self.deleteMarker();
			self.resetCatList();
		}

		// Ajout du marqueur.
		else
		{
			self.addMarker(self.map.getCenter());
		}

		return false;
	});

	// Coordonnées d'une catégorie déjà géolocalisée.
	$('body').on('change', '#' + prefix + '_cat_coords', function()
	{
		var option = $(this).find('option:selected');

		if (self.markerActive)
		{
			self.deleteMarker();
		}
		if (option.val() > 0)
		{
			$('#' + prefix + '_latitude, #' + prefix + '_longitude').prop('disabled', true);

			var lat = option.attr('data-lat');
			var lng = option.attr('data-long');
			self.addMarker([lat, lng]);
			self.map.setView([lat, lng], self.markerZoom);
		}
		else
		{
			$('#' + prefix + '_latitude, #' + prefix + '_longitude').prop('disabled', false);
		}
	});

	// On réactive les champs désactivés lors de l'envoi du formulaire.
	$('body').on('submit', '#' + prefix + '_form', function()
	{
		$('#' + prefix + '_latitude, #' + prefix + '_longitude').prop('disabled', false);
	});

	// Initialisation.
	if ($('#leaflet_js').length)
	{
		self.setMap();
	}
	else
	{
		self.loadFile(leaflet_css_file, leaflet_css_file_integrity, 'link', 'leaflet_css');
		self.loadFile(leaflet_js_file, leaflet_js_file_integrity, 'script', 'leaflet_js');
		document.getElementById('leaflet_js').addEventListener('load', (event) =>
		{
			self.setMap();
		});
	}
}



/*
 * Listes flottantes.
 *
 */
jQuery(function($)
{
	if (!$('a[data-box-list]').length)
	{
		return;
	}

	// Élément de formulaire.
	var element_id;

	// Paramètres de la liste.
	var list_open = false;
	var list_type;

	// Ajax.
	var ajax_request;

	// Paramètres pour l'ajout de tags.
	var tags_item = [];

	// Paramètres pour la suppression de tags.
	var tags_delete = [];
	var tags_delete_flip = [];
	var tags_delete_selected = [];
	var timeout_loading;

	// Catégorie parente.
	var make_list_categories = function()
	{
		$('#box_list_outer h1 img').attr('src', style_path + '/icons/16x16/move.png');

		var list = Array.from($('#' + element_id).parents('p').find('option'));
		var html = '';
		var subcats = 0;
		for (var i in list)
		{
			var id = list[i].attributes['id'].nodeValue.replace(/[om]/i, 'x');
			var disabled = list[i].attributes['disabled'] ? ' disabled' : '';
			var title = list[i].innerHTML
				.replace(/(^([\r\n\t\s]|&nbsp;)*|([\r\n\t\s]|&nbsp;)*$)/g, '');
			html += `<li${disabled} id="${id}">`;
			if (id.match(/s/)
			&& $('#' + element_id + ' option[id*="}' + id.split('}')[1] + '."]').length > 0)
			{
				html += '<i>+</i>';
				if (subcats < 1 && parseInt(id.replace(/^.+\{(\d+)\}.+$/, '$1')) > 1)
				{
					subcats = 1;
				}
			}
			html += `<a href="javascript:;"><b>${title}</b></a>`;
			html += '</li>';
		}

		$('#box_list')
			.append('<ul tabindex="-1">' + html + '</ul>')
			.addClass('browse cat_list')
			.attr('data-subcats', subcats);

		cat_list_current('#box_list');

		if ($('#box_list li[id*="c"]').length)
		{
			$('#box_list').scrollTop(0);
			var top = $('#box_list li[id*="c"]').offset().top;
			var height_current = $('#box_list li[id*="c"]').outerHeight();
			var height_list = $('#box_list').outerHeight();
			var n = Math.floor((height_list / height_current) / 3);
			$('#box_list').scrollTop(
				top - $('#box_list').offset().top - (n * height_current)
			);
		}

		$('#box_list li > i').click(function()
		{
			cat_list_subcats($(this));
			$('#box_list_search input').focus();
		});

		// Chemin de la catégorie.
		box_info('#box_list_container');
	};

	// Ajout de tags.
	var make_list_tags_add = function()
	{
		$('#box_list_outer h1 img').attr('src', style_path + '/icons/16x16/tag.png');

		// Aucun tag ?
		if (!tags.length)
		{
			$('#box_list').append(
				'<p class="box_list_message">' + l10n_list_tags_empty + '</p>'
			);
			return;
		}

		// Fabrication de la liste.
		var html = '<ul>';
		for (var i in tags)
		{
			html += '<li class="link" data-tag-id="' + i
				+ '"><span class="checkbox"><span></span></span>'
				+ '<span>' + $('<textarea>').text(tags[i]).html() + '</span></li>';
		}
		html += '</ul>';
		$('#box_list').append(html);

		// Tags sélectionnés.
		tags_item = $('#' + element_id).val().split(',').filter(function(e)
		{
			return !e.match(/^\s*$/);
		});
		if (tags_item.length)
		{
			for (var i in tags_item)
			{
				tags_item[i] = tags_item[i].replace(/(^\s+|\s+$)/, '');
				if (tags_flip[tags_item[i]])
				{
					$('#box_list li[data-tag-id="' + tags_flip[tags_item[i]] + '"]')
						.addClass('selected');
				}
			}
		}
	};

	// Suppression de tags.
	var make_list_tags_delete = function()
	{
		$('#box_list_outer h1 img').attr('src', style_path + '/icons/16x16/tag.png');

		if (!selected_group_id.length)
		{
			$('#box_list').append(
				'<p class="box_list_message">' + l10n_items_none_selected + '</p>'
			);
			return;
		}

		// Icône de chargement.
		timeout_loading = setTimeout(function()
		{
			var html = '<div id="box_list_loading"><div class="loading"></div></div>';
			$('#box_list').append(html);
		}, 250);

		// Récupération des tags.
		ajax_request = $.post(
			gallery_path + '/ajax.php',
			{
				anticsrf: anticsrf,
				section: 'grid-get-tags-items',
				id: selected_group_id.join(',')
			},
			function(r)
			{
				if (typeof r != 'object' || r === null)
				{
					return;
				}
				switch (r.status)
				{
					case 'error' :
						alert('error: ' + r.message);
						break;

					case 'success' :
						tags_delete = r.tags;
						clearTimeout(timeout_loading);
						$('#box_list_loading').remove();

						if (tags_delete.length)
						{
							tags_delete_flip = [];
							for (var i in tags_delete)
							{
								tags_delete_flip[tags_delete[i]] = i;
							}

							// Fabrication de la liste.
							var html = '<ul>';
							for (var i in tags_delete)
							{
								html += '<li class="link" data-tag-id="' + i
									+ '"><span class="checkbox"><span></span></span>'
									+ '<span>' + $('<textarea>').text(tags_delete[i]).html()
									+ '</span></li>';
							}
							html += '</ul>';
							$('#box_list').append(html);

							// Tags sélectionnés.
							tags_delete_selected = $('#' + element_id).val().split(',')
							.filter(function(e)
							{
								return !e.match(/^\s*$/);
							});
							if (tags_delete_selected.length)
							{
								for (var i in tags_delete_selected)
								{
									tags_delete_selected[i] = tags_delete_selected[i]
										.replace(/(^\s+|\s+$)/, '');
									if (tags_delete_flip[tags_delete_selected[i]])
									{
										$('#box_list li[data-tag-id="'
											+ tags_delete_flip[tags_delete_selected[i]] + '"]')
											.addClass('selected');
									}
								}
							}
						}
						else
						{
							$('#box_list').append(
								'<p class="box_list_message">' + r.text_no_tag + '</p>'
							);
						}
						break;
				}
			},
			'json'
		);
	};

	// Tableau des tags.
	if (typeof tags !== 'undefined')
	{
		for (var i in tags)
		{
			tags[i] = $('<textarea>').html(tags[i]).text();
			tags_flip[tags[i]] = i;
		}
	}

	// Ouverture de la liste.
	$('body').on('click', 'a[data-box-list]', function()
	{
		list_open = true;
		list_type = $(this).attr('data-box-list');
		page_scrollbar_hide();
		var title = $(this).attr('data-box-title')
			? $(this).attr('data-box-title')
			: $(this).attr('title');

		var html = '<section data-box-list="' + list_type
			+ '" id="box_list_container"><div id="box_list_outer">'
			+ '<div id="box_list_title"><h1><img width="16" height="16"><span>' + title
			+ '</span></h1><span id="box_list_close"></span></div><div id="box_list_inner">'
			+ '<p id="box_list_search" class="field"><input name="search" type="text"></p>'
			+ '<div id="box_list"></div></div><div class="box_info"></div></div></section>';
		$('main').append(html);

		element_id = $(this).parents('p')
			.find(list_type == 'categories' ? 'select' : 'textarea').attr('id');

		if (list_type == 'categories')
		{
			make_list_categories();
		}
		if (list_type == 'tags_add')
		{
			make_list_tags_add();
		}
		if (list_type == 'tags_delete')
		{
			make_list_tags_delete();
		}

		$('#box_list_search input').focus();

		return false;
	});

	// Fermeture de la liste.
	var close_list = function()
	{
		if (ajax_request)
		{
			ajax_request.abort();
		}
		list_open = false;
		$('#box_list_container').remove();
		page_scrollbar_show();
		$('#' + element_id).focus();
	};
	$('body').on('click', '#box_list_container,#box_list_close', function()
	{
		close_list();
		return false;
	});
	$('body').on('click', '#box_list_outer', function(e)
	{
		e.stopPropagation();
	});
	$(window).keyup(function(e)
	{
		if (list_open && e.keyCode == 27)
		{
			close_list();
		}
	});

	// Sélection d'un élément de la liste.
	$('body').on('click', '#box_list a, #box_list .link', function()
	{
		if (list_type == 'categories' && !$(this).parents('li').attr('disabled'))
		{
			$('#' + element_id).children('option').prop('selected', false);
			$('#' + element_id).children('option[value="'
				+ cat_list_infos($(this).parents('li')).id + '"]').prop('selected', true);
			close_list();
		}

		if (list_type == 'tags_add')
		{
			var tag_name = tags[$(this).attr('data-tag-id')];
			if ($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
				tags_item = tags_item.filter(function(e)
				{
					return e != tag_name;
				});
			}
			else
			{
				$(this).addClass('selected');
				tags_item.push(tag_name);
			}
			$('#' + element_id).val(tags_item.join(', '));
			$('#box_list_search input').focus();
		}

		if (list_type == 'tags_delete')
		{
			var tag_name = tags_delete[$(this).attr('data-tag-id')];
			if ($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
				tags_delete_selected = tags_delete_selected.filter(function(e)
				{
					return e != tag_name;
				});
			}
			else
			{
				$(this).addClass('selected');
				tags_delete_selected.push(tag_name);
			}
			$('#' + element_id).val(tags_delete_selected.join(', '));
			$('#box_list_search input').focus();
		}

		return false;
	});

	// Barre de recherche.
	$('body').on('input', '#box_list_search input', function()
	{
		var val = $(this).val();
		var regexp = new RegExp(search_escape(val), 'i');
		$('#box_list li').hide();
		if (list_type == 'categories')
		{
			$('#box_list li:not(:first-child)').each(function()
			{
				if (regexp.test($(this).find('b').text()))
				{
					if (!$(this).attr('disabled'))
					{
						$(this).css('display', 'flex');
					}
				}
			});
			if (val === '')
			{
				$('#box_list').removeClass('search');
				$('#box_list li[id*="v"]').css('display', 'flex');
				$('#box_list li:not([id*="v"])').css('display', 'none');
			}
			else
			{
				$('#box_list').addClass('search');
			}
		}
		else
		{
			$('#box_list li').each(function()
			{
				if (regexp.test($(this).find('span:last-child').text()))
				{
					$(this).show();
				}
			});
		}
	});
});



/*
 * Général.
 *
 */
jQuery(function($)
{
	report();

	// Liens pour montrer / cacher des éléments.
	$('body').on('click', '.showhide', function()
	{
		var sel = $(this).attr('rel');
		if ($(sel).is(':hidden'))
		{
			$(sel).addClass('show');
		}
		else
		{
			$(sel).removeClass('show');
		}
		return false;
	});
	$('body').on('click', '.hide_all', hide_all);
	$('body').on('click', '.show_all', show_all);

	// Outils de sélections des objets.
	$('body').on('click', '.select_all', select_all);
	$('body').on('click', '.select_none', select_none);
	$('body').on('click', '.select_invert', select_invert);

	// Vidéos.
	$('video').prop('volume', 0.5);

	// Liens des fichiers d'aides contextuelles.
	$('#help a').each(function()
	{
		$(this).attr('referrerpolicy', 'no-referrer');
	});

	// Changement de page.
	$('body:not(.grid) .pages form').submit(function()
	{
		var page = $(this).find('input[name="page"]').val();
		if (page.match(/^\d{1,12}$/) && !page.match(/^0/)
		&& parseInt(page) <= parseInt($(this).find('.count').text()))
		{
			window.location.href = '?q=' + q_pageless + '/page/' + page;
		}
		return false;
	});

	// Envoi de fichier.
	$('input[type="file"]').change(function(e)
	{
		if (e.target.value)
		{
			var filename = e.target.value.replace(/^.*?([^/\\]+)$/, '$1');
			var id = $(this).attr('id');
			$('#' + id + ' + label').text(filename);
		}
	});
	$('form[data-upload-check="1"]').submit(function()
	{
		var ok = true;
		$(this).find('input[type="file"]').each(function()
		{
			if ($(this).attr('data-maxsize'))
			{
				if (this.files[0].size > parseInt($(this).attr('data-maxsize')))
				{
					alert(htmldecode(maxsize_text));
					ok = false;
				}
			}
		});
		return ok;
	});

	// Bouton "Réinitialiser" des formulaires.
	$('.reset_js').click(function()
	{
		$(this).parents('form').find('*[data-reset]').each(function()
		{
			var reset = $(this).attr('data-reset');
			var type = $(this).attr('type');
			if ($(this).is('input'))
			{
				if ($.inArray(type, ['email', 'number', 'password', 'text', 'url']) !== -1)
				{
					$(this).val(reset);
				}
				if ($.inArray(type, ['checkbox', 'radio']) !== -1)
				{
					$(this).prop('checked', reset == '1');
				}
			}
			if ($(this).is('select'))
			{
				$(this).find('option').each(function()
				{
					$(this).prop('selected', $(this).val() == reset)
				});
			}
		});
		return false;
	});

	// Liens "viewer".
	$('body').on('click', '.viewer', function()
	{
		viewer($(this).attr('href'));
		return false;
	});

	// Ajout d'un bouton permettant de visionner les mots de passe en clair.
	$('input[data-password-view]').each(function()
	{
		$(this).wrapAll('<span class="password_container">');
		$(this).after('<span class="password_view"><a>&#xe9ce;</a></span>');
		if ($(this).attr('autofocus'))
		{
			$(this).focus();
		}
	});
	$('body').on('click', '.password_view', function()
	{
		var e = $(this).parents('.password_container').find('input');
		if (e.attr('type') == 'text')
		{
			e.attr('type', 'password');
			$(this).find('a').html('&#xe9ce;');
		}
		else
		{
			e.attr('type', 'text');
			$(this).find('a').html('&#xe9d1;');
		}
		e.focus();
		return false;
	});

	// Lien de déconnexion.
	$('#user_logout').click(function()
	{
		$.post(
			gallery_path + '/ajax.php',
			{
				anticsrf: anticsrf,
				section: 'logout',
				from_admin: 1
			},
			function(r)
			{
				if (typeof r != 'object' || r === null)
				{
					return;
				}
				switch (r.status)
				{
					case 'error' :
						alert('error: ' + r.message);
						break;

					case 'success' :
						window.location = r.redirect;
						break;
				}
			},
			'json'
		);
		return false;
	});

	// Actions sur la sélection sans Javascript.
	$('#selection_action option[value$="_confirm"]').each(function()
	{
		$(this).val($(this).val().replace('_confirm', ''));
	});

	// Confirmation de suppression.
	var delete_confirm = function()
	{
		if ($(this).attr('name') == 'delete'
		|| $('#selection_action option[value="delete"]').prop('selected'))
		{
			return confirm(htmldecode(confirm_delete));
		}
	};
	$('input[name="delete_confirm"][type="submit"]').attr('name', 'delete');
	$('input[name="delete"][type="submit"]').parents('form')
		.find('input[type="submit"]').click(delete_confirm);
	$('option[value="delete"]').parents('form')
		.find('input[type="submit"][name="selection"]').click(delete_confirm);

	// Pour la sélection, on affiche l'élément secondaire selon le type d'action choisi.
	$('#selection_action').change(function()
	{
		$(this).find('option[data-id]').each(function()
		{
			if ($(this).prop('selected'))
			{
				$('#' + $(this).attr('data-id')).css('display', 'inline-block');
			}
			else
			{
				$('#' + $(this).attr('data-id')).css('display', 'none');
			}
		});
	});

	// Affichage d'éléments de la page courante.
	$('.show_parts').click(function()
	{
		var id = '#' + $(this).find('a').attr('data-id');
		var obj_id = id.replace(/^.*_(\d+)$/, '$1');
		if ($(id).is(':hidden'))
		{
			$('#obj_' + obj_id  + ' .obj_fold').removeClass('show');
			$('#obj_' + obj_id  + ' a.show').removeClass('show');
			$(this).find('a').addClass('show');
			$(id).addClass('show');
			$('#' + $(id + ' p label').attr('for')).focus();
		}
		else
		{
			$(this).find('a').removeClass('show');
			$(id).removeClass('show');
		}
		return false;
	});

	// Affichage d'outils (options, recherche, etc.).
	$('.show_tool').click(function()
	{
		$('.show_tool a').removeClass('show');
		var id = '#' + $(this).find('a').attr('data-id');
		if ($(id).is(':hidden'))
		{
			$('.tool').not($(id)).hide();
			$(id).show();
			$(this).find('a').addClass('show');
			$(id + ' .focus').focus();
		}
		else
		{
			$(id).hide();
		}
		return false;
	});

	// Sélection d'objets.
	{
		// Initialisation.
		$('.selectable').prop('checked', false);

		// Case à cocher.
		$('.selectable').click(function()
		{
			select($(this), 'invert');
		});

		// Zone de sélection.
		$('.selectable_zone').click(function()
		{
			select($(this).find('.selectable'), 'invert');
		});
	}

	// Édition de dates.
	$('.dt_now').click(function()
	{
		var dt = new Date();
		$(this).parents('p').find('.dt_year').val(dt.getFullYear());
		$(this).parents('p').find('.dt_month').val(('0' + (dt.getMonth()+1)).slice(-2));
		$(this).parents('p').find('.dt_day').val(('0' + dt.getDate()).slice(-2));
		$(this).parents('p').find('.dt_hour').val(('0' + dt.getHours()).slice(-2));
		$(this).parents('p').find('.dt_minute').val(('0' + dt.getMinutes()).slice(-2));
		$(this).parents('p').find('.dt_second').val(('0' + dt.getSeconds()).slice(-2));
		return false;
	});
	$('.dt_reset').click(function()
	{
		$(this).parents('p').find('input').val('');
		return false;
	});

	// Gestion de l'affichage du menu.
	$('.js_menu_link').click(function(e)
	{
		if ($('#menu').is(':hidden'))
		{
			$('.js_box_inner').fadeOut(150);

			$('#menu').show('slide', { direction: 'left' }, 150, function()
			{
				$(window).keyup(function(e)
				{
					$(this).off('keyup');
					if (e.keyCode == 27)
					{
						$('#menu').hide('slide', { direction: 'left' }, 150);
					}
				});
				$(window).click(function()
				{
					if (!$('#header_links > img').is(':visible'))
					{
						$(this).off('click');
						$('#menu').hide('slide', { direction: 'left' }, 150);
					}
				});
				$('#menu').click(function(e)
				{
					$(this).off('click');
					e.stopPropagation();
				});
			});
		}
		else
		{
			$('#menu').hide('slide', { direction: 'left' }, 150);
		}
		e.stopPropagation();
		return false;
	});

	// Réinitialisation des formulaires.
	$('form').trigger('reset');

	// Mode d'affichage et affichage en grille.
	$('#display a:not(.current)').click(function()
	{
		$('input[name="display"]').val($(this).attr('id').replace('display_', ''));
		$('#display form').submit();
		return false;
	});
	if ($('#obj_grid').is('div'))
	{
		new Grid($('#obj_grid').attr('data-section'));
	}

	// Autoclicks et focus sur les champs à erreur (doit être en dernier).
	$('.autoclick').click();
	$('.autofocus').focus();
	$('.field_error input,.field_error textarea').focus();

	// Géolocalisation.
	if ($('#geolocation_container').length)
	{
		new Worldmap('geolocation');
	}

	// Réinitilisation de la date de publication.
	change_reset_item_pubdt($('#status').val(), '#reset_item_pubdt');
	$('body').on('change', '#status', function()
	{
		change_reset_item_pubdt($(this).val(), '#reset_item_pubdt');
	});

	// Captures vidéos.
	if (typeof captures !== 'undefined')
	{
		VideoCaptures(captures);
	}
});



/**
 * Page "Thèmes".
 *
 */
jQuery(function($)
{
	if (!$('#themes').length)
	{
		return;
	}

	$('.theme img, .theme_button').click(function()
	{
		$('.theme').removeClass('selected');
		$('.theme input[type="radio"]').prop('checked', false);
		$(this).parents('.theme').addClass('selected');
		$(this).parents('.theme').find('input[type="radio"]').prop('checked', true);
	});
});



/**
 * Page "Carte du monde".
 *
 */
jQuery(function($)
{
	if (!$('#section_page_worldmap').length)
	{
		return;
	}

	var geolocation = new Worldmap('geolocation');

	$('#geolocation_form input[type="submit"]').click(function()
	{
		var lat = geolocation.map.getCenter().lat;
		var lng = geolocation.map.getCenter().lng;
		var zoom = geolocation.map.getZoom();
		$(this).append(
			'<input name="latitude" type="hidden" value="' + lat + '">' +
			'<input name="longitude" type="hidden" value="' + lng + '">' +
			'<input name="zoom" type="hidden" value="' + zoom + '">'
		);
	});
});



/**
 * Objets "mini" de la partie "Réglages".
 *
 */
jQuery(function($)
{
	if (!$('#obj_mini_form').is('form'))
	{
		return;
	}

	// Actions.
	$('body').on('click', '.obj_mini_action .icon', function()
	{
		switch ($(this).attr('data-action'))
		{
			case 'delete' :
				$(this).parents('.obj_mini').remove();
				break;

			case 'edit' :
				var edit = $(this).parents('.obj_mini').find('.obj_mini_edit');
				if (edit.is(':hidden'))
				{
					edit.slideDown(250, function()
					{
						edit.find('p:first input').focus();
					});
				}
				else
				{
					edit.slideUp(250);
				}
				break;
		}
		return false;
	});

	// Tri.
	$('#obj_mini_form').sortable(
	{
		axis: "y",
		containment: 'main',
		items: '.obj_mini',
		handle: '.obj_mini_sortable',
		opacity: 0.5
	});
	$('#obj_mini_form').submit(function()
	{
		$('input[name="serial"]').val($(this).sortable('serialize'));
	});

	// Tags des métadonnées.
	$('#meta_tags_link').click(function()
	{
		if ($('#obj_mini_form').hasClass('tags'))
		{
			$('#obj_mini_form').removeClass('tags');
			$(this).text(tags_name_show_text)
		}
		else
		{
			$('#obj_mini_form').addClass('tags');
			$(this).text(tags_name_hide_text)
		}
		return false;
	});
});



/**
 * Liens externes.
 *
 */
jQuery(function($)
{
	if ($('body').attr('id') != 'section_links')
	{
		return;
	}

	// Ajout d'un lien.
	$('#link_add').click(function()
	{
		$('.obj_mini_edit').hide();
		var n = 0;
		while ($('#i_' + n).is('div'))
		{
			n++;
		}
		$('#obj_mini_form > div:first-child').prepend(
			link_html.replace(/{style_path}/g, style_path).replace(/{id}/g, n)
		);
		$('#i_' + n).find('span[data-action="edit"] a').click();
		return false;
	});
});



/**
 * Aide contextuelle.
 *
 */
jQuery(function($)
{
	var focused_element;
	var focused_help_icon;
	var help_open = false;

	$('*[data-help-icon]').each(function()
	{
		$(this).after('<a data-help-link="' + $(this).attr('data-help-icon')
			+ '" title="' + $('#help').attr('data-text-link')
			+ '"class="help_link" href="javascript:;">'
			+ '<img width="16" height="16" src="'
			+ style_path + '/icons/16x16/help-link.png"></a>');
	});

	$('body').on('mousedown', '.help_link,.html_inner > span', function()
	{
		focused_element = $(':focus');
	});

	$('body').on('click', '.help_link,.html_inner > span', function()
	{
		focused_help_icon = $(':focus');

		page_scrollbar_hide();

		if ($(this).parent().hasClass('html_inner'))
		{
			$('main').append(help_html);
		}
		else
		{
			var item = $(this).attr('data-help-link');
			var content = $('section[data-help-content="' + item + '"]');
			if (!content.is('section'))
			{
				return false;
			}
			$('main').append('<section class="help_context" data-help-id="' + item + '"><div>'
				+ '<div class="help_title">'
					+ '<h1><span class="icon icon_help">'
					+ content.find('h1').text()
					+ '</span></h1>'
					+ '<span class="help_close"></span>'
				+ '</div>'
				+ '<div class="help_content">' + content.html() + '</div>'
			+ '</div></section>');
		}

		help_open = true;
		return false;
	});

	$('body').on('click', '.help_close', function()
	{
		$('.help_context').remove().off('keyup');
		page_scrollbar_show();
		help_open = false;
		if ((focused_element.is('input') && $.inArray(focused_element.attr('type'),
		['email', 'number', 'password', 'text', 'url']) !== -1) || focused_element.is('textarea'))
		{
			focused_element.focus();
		}
		else
		{
			focused_help_icon.focus();
		}
		return false;
	});

	$('body').on('click', '.help_context', function()
	{
		$(this).find('.help_close').click();
		return false;
	});

	$('body').on('click', '.help_context > div', function(e)
	{
		e.stopPropagation();
	});

	$(window).keyup(function(e)
	{
		if (help_open && e.keyCode == 27)
		{
			$('.help_context').find('.help_close').click();
		}
	});
});



/**
 * Tableau de bord.
 *
 */
jQuery(function($)
{
	if (!$('#section_dashboard').length)
	{
		return;
	}

	// Navigation entre éléments d'un bloc.
	$(this).find('.dashboard_nav a').click(function()
	{
		var prev_or_next = $(this).attr('class').replace('dashboard_', '');
		var nb_items = $(this).parents('.dashboard_bloc')
			.find('.' + $(this).attr('rel')).length;
		var current = $(this).parents('.dashboard_bloc')
			.find('.' + $(this).attr('rel') + ':visible');
		var current_n = current.attr('id').replace($(this).attr('rel') + '_', '');
		var current_n_new = (prev_or_next == 'next' ?
				parseInt(current_n) + 1 : parseInt(current_n) - 1);

		// Élément courant.
		current.css('display', 'none');
		$(this).parents('.dashboard_bloc')
			.find('#' + $(this).attr('rel') + '_' + current_n_new).css('display', 'flex');

		// Position courante.
		$(this).parents('.dashboard_bloc').find('.dashboard_nav span')
			.text(current_n_new + '/' + nb_items);

		// Liens de navigation.
		if (current_n == 1)
		{
			$(this).parents('.dashboard_bloc').find('.dashboard_prev')
				.css('visibility', 'visible');
		}
		if (current_n == 2 && prev_or_next == 'prev')
		{
			$(this).parents('.dashboard_bloc').find('.dashboard_prev')
				.css('visibility','hidden');
		}
		if (parseInt(current_n) + 1 == nb_items && prev_or_next == 'next')
		{
			$(this).parents('.dashboard_bloc').find('.dashboard_next')
				.css('visibility', 'hidden');
		}
		if (current_n == nb_items)
		{
			$(this).parents('.dashboard_bloc').find('.dashboard_next')
				.css('visibility', 'visible');
		}

		return false;
	});
});




/**
 * Boîtes flottantes.
 *
 */
jQuery(function($)
{
	// Listes "Parcourir".
	if ($('#browse').is('div'))
	{
		// Dimensions.
		var resize = function()
		{
			var available_height = $(window).height();
			var top = Math.round($('#browse_link')[0].getBoundingClientRect().bottom);
			var max_height = available_height - top - 200;
			max_height = max_height > 600 ? 600 : max_height;
			$('#browse_inner > div').css('maxHeight', max_height + 'px');

			// On corrige un petit problème de largeur avec la barre de défilement.
			if ($('#browse.cat_list').length)
			{
				return;
			}
			var visible = $('#browse_content').is(':visible');
			if (!visible)
			{
				$('#browse_content').css({'display': 'block', 'opacity': '0'});
			}
			$('#browse_inner > div').css(
			{
				'overflow-y': $('#browse ul').height() > $('#browse_inner > div').height()
					? 'scroll'
					: 'auto'
			});
			if (!visible)
			{
				$('#browse_content').css({'display': 'none', 'opacity': '1'});
			}
		};
		resize();
		$(window).resize(function(){resize();});

		// Recherche.
		$('#browse_search input').val('');
		$('#browse_search').on('input', function(e)
		{
			$('#browse_inner').css('width', $('#browse_inner').width() + 'px');

			var val = $(this).children('input').val();
			var regexp = new RegExp(search_escape(val), 'i');
			$('#browse li').hide();
			var selector = $('#browse.cat_list').length
				? '#browse li:not(:first-child)'
				: '#browse li:not([id*="!"])';
			$(selector).each(function()
			{
				if (regexp.test($(this).find('b').text()))
				{
					if ($('#browse.cat_list').length)
					{
						$(this).css('display', 'flex');
					}
					else
					{
						$(this).show();
					}
				}
			});
			if (val === '')
			{
				$('#browse').removeClass('search');
				$('#browse li[id*="v"]').css('display', 'flex');
				$('#browse li:not([id*="v"])').css('display', 'none');
			}
			else
			{
				$('#browse').addClass('search');
			}
			resize();
		});

		// Catégorie courante.
		cat_list_current('#browse');

		// Sous-catégories.
		$('.cat_list li > i').off().click(function()
		{
			cat_list_subcats($(this));
		});

		// Liens.
		$('#browse li').each(function()
		{
			if ($(this).find('a').attr('href') != 'javascript:;')
			{
				return true;
			}
			var i = cat_list_infos($(this));
			if (i.id > 1 && !$(`#browse li[id$=".${i.id}"]`).length)
			{
				$(this).find('> i').remove();
			}
			var p = q_pageless.split('/');
			var id = parseInt(i.id);
			var section_replace = function(c)
			{
				if (p.length == 5)
				{
					p = id > 0 ? [p[0], c, id, p[3], p[4]] : [p[0], p[3], p[4]];
				}
				else if (p.length == 3 && p[1] != c)
				{
					p = id > 0 ? [p[0], c, id, p[1], p[2]] : p;
				}
				else
				{
					p = id > 0 ? [p[0], c, id] : [p[0]];
				}
			};
			if ($(this).parents('#browse').hasClass('cat_list'))
			{
				var type = $(this).attr('id').match('t') ? 'category' : 'album';
				var section = p[0].split('-');
				switch (section[0])
				{
					case 'album' :
					case 'category' :
						if ((section[1] == 'items' && type == 'album')
						 || (section[1] != 'items' && section[1] != 'sort' && id == 1))
						{
							p[0] = type;
							p[1] = id;
							break;
						}
						p[0] = p[0].replace(/^(album|category)/, type);
						p[1] = id;
						break;
					case 'items' :
						if (section[1] == 'pending')
						{
							p[1] = id;
						}
						break;
					case 'comments' :
					case 'votes' :
						if ($.inArray(p[1],
						['date', 'ip', 'item', 'note', 'search', 'user']) !== -1)
						{
							p = [p[0], type, id, p[1], p[2]];
						}
						else if (p[1] == 'pending')
						{
							p = [p[0], type, id, p[1]];
						}
						else if (p.length > 2)
						{
							p[1] = type;
							p[2] = id;
						}
						else
						{
							p[0] += '/' + type;
							p[1] = id;
						}
						break;
				}
			}
			else if (p[0] == 'logs')
			{
				section_replace('user');
			}
			else if (p[0] == 'users')
			{
				section_replace('group');
			}
			else
			{
				p[1] = id;
			}
			$(this).find('a').attr('href', admin_path + '/?q=' + p.join('/'));
		});
	}

	// Gestion de l'affichage des boîtes.
	var anim_speed = 200;
	var timeout_box = [];
	var z_index_change = false;
	var open = false;
	var close_box = function(box_id)
	{
		z_index_change = true;
		$('#' + box_id + ' .js_box_inner').fadeOut(anim_speed, function()
		{
			if (z_index_change)
			{
				$('.js_box').css('z-index', 14);
			}
		});
		$('#' + box_id).off('keyup');
		open = false;
	};
	var hide_box = function(box_id)
	{
		if ($('#' + box_id + ' .js_box_inner').is(':hidden')
		 || $('#' + box_id + ' .js_box_link').is(':hidden')
		 || $('#' + box_id + ' .js_box_inner input:first').is(':focus')
		 || !open)
		{
			return;
		}
		clear_box(box_id);
		timeout_box[box_id] = setTimeout(function(){close_box(box_id);}, 500);
	};
	var clear_box = function(box_id)
	{
		clearTimeout(timeout_box[box_id]);
	};
	$('.js_box_inner')
		.bind('mouseenter', function() { clear_box($(this).parents('.js_box').attr('id')) })
		.bind('mouseleave', function() { hide_box($(this).parents('.js_box').attr('id')) });
	$('.js_box_link')
		.bind('mouseenter', function() { clear_box($(this).parents('.js_box').attr('id')) })
		.bind('mouseleave', function() { hide_box($(this).parents('.js_box').attr('id')); });
	$('.js_box_link,.js_box_title').click(function()
	{
		var box_id = $(this).parents('.js_box').attr('id');
		z_index_change = false;
		for (var bi in timeout_box)
		{
			clearTimeout(timeout_box[bi]);
		}
		if ($('#' + box_id + ' .js_box_inner').is(':hidden'))
		{
			// Fermeture de toutes les boîtes.
			$('.js_box_inner').hide();

			// Si le menu est ouvert, on le ferme.
			if (!$('#menu .js_menu_link').is(':hidden'))
			{
				$('#menu .js_menu_link').click();
			}

			// On place la boîte courante devant toutes les autres.
			$('.js_box').css('z-index', 13);
			$('#' + box_id + '.js_box').css('z-index', 14);

			// Ouverture de la boîte.
			$('#' + box_id + ' .js_box_inner').css({'opacity':0}).show();
			if (box_id == 'browse')
			{
				if ($('#browse_inner li[id*="c"]').length)
				{
					$('#browse_inner > div').scrollTop(0);
					var top = $('#browse_inner li[id*="c"]').offset().top;
					var height_current = $('#browse_inner li[id*="c"]').outerHeight();
					var height_list = $('#browse_inner > div').outerHeight();
					var n = Math.floor((height_list / height_current) / 3);
					$('#browse_inner > div').scrollTop(
						top - $('#browse_inner > div').offset().top - (n * height_current)
					);
				}
				if ($('#browse_inner .box_info'))
				{
					box_info('#browse_inner');
				}
			}
			$('#' + box_id + ' .js_box_inner').animate({'opacity':1}, anim_speed, function()
			{
				$('#' + box_id + ' .js_box_inner input:first').focus();
				open = true;
			});

			// Evénements pour la fermeture de la boîte.
			$(window).click(function() { close_box(box_id); $(this).off('click'); });
			$('#' + box_id).click(function(e) { e.stopPropagation(); });
			$('#' + box_id).keyup(function(e) { if (e.keyCode == 27) { close_box(box_id); } });
		}
		else
		{
			close_box(box_id);
		}

		return false;
	});
});



/*
 * Section "Albums".
 *
 */
jQuery(function($)
{
	if ($('body').attr('id') != 'section_category'
	 && $('body').attr('id') != 'section_category_items'
	 && $('body').attr('id') != 'section_album'
	 && $('body').attr('id') != 'section_item_replace')
	{
		return;
	}

	// Envoi de fichiers.
	if (typeof upload_options != 'undefined')
	{
		new Upload('upload_', upload_options);
	}

	// Action sur la sélection, déplacer vers...
	if (!$('#list_categories_select option').length)
	{
		if ($('#obj_form').length)
		{
			$('#list_categories_select').html(
				get_select_categories($('#obj_form').attr('data-type'))
			);
		}
	}
});



/*
 * Section Tags.
 *
 */
jQuery(function($)
{
	if (!$('#section_tags').length)
	{
		return;
	}

	$('#new_tags .icon_add').click(function()
	{
		var html = $('<input>').append($('#new_tags_fields input:last-child').clone()).html();
		$('#new_tags_fields').append(html.repeat(4));
		return false;
	});
});



/*
 * Section Utilisateurs / Groupes / Permissions d'accès aux catégories.
 *
 */
jQuery(function($)
{
	if ($('body').attr('id') != 'section_group_categories')
	{
		return;
	}

	// Type de liste sélectionnée.
	$('#blacklist,#whitelist').each(function()
	{
		if ($(this).prop('checked'))
		{
			$(this).parents('.group_categories').addClass('select');
		}
	});

	// Modifie le style du type de liste sélectionné.
	$('#blacklist,#whitelist').click(function()
	{
		$('.group_categories').removeClass('select');
		$(this).parents('.group_categories').addClass('select');
	});

	// Déplie et replie des catégories.
	$('#group_categories li > span a').click(function()
	{
		if (!$(this).parents('.group_categories').hasClass('select'))
		{
			return false;
		}
		if ($(this).parent().hasClass('fold'))
		{
			$(this).parent().children('span + a + ul').css('display', 'block');
			$(this).parent().removeClass('fold');
			$(this).text('[-]');
		}
		else
		{
			$(this).parent().children('span + a + ul').css('display', 'none');
			$(this).parent().addClass('fold');
			$(this).text('[+]');
		}
		return false;
	});

	// Permissions de la liste noire.
	$('#group_blacklist .perm').click(function()
	{
		if (!$(this).parents('.group_categories').hasClass('select'))
		{
			return false;
		}
		if ($(this).hasClass('allowed'))
		{
			$(this).parent().find('.perm').each(function()
			{
				$(this)
					.removeClass('allowed')
					.removeClass('forbidden_child')
					.addClass('forbidden')
					.addClass('by_parent');
			});
			$(this).parents().each(function()
			{
				$(this).children('.perm')
					.addClass('forbidden_child');
			});
			$(this).removeClass('by_parent').removeClass('forbidden_child');
		}
		else if ($(this).hasClass('forbidden') && !$(this).hasClass('by_parent'))
		{
			$(this).parent().find('.perm').each(function()
			{
				$(this)
					.removeClass('forbidden')
					.removeClass('by_parent')
					.addClass('allowed');
			});
			$(this).parents().each(function()
			{
				if (!$(this).find('ul .perm').hasClass('forbidden'))
				{
					$(this).children('.perm')
						.removeClass('forbidden_child');
				}
			});
		}
		return false;
	});

	// Permissions de la liste blanche.
	$('#group_whitelist .perm').click(function()
	{
		if (!$(this).parents('.group_categories').hasClass('select'))
		{
			return false;
		}
		if ($(this).hasClass('forbidden'))
		{
			$(this).parent().find('.perm').each(function()
			{
				$(this)
					.removeClass('forbidden')
					.removeClass('allowed_child')
					.addClass('allowed')
					.addClass('by_parent');
			});
			$(this).parents().each(function()
			{
				$(this).children('.perm')
					.addClass('allowed_child');
			});
			$(this).removeClass('by_parent').removeClass('allowed_child');
		}
		else if ($(this).hasClass('allowed') && !$(this).hasClass('by_parent'))
		{
			$(this).parent().find('.perm').each(function()
			{
				$(this)
					.removeClass('allowed')
					.removeClass('by_parent')
					.addClass('forbidden');
			});
			$(this).parents().each(function()
			{
				if (!$(this).find('ul .perm').hasClass('allowed'))
				{
					$(this).children('.perm')
						.removeClass('allowed_child');
				}
			});
		}
		return false;
	});

	// Envoi du formulaire.
	$('#group_categories_form').submit(function()
	{
		// Nouvelle liste noire.
		var blacklist = '';
		$('#group_blacklist a.forbidden:not(.by_parent)').each(function()
		{
			blacklist += (blacklist != '' ? ',' : '') + $(this).attr('id').replace('b', '');
		});
		$('input[name="blacklist"]').val(blacklist);

		// Nouvelle liste blanche.
		var whitelist = '';
		$('#group_whitelist a.allowed:not(.by_parent):not(.allowed_child)').each(function()
		{
			whitelist += (whitelist != '' ? ',' : '') + $(this).attr('id').replace('w', '');
		});
		$('input[name="whitelist"]').val(whitelist);
	});
});



/*
 * Section "Groupes", "Fonctionnalités".
 *
 */
jQuery(function($)
{
	if (!$('#section_group_features').length)
	{
		return;
	}

	$('#group_account input').click(function()
	{
		if ($(this).val() == 1)
		{
			$('#group_permissions').hide();
		}
		else
		{
			$('#group_permissions').show();
		}
	});
});



/*
 * Section Utilisateurs / Envoyer un courriel.
 *
 */
jQuery(function($)
{
	if ($('body').attr('id') != 'section_users_sendmail')
	{
		return;
	}

	$('#users_sendmail_users_all').change(function()
	{
		var selector = '#users_sendmail_fields > div:not(:first-child)'
			+ ' *:not(#users_sendmail_users_all)';
		if ($(this).is(':checked'))
		{
			$(selector).prop('disabled', true);
		}
		else
		{
			$(selector).prop('disabled', false);
		}
	});
});



/*
 * Section "Fonctionnalités".
 *
 */
jQuery(function($)
{
	if (!$('#section_features').length)
	{
		return;
	}

	$('fieldset legend + p.field input[type="checkbox"]').click(function()
	{
		var p = $(this).parents('div');
		if ($(this).prop('checked'))
		{
			p.addClass('activated');
		}
		else
		{
			p.removeClass('activated');
		}
	});
});



/*
 * Section "Albums", tri des fichiers et des catégories.
 *
 */
jQuery(function($)
{
	if (!$('#section_album_sort').length
	 && !$('#section_category_sort').length)
	{
		return;
	}

	$('#thumbs_sort')
		.sortable(
		{
			containment: 'main',
			items: 'dl',
			opacity: 0.5
		})
		.submit(function()
		{
			$('input[name="serial"]').val($('#thumbs_sort').sortable('serialize'));
		});
});



/*
 * Section "Albums", nouvelle vignette de catégorie.
 *
 */
jQuery(function($)
{
	if (!$('#thumb_new').length)
	{
		return;
	}

	$('.std_thumbs dt').click(function()
	{
		$('#thumb_id').val($(this).parents('dl').attr('data-id'));
		$('#thumb_new > form:first-child').submit();
	});

	$('.pages a').each(function()
	{
		$(this).attr('href', $(this).attr('href') + '#thumbs');
	});
});



/*
 * Section "Albums", capture d'image pour les vidéos.
 *
 */
jQuery(function($)
{
	if (!$('#thumb_video').length)
	{
		return;
	}

	var canplay = false;
	$('#thumb_video video').on('canplaythrough', function()
	{
		if (canplay)
		{
			return;
		}
		canplay = true;

		var video = $(this)[0];
		var width = video.videoWidth;
		var height = video.videoHeight;
		var duration = Math.round(video.duration);

		if (width < 1)
		{
			return;
		}

		$('#thumb_video_getcapture').click(function()
		{
			var canvas = document.createElement('canvas');
			var maxsize = 1920;
			canvas.width = width;
			canvas.height = height;

			if (width > maxsize || height > maxsize)
			{
				if (width < height)
				{
					canvas.width = Math.round((maxsize / height) * width);
					canvas.height = maxsize;
				}
				else
				{
					canvas.height = Math.round((maxsize / width) * height);
					canvas.width = maxsize;
				}
			}
			canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

			var canvas_data = canvas.toDataURL('image/jpeg');

			$('#thumb_video_capture').attr('src', canvas_data);
			$('input[name="video_width"]').val(width);
			$('input[name="video_height"]').val(height);
			$('input[name="video_duration"]').val(duration);
			$('input[name="video_capture"]').val(
				canvas_data.replace(/^data:image\/jpeg;base64,/, '')
			);

			return false;
		});
	});
});



/*
 * Section "Albums", édition des vignettes.
 *
 */
jQuery(function($)
{
	if (!$('#section_item_thumb').length
	&& !$('#section_album_thumb').length && !$('#section_category_thumb').length)
	{
		return;
	}

	// Rognage.
	$('#thumb_crop img').imgLoad(function()
	{
		var max_width = 800;
		var max_height = 600;
		var ratio;

		var set_image_size = function(m_width)
		{
			var image_width = parseInt($('#thumb_crop img').attr('data-width'));
			var image_height = parseInt($('#thumb_crop img').attr('data-height'));

			var preview_width = $('#thumb_crop img').width();
			var preview_height = $('#thumb_crop img').height();

			var r_width = image_width / m_width;
			var r_height = image_height / max_height;

			if ((image_width > m_width) && (r_width >= r_height))
			{
				image_width = m_width;
				image_height = Math.round(image_height / r_width);
			}
			else if ((image_height > max_height) && (r_height >= r_width))
			{
				image_width = Math.round(image_width / r_height);
				image_height = max_height;
			}

			$('#thumb_crop img').height(image_height).width(image_width).show();

			ratio = parseInt($('#thumb_crop img').attr('data-width'))
				/ $('#thumb_crop img').width();

			return {'w': preview_width / image_width, 'h': preview_height / image_height};
		};

		var resize = function()
		{
			$('#thumb_crop img').hide();
			var scrollbar_width = 20;
			var container_width = Math.round($('#thumb_crop_container').width())
				- scrollbar_width;
			if (container_width > max_width)
			{
				container_width = max_width;
			}
			$('#thumb_crop img').show();

			return set_image_size(container_width);
		}

		resize();

		var crop = $('#thumb_crop img').imgAreaSelect(
		{
			handles: true,
			instance: true,
			minHeight: 50,
			minWidth: 50,
			persistent: true,
			x1: Math.round(parseInt($('#thumb_crop img').attr('data-selection-x')) / ratio),
			y1: Math.round(parseInt($('#thumb_crop img').attr('data-selection-y')) / ratio),
			x2: Math.round((parseInt($('#thumb_crop img').attr('data-selection-x'))
			  + parseInt($('#thumb_crop img').attr('data-selection-w'))) / ratio),
			y2: Math.round((parseInt($('#thumb_crop img').attr('data-selection-y'))
			  + parseInt($('#thumb_crop img').attr('data-selection-h'))) / ratio)
		});

		$(window).resize(function()
		{
			var r = resize();
			var s = crop.getSelection();

			crop.setSelection(s.x1 / r.w, s.y1 / r.h, s.x2 / r.w, s.y2 / r.h);
			crop.update();
		});

		$('#thumb_crop_select_all').click(function()
		{
			crop.setSelection(0, 0, $('#thumb_crop img').width(),
				$('#thumb_crop img').height());
			$('#thumb_crop_free').click();
			return false;
		});

		$('#thumb_crop_free').click(function()
		{
			crop.setOptions(
			{
				aspectRatio: '',
				handles: true
			});
			crop.update();
			return false;
		});

		$('#thumb_crop_square').click(function()
		{
			var height = $('#thumb_crop img').height();
			var width = $('#thumb_crop img').width();
			var x1 = 0;
			var y1 = 0;
			var x2 = 0;
			var y2 = 0;
			if (width > height)
			{
				x1 = Math.round((width - height) / 2);
				x2 = x1 + height;
				y2 = height;
			}
			else
			{
				y1 = Math.round((height - width) / 2);
				y2 = y1 + width;
				x2 = width;
			}
			crop.setSelection(x1, y1, x2, y2);
			crop.setOptions({
				aspectRatio: '1:1',
				handles: 'corners'
			});
			crop.update();
			return false;
		});

		$('#thumb_edit').submit(function()
		{
			var s = crop.getSelection();
			var x = Math.round(s.x1 * ratio);
			var y = Math.round(s.y1 * ratio);
			var w = Math.round(s.width * ratio);
			var h = Math.round(s.height * ratio);
			$('input[name="crop_selection"]').val(
				'{"x":' + x + ',"y":' + y + ',"w":' + w + ',"h":' + h + '}'
			);
		});
	});
	
});
