// Galerie-infographie - gallery.js - gestion des actions de la galerie personnelle
// Original par Pierre-Antoine Delnatte 2007
// JQuery par Jehan 'Killan' Bihin 2008-02-13

$(initDragDrop);
$(initUnFriend);
$(initDelImg);

function initDragDrop()
{
	$("#addFolder").click(function() {
										addFolder();
										return false;
									});
	$("#toggleTools").click(function() {
										toggleTools();
										return false;
									});

	//Actions sur un folder
	$('div.folder').not("#folder_friends").each(function() { initFolderById($(this).attr('id'), false); });

	//Action sur myFavorites & folder_friends
	$('#myFavorites h4 a').click(function () { toggleFolder($(this)); });
	$('#folder_friends h4 a').click(function () { toggleFolder($(this)); });
}

function initFolderById(fid, reload)
{
	if (fid != "folder_0")
	{
		$('#' + fid + " a.editFolderName").unbind('click');
		$('#' + fid + " a.editFolderName").click(function() {
																editFolder($(this));
																return false;
															});

		$('#' + fid + " a.deleteFolder").unbind('click');
		$('#' + fid + " a.deleteFolder").click(function() {
																deleteFolder($(this));
																$('#' + fid + " a.deleteFolder").unbind('click');
																return false;
															});
	}

	$('#' + fid + " h4 a.folder_link").unbind('click');
	$('#' + fid + " h4 a.folder_link").click(function () { toggleFolder($(this)); });

	//Chargement du contenu du folder
	if (reload)
	{
		fldid = fid.substr("folder_".length);
		if (fldid == '') fldid = 0;
		else fldid = parseInt(fldid);

		//Loader
		if (fid != "folder_0") $('#' + fid + ' h4 a img:last').attr("src", "./styles/images/loader-2-1.gif");
		else $('#' + fid + ' h4 a img:last').attr("src", "./styles/images/loader-2-1g.gif");

		$.ajax({
				type: "POST",
				url: "ajax_gallery.php",
				data: 'action=loadFolderContent&userId=' + $.query.get('id') + '&folderId=' + fldid,
				cache: false,
				success: function(data) {
											if (fid != "folder_0") $('#' + fid + ' h4 a img:last').attr("src", "./styles/icons/pictures.png");
											else $('#' + fid + ' h4 a img:last').attr("src", "./styles/icons/images.png");
											$('#' + fid + ' div.imageContent div.thumbBox, #' + fid + ' div.imageContent br').not($('div.loading br')).remove();

											//Remplir
											if (data.trim() != tab_lang[39])
											{
												$('#' + fid + ' div.imageContent').append(data);
												$('#' + fid + ' div.imageContent div.loading').hide();

												//Indiquer le nombre d'images
												$('#' + fid + ' h4 a.folder_link span:last').text($('#' + fid + ' div.imageContent').children('.thumbBox.movable').length);
											}
											else
											{
												$('#' + fid + ' div.imageContent div.loading').show();
											}

											prepareFolder(fid)
										}
				});
	}
	else
	{
		$('#' + fid + ' div.imageContent div.thumbBox.droper').remove();
		prepareFolder(fid);
	}
}

function initDragImg(di)
{
	di.draggable({helper: 'clone'}); //, cursorAt: {top:0, left:0}
	di.css("z-index", "10000");
}

//Folder
function addFolder()
{
	folderName = prompt(tab_lang[40], tab_lang[41]);

	if ( folderName == '' || folderName == null ) return false;

	$.ajax({
			type: "POST",
			url: "ajax_gallery.php",
			data: 'action=addFolder&folderName=' + folderName,
			cache: false,
			success: function(data) {
							if ( data < 1 ) alert(tab_lang[42] + requester.responseText);
							else
							{
								newFolderCode = '<div class="folder" id="folder_' + data + '" title="' + folderName + '"><div id="folder_' + data + '_toolbar" class="folder_toolbar"><a href="prompter.php?action=editFolder&amp;folderId=' + data + '" id="editFolderName_' + data + '" class="editFolderName" title="' + tab_lang[43] + '"><img alt="" src="./styles/icons/images_edit.png" /></a> <a href="prompter.php?action=deleteFolder&amp;folderId=' + data + '" id="deleteFolder_' + data + '" class="deleteFolder" title="' + tab_lang[44] + '"><img alt="" src="./styles/icons/images_delete.png" /></a></div><h4 class="folder_title"><a id="link_' + data + '" class="folder_link" title="' + tab_lang[45] + ' ' + folderName + '"><img class="folder_arrow" src="./styles/icons/bullet_arrow_down.png" alt="' + tab_lang[45] + ' ' + folderName + '" /> <img alt="" src="./styles/icons/images.png" /> <span id="fcname_' + data + '">' + folderName + '</span> (<span id="folder_content_' + data + '">0</span>)</a></h4><div class="imageContent" id="imageContent_' + data + '"><div class="loading">' + tab_lang[46] + '</div></div><span class="clearer"></span></div>';
								$('#folder_0').parent().append(newFolderCode);

								ordoneFolder(data);
							}
						}
			});
}

function editFolder(obj)
{
	folderId = obj.attr('id').substr("editFolderName_".length);

	oldFolderName = $("#folder_" + folderId).attr("title");
	folderName = prompt(tab_lang[47], oldFolderName);

	if ( folderName == '' || folderName == null || folderName == oldFolderName ) return false;

	$("#folder_" + folderId).slideUp('fast');

	$.ajax({
			type: "POST",
			url: "ajax_gallery.php",
			data: 'action=editFolder&folderName=' + folderName + '&folderId=' + folderId,
			cache: false,
			success: function(data) {
							if( data != 1 ) alert(tab_lang[48]);
							else
							{
								$("#fcname_" + folderId).html(folderName);
								$("#link_" + folderId).attr('title', tab_lang[45] + folderName);
								$("#folder_" + folderId).attr('title', folderName);

								ordoneFolder(folderId);

								$("#folder_" + folderId).hide();
								$("#folder_" + folderId).slideDown('fast');
							}
						}
			});
}

function deleteFolder(obj)
{
	if (confirm(tab_lang[49]) == false) return false;

	folderId = obj.attr('id').substr("deleteFolder_".length);

	$.ajax({
			type: "POST",
			url: "ajax_gallery.php",
			data: 'action=deleteFolder&folderId=' + folderId,
			cache: false,
			success: function(data) {
							if( data != 1 ) alert(tab_lang[50]);
							else
							{
								$('#folder_' + folderId).slideUp('fast', function() {
																						$(this).remove();
																						initFolderById("folder_0", true);
																					});
							}
						}
			});
}

function toggleFolder(obj)
{
	if (obj.parent().parent().children('div.imageContent').css('display') == 'block') obj.children('img.folder_arrow').attr('src', './styles/icons/bullet_arrow_right.png');
	else obj.children('img.folder_arrow').attr('src', './styles/icons/bullet_arrow_down.png');
	obj.parent().parent().children('div.imageContent').slideToggle('fast');
}

function moveThumb(rep, thumb, droper)
{
	//Supprimer l'image
	thumb.hide();

	//Infos, parentée, structure
	vignette = $('#'+thumb.attr('id')); //Me semble etre = à thumb
	img_id = thumb.attr('id').substr(6);
	oldFolder = vignette.parent().parent();
	reinsert = '<div id="' + thumb.attr('id') + '" rev="*" class="thumbBox movable">' + vignette.html() + '</div>';

	//Loader
	if (rep.attr('id') == "folder_0") $('#' + rep.attr('id') + ' h4 a img:last').attr("src", "./styles/images/loader-2-1.gif");
	else $('#' + rep.attr('id') + ' h4 a img:last').attr("src", "./styles/images/loader-2-1g.gif");
	if (oldFolder.attr('id') == "folder_0") $('#' + oldFolder.attr('id') + ' h4 a img:last').attr("src", "./styles/images/loader-2-1.gif");
	else $('#' + oldFolder.attr('id') + ' h4 a img:last').attr("src", "./styles/images/loader-2-1g.gif");

	//Action d'échange de place + Ordo
	$.ajax({
				type: "POST",
				url: "ajax_gallery.php",
				data: 'action=changeFolder&folder=' + rep.attr('id').substr(7) + '&img=' + img_id,
				cache: false,
				success: function(data) {
								if ( data != "1" )
								{
									alert("L'élément n'a pas pu être déplacé !");
									thumb.show();
									//location.reload(true);
								}
								else
								{
									// on réinsere la vignette dans son nouveau dossier et on la (re)rends draggable
									if (rep.attr('id') == "folder_0") target = $("#imageContent_0");
									else target = $("#imageContent_" + rep.attr('id').substr(7));
									if ( target.children("div.loading") ) target.children("div.loading").hide();

									lastdroper = $('#' + rep.attr('id') + ' div.thumbBox.droper:last');
									if (lastdroper.attr('rev') != droper.attr("rev")) lastdroper.remove();
									droper.replaceWith(reinsert.replace('*', droper.attr("rev")));

									$("#folder_content_" + rep.attr('id').substr(7)).text( parseInt($("#folder_content_" + rep.attr('id').substr(7)).text(), 10) + 1 );
									$("#folder_content_" + oldFolder.attr('id').substr(7)).text( parseInt($("#folder_content_" + oldFolder.attr('id').substr(7)).text(), 10) - 1 );

									thumb.remove();
									if (oldFolder.children('div.imageContent').children('.thumbBox.movable').length == 0 ) //image en float height() == 0 ne sert à rien ici
									{
										if ($('#' + oldFolder.attr('id') + " div.imageContent div.loading").length <= 0) oldFolder.children('div.imageContent').append('<div class="loading" style="display: none;">' + tab_lang[46] + '</div>');
										oldFolder.children("div.imageContent").children("div.loading").slideDown('fast');
									}

									//Ré-arrangement fait par cette requete AJAX
									//Créer une sérialisation des id img via les rev
									var lst = '';
									var thumbs = $('#' + droper.attr('rel') + ' div.thumbBox.movable');

									for (i = 0; i < thumbs.length; i++)
									{
										if (lst != '') lst += ',';
										lst += $(thumbs[i]).attr('id').substr(6) + '=' + $(thumbs[i]).attr('rev');
									}
									$.ajax({
												type: "POST",
												url: "ajax_gallery.php",
												data: 'action=ordoFolder&folder=' + rep.attr('id').substr(7) + '&ordoLst=' + lst,
												cache: false,
												success: function(data) {
																			initFolderById(rep.attr('id'), true);
																			if (rep.attr('id') != "folder_0") $('#' + rep.attr('id') + ' h4 a img:last').attr("src", "./styles/icons/pictures.png");
																			else $('#' + rep.attr('id') + ' h4 a img:last').attr("src", "./styles/icons/images.png");
																		}
											});

									//Recharger les images avec un ré-arrangement de base
									$.ajax({
												type: "POST",
												url: "ajax_gallery.php",
												data: 'action=ordoFolder&folder=' + rep.attr('id').substr(7),
												cache: false,
												success: function(data) {
																			initFolderById(oldFolder.attr('id'), true);
																			if (oldFolder.attr('id') != "folder_0") $('#' + oldFolder.attr('id') + ' h4 a img:last').attr("src", "./styles/icons/pictures.png");
																			else $('#' + oldFolder.attr('id') + ' h4 a img:last').attr("src", "./styles/icons/images.png");
																		}
											});
								}
							}
			});
}

function compare(nom1, nom2)
{
	return new Array(nom1, nom2).sort();
}

function ordoneFolder(id)
{
	//Liste des comparrables
	var lstflds = $("div.folder").not('div#folder_' + id + ', div#folder_0, div.folder.favs');
	var nom = $('span#fcname_' + id).text().toLowerCase();
	var cont = '<div id="folder_' + id + '" class="folder" title="' + $('div#folder_' + id).attr('title') + '">' + $('div#folder_' + id).html(); + '</div>'

	//Comparaison des noms
	for (i = 0; i < lstflds.length; i++)
	{
		tfid = $(lstflds[i]).attr('id').substr("folder_".length);

		if (compare(nom, $('span#fcname_' + tfid).text().toLowerCase())[0] == nom)
		{
			//> On doit se mettre avant lui
			$('div#folder_' + id).remove();				//On le supprime
			$(lstflds[i]).before(cont);					//On le place
			initFolderById('folder_' + id, false);		//Actions
			return;
		}
	}

	//> On se met à la fin
	$('div#folder_' + id).remove();				//On le supprime
	$('#folder_0').parent().append(cont);		//On le place
	initFolderById('folder_' + id, false);		//Actions
	return;
}

function prepareFolder(fid)
{
	if ($('#' + fid + ' div.folder_toolbar').length > 0)	//Si pas moveable, pas de prépa
	{
		//Ajouter des drop entre les images, attribuer des id à chaque objet (attribut perso)
		var id = fid.substr('folder_'.length);
		var droper = '<div id="droper_' + id + '" class="thumbBox droper">&nbsp;</div>';

		var thumbs = $('#' + fid + ' div.thumbBox.movable');

		//Initialisation des drag
		thumbs.each( function() { initDragImg($(this)); });

		//Intercaller un droper
		$('#' + fid + ' div.imageContent').prepend(droper);	//Celui de départ
		vligne = 0;
		for (i = 0; i < thumbs.length; i++)
		{
			vligne++;
			if (vligne >= 8 && i < thumbs.length - 1)
			{
				vligne = 0;
				$(thumbs[i]).after('<br />' + droper);
			}
			$(thumbs[i]).after(droper);
		}

		//Donner un ID perso a cette nouvelle bande de potes
		var friends = $('#' + fid + ' div.thumbBox');

		for (i = 0; i < friends.length; i++)
		{
			$(friends[i]).attr("rev", i);
			$(friends[i]).attr("rel", fid);
		}

		//Largeur du dernier droper
		posp = $('#' + fid + ' div.thumbBox.droper:last').parent().offset();
		posd = $('#' + fid + ' div.thumbBox.droper:last').offset();
		lc = posd.left - posp.left;
		$('#' + fid + ' div.thumbBox.droper:last').css('width', $('#' + fid + ' div.thumbBox.droper:last').parent().width() - lc - 15);

		//Initialisation des droper
		$('#' + fid + ' div.thumbBox.droper').droppable({
															accept: function(draggable) { return $(draggable).is('div.thumbBox.movable'); },
															drop: function(ev, ui) { moveThumb($('#' + fid), $(ui.draggable.element), $(this)); },
															tolerance: 'pointer',
															hoverClass: 'hoverclass'
														});

		$('#' + fid + ' div.thumbBox.movable').droppable({
															accept: function(draggable) { return $(draggable).is('div.thumbBox.movable'); },
															drop: function(ev, ui)
																{
																	//De quelle coté on est ?
																	if (ev.pageX - $(this).offset().left < $(this).width() / 2) moveThumb($('#' + fid), $(ui.draggable.element), $(this).prev('div.thumbBox.droper'));
																	else moveThumb($('#' + fid), $(ui.draggable.element), $(this).next('div.thumbBox.droper'));
																},
															tolerance: 'pointer',
															hoverClass: 'hover'
														});
		//Si loading est là
		if ($('#' + fid + ' div.loading').length > 0) $('#' + fid + ' div.loading').css('position', 'absolute');
	}
}

function initUnFriend()
{
	$("a.unfriend").click(function() {
											if (!confirm($(this).children("img").attr('title')))
											{
												return false;
											}
										});
}

function initDelImg()
{
  if ($('a.delImg').length > 0) $('a.delImg').click(function() {
      if (confirm(tab_lang[51]))
      {
        url = $(this).attr('href').split('&id=')[1];
        location.href = "prompter_executer.php?action=deleteImage&imageId=" + url + "&user_id=" + $("#user_id").text();
      }
      return false;
    });
}