var isChatActive = false,
	checkMessage = false,
	behaviorTag = [],
	optionsTag;

$(document).ready(function() {
	//Afficher toutes les notifications non lues avec restriction
	showNotReadNotifications();
	//Ignorer toutes les notifications
	ignoreAllNotifications();
	//Ignorer une notification en particulier
	ignoreOneNotification();
	//Afficher tous les messages non lus dans la discussion instantanée
	showMessagesNotRead();
	//Ignorer tous les messages de la discussion instantanée
	ignoreAllMessages();
	//Ignorer un message dans la discussion instantanée
	ignoreOneMessage();
	// Gère les tooltip v2
	tooltipManager($("body"), true, ".tooltipNoIcon");
	tooltipManager($("body"), false, ".tooltipIcon");

	showNotificationsManager();
	updateNotificationsManager();

	// ---------------------------------------------------------------------------
	// Gestion du layer d'ajout de contacts

	// Appel du layer d'ajout de contact
	$(document).on("click", "#profileContactAdd", function(e) {
		e.preventDefault();

		$.ajax({
			url: $(this).attr("href") + "?new=1",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("#contactActions").css({
					position: "relative",
					"z-index": 20,
				});
				$("#result").remove();
				$("#contactActions").append(
					$("<div>")
						.attr({
							id: "result",
						})
						.addClass("modalAddContact")
						.html(
							$(response)
								.find("#profile_search")
								.html()
						)
						.prepend(
							$("<div>")
								.attr({
									id: "closeResult",
								})
								.append(
									$("<span>")
										.addClass("icons")
										.text("X"),
									$("<div>").addClass("arrowTop icons")
								)
						)
				);
				$("#tabsSearch li:first").addClass("active_section");
			},
		});
	});

	// Switch de la méthode pour trouver un contact
	$(document).on("click", "#contactActions #tabsSearch li a", function(e) {
		e.preventDefault();

		var href = $(this).attr("href") + "-getpagecontent",
			callUrl = function() {
				return href;
			};

		$.ajax({
			url: $(this).attr("href"),
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				var url = callUrl();

				$("#contactActions #result")
					.html(
						$(response)
							.find("#profile_search")
							.html()
					)
					.prepend(
						$("<div>")
							.attr({
								id: "closeResult",
							})
							.append(
								$("<span>")
									.addClass("icons")
									.text("X"),
								$("<div>").addClass("arrowTop icons")
							)
					);

				if (url.indexOf("suggest") > 0) {
					$("#tabsSearch li:first").addClass("active_section");
				} else {
					$("#tabsSearch li")
						.eq(1)
						.addClass("active_section");
					$("#tabsSearch ul", "#contactActions").css({
						"border-bottom": "none",
						"border-top": "1px solid #ccc",
						"margin-top": "-1px",
					});
				}
			},
		});
	});

	// Fermeture du layer d'ajout de contact
	$(document).on("click", "#closeResult, #tabSuggest .linkClose", function(e) {
		$("div#result")
			.parent()
			.parent()
			.removeAttr("style");
		$("div#result").remove();
	});

	$(document).on("click", "div.result a.sendRequest", function(e) {
		e.preventDefault();
		var element = $(this);

		if (element.attr("href") != "javascript:void(0);") {
			$.ajax({
				url: element.attr("href"),
				type: "get",
				dataType: "html",
				success: function(response, textStatus, xhr) {
					element
						.attr({
							href: "javascript:void(0);",
						})
						.text("En attente de validation");
				},
			});
		}
	});

	// Recherche de contacts
	$(document).on("submit", "#profileFormSearchId", function(e) {
		e.preventDefault();
		$(".result")
			.html("")
			.append(
				'<div id="loadingAjax"><img src="/common_images/community/ajax-loader.gif"></div><div id="infoSearch">Recherche en cours...</div>'
			);
		$("#loadingAjax").css({
			position: "absolute",
			top: $("#result").height() / 2,
			left: $("#result").width() / 2,
		});

		$("#infoSearch").css({
			position: "absolute",
			top: $("#result").height() / 2 + 16,
			left: $("#result").width() / 2 - 60,
		});

		var data = $(this).serialize();

		$.ajax({
			url: $(this).attr("action"),
			type: "post",
			data: $(this).serialize(),
			dataType: "html",
			success: function(response, textStatus, xhr) {
				if (
					$(response)
						.find("div.result")
						.html() == ""
				) {
					$("div.result").html("Aucun résultat");
				} else {
					$("div.result").html(
						$(response)
							.find("div.result")
							.html()
					);
				}
				//$("div#tabSearch").mCustomScrollbar();
			},
		});
	});

	// ---------------------------------------------------------------------------
	// Gestion du partage d'éléments
	$(document).on("click", "a.communityShareLink", function(e) {
		e.preventDefault();

		var self = $(this),
			elementId = self.attr("data-elementId"),
			elementType = self.attr("data-elementType"),
			elementUrl = self.attr("href"),
			elementTitle = self.attr("data-elementTitle"),
			content = "";

		$.ajax({
			url: "/action-CommunityAction-getSharePopup",
			type: "post",
			dataType: "json",
			data: {
				elementId: elementId,
				elementType: elementType,
				elementUrl: elementUrl,
				elementTitle: elementTitle,
			},
			success: function(response, textStatus, xhr) {
				if (response.result) {
					modalConfirmManager(
						e,
						response.content.title,
						response.content.msg,
						saveSharedElement,
						[self, elementType, elementId, elementUrl, elementTitle],
						response.content.validText,
						"od_share"
					);
				}
			},
		});
	});

	// ---------------------------------------------------------------------------
	// Gestion mur d'activités

	if ($(".wWall").length > 0) {
		activityWallManager();
	}

	// ---------------------------------------------------------------------------
	// Page de gestion des contacts
	$("#community_relationship .person").each(function() {
		$(this).on("click", function(e) {
			e.preventDefault();
			if ($(this).hasClass("active")) {
				$(this)
					.removeClass("active")
					.find(".relationshipCheckbox")
					.removeAttr("checked");
			} else {
				$(this)
					.addClass("active")
					.find(".relationshipCheckbox")
					.attr("checked", "checked");
			}
		});
		$("a", this).on("click", function(e) {
			e.stopPropagation();

			if ($(this).hasClass("specialLink")) {
				window.location = $(this)
					.closest(".person")
					.find(".author_profile a:first")
					.attr("href");
			}
		});
	});

	// ---------------------------------------------------------------------------
	// GROUPES

	// Page de groupe
	$("#menutab li:first").addClass("active");
	$("#menutab li").on("click", function() {
		if ($(this).hasClass("active")) {
		} else {
			$(this)
				.addClass("active")
				.siblings()
				.removeClass("active");
		}
	});
	$("#menutab li:first").on("click", function() {
		$("#membersList").hide();
		$("#previewGroup").show();
	});
	$("#menutab li:last").on("click", function() {
		$("#previewGroup").hide();
		$("#membersList").show();
		$(".personImg").each(function() {
			$(this).height($(this).width());
		});
	});

	// Recherche un ami grace à l'input searchFriend
	$(document).on("keyup", "#addMember #searchFriend", function(e) {
		var searchVal = $(this).val();

		if (searchVal != "") {
			$("#addMember .person").each(function() {
				if (
					$(this)
						.attr("rel")
						.toLowerCase()
						.indexOf(searchVal.toLowerCase()) > -1
				) {
					$(this).show();
				} else {
					$(this).hide();
				}
			});
		} else {
			$("#addMember .person").show();
		}
	});

	// Ouverture du layer d'ajout de membres
	$(document).on("click", "#addMember a.invitation", function(e) {
		e.preventDefault();
		var link = $(this).attr("href") + "?new=1";
		$.ajax({
			url: link + "&lazyLoading=true",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("div#addMember").css({ "z-index": "10" });
				$("div#addMember").append(
					'<div id="result" class="relative"><div id="tabsSearch"><ul><li class="left active_section">Vos contacts</li><li>&nbsp;</li></ul></div><div id="tabSuggest" /></div>'
				);
				results = $(response)
					.find("#resultSearchMembers")
					.html();
				if (results) {
					$("div#result #tabSuggest").html(results);
					if ("1" == $("#getMoreResults").val()) {
						$.ajax({
							url: link + "&moreResults=true",
							type: "get",
							dataType: "html",
							success: function(response, textStatus, xhr) {
								results = $(response).find("#resultSearchMembers .person");
								$("div#result #tabSuggest .person")
									.last()
									.after(results);
								$("#nbPerson").text(
									"0 / " + $(".person", "#addMember").length + " contacts sélectionnés"
								);
							},
						});
					}
				} else {
					$("div#result #tabSuggest").html(
						$(response)
							.find("#group_invite")
							.html()
					);
				}
				$("div#result").prepend(
					'<div id="closeResult" class="closeBox"><span class="icons">X</span></div><div class="arrowTop icons"></div>'
				);
				$(".person", "div#tabSuggest").wrapAll('<div class="specialOverflow" />');
				$("#nbPerson").text("0 / " + $(".person", "#addMember").length + " contacts sélectionnés");
			},
		});
	});

	// Sélection ou non d'un contact pour devenir membre du groupe
	$(document).on("click", "#addMember .person", function(e) {
		e.preventDefault();

		var idMember = $(this)
				.attr("id")
				.split("id")[1],
			nameMember = $(this)
				.find(".personName")
				.text();

		if (!$(this).data("active") || !$(this).data("active")) {
			$(this).addClass("active");
			$(this).data("active", true);
			$('input[type="checkbox"]', this).attr("checked", "checked");
		} else {
			var idMember = $(this)
					.attr("id")
					.split("id")[1],
				id = -1,
				i = null;

			$(this).removeClass("active");
			$(this).data("active", false);
			$('input[type="checkbox"]', this).removeAttr("checked");
		}

		$("#nbPerson").text(
			$(".person.active", "#addMember").length +
				" / " +
				$(".person", "#addMember").length +
				" contacts sélectionnés"
		);
	});

	// Ajout de membres
	$(document).on("submit", "#addMember #formAddMember", function(e) {
		e.preventDefault();

		$.ajax({
			url: $(this).attr("action"),
			type: "post",
			data: $(this).serialize(),
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("#tabSuggest")
					.find(".confirmInvite")
					.remove();
				$("#tabSuggest .specialOverflow").prepend(
					'<span class="confirmInvite">Les invitations ont bien été envoyées.</span>'
				);
				$(".person.active", "#tabSuggest").remove();

				$(".text-tags")
					.children()
					.remove();
			},
		});
	});

	// Fermeture du layer
	$(document).on("click", "#addMember #cancelInvite", function(e) {
		e.preventDefault();
		$("div#result").remove();
		$("div#addMember").css({ "z-index": "1" });
	});

	// Page de creation/modification de groupe
	var pictureElement = $(".picturePreview");

	if (typeof $("#picture").preimage !== "undefined") {
		$("#picture").preimage();
	}

	$("#pictureDelete").on("click", function() {
		$("img", pictureElement).attr("src", "/common_images/community/default_user.png");
	});

	// Administration des groupes
	$(".publicationElement").each(function() {
		$(".author", this).text($(".personName:first", this).text());
	});
	if ($("span", "#adminMenu li a").text().length == 0) {
		$("span", "#adminMenu li a").hide();
	}

	$(".groupItem.owner, .person.owner").each(function() {
		$(this).prepend(
			$("<div>")
				.addClass("pictOwner icons")
				.append(
					$("<span>")
						.addClass("arrowContent")
						.text("Propriétaire du groupe")
						.append($("<span>").addClass("arrowBlack icons"))
				)
		);
	});

	$(".groupItem.admin, .person.admin").each(function() {
		$(this).prepend(
			$("<div>")
				.addClass("pictAdmin icons")
				.append(
					$("<span>")
						.addClass("arrowContent")
						.text("Administrateur du groupe")
						.append($("<span>").addClass("arrowBlack icons"))
				)
		);
	});

	// ---------------------------------------------------------------------------
	// Centre de messagerie
	$("a", ".rowMessage .resumeAction").on({
		mouseenter: function() {
			$(this).append("<div class='arrow' />");
		},
		mouseleave: function() {
			$(".arrow", this).remove();
		},
	});

	// Chargement de la discussion dans la zone droite au clic sur le résumé
	$(document).on("click", "div.rowMessage .resume", function(e) {
		currentThreadIndex = $(".detailAction").index($("a.detailAction", this));

		e.preventDefault();

		$("#showMessage")
			.html("")
			.append('<div id="loadingAjax"><img src="/common_images/community/ajax-loader.gif"/></div>');
		$("#loadingAjax").css({
			position: "absolute",
			top: $("#showMessage").height() / 2,
			left: $("#showMessage").width() / 2,
		});
		$.ajax({
			url: $("a.detailAction", this).attr("href") + "?getpagecontent&isajax=true",
			type: "get",
			datatype: "html",
			success: function(response, textStatus, xhr) {
				$("#showMessage")
					.html("")
					.append(
						$(response)
							.find("#currentThread")
							.html()
					);
				if ($("#contextAjaxMessaging").length == 0) {
					$("#showMessage > *").wrapAll('<div id="contextAjaxMessaging"/>');
				}

				$("#showMessage #listMessages").scrollTop(1000000);
				$("#loadingAjax").remove();
			},
		});
		$("#showMessage").show();
		$(this)
			.closest(".rowMessage")
			.addClass("selectedTalk")
			.siblings()
			.removeClass("selectedTalk");
	});

	// Auto Chargement d'une conversation au démarrage
	if (window.location.hash != "" && window.location.hash.split("-")[0] == "#detail") {
		var idToLoad = window.location.hash.split("-")[1];

		$("div.rowMessage .resume").each(function() {
			var url = $("a.detailAction", this).attr("href"),
				param = url.split("-");

			if (param[param.length - 1] == idToLoad) {
				$(this).trigger("click");
			}
		});
	}

	// Postage d'un message dans le centre de messagerie
	$(document).on("submit", '#contextAjaxMessaging form[name="response_form"]', function(e) {
		e.preventDefault();

		$("#showMessage").append('<div id="loadingAjax"><img src="/common_images/community/ajax-loader.gif"/></div>');
		$("#loadingAjax").css({
			position: "absolute",
			top: $("#showMessage").height() / 2,
			left: $("#showMessage").width() / 2,
		});
		$("#contextAjaxMessaging #message_body").attr("readonly", "readonly");

		if (isAjaxLocked()) {
			return false;
		}
		initAjaxLock();
		$.ajax({
			url: $(this).attr("action"),
			type: "post",
			data: $(this).serialize(),
			dataType: "html",
			success: function(response, textStatus, xhr) {
				var tmpBody = $("#message_body").val(),
					newbody;

				if (tmpBody.length > 20) {
					var str1 = tmpBody.substr(0, 10),
						str2 = tmpBody.substr(tmpBody.length - 10, tmpBody.length);

					newbody = str1 + "..." + str2;
				} else {
					newbody = tmpBody;
				}
				$("#showMessage #contextAjaxMessaging")
					.html("")
					.append(
						$(response)
							.find("#currentThread")
							.html()
					);
				$("#showMessage #contextAjaxMessaging #listMessages").scrollTop(1000000);
				$("a.detailAction")
					.eq(currentThreadIndex)
					.text(newbody);
				$("#loadingAjax").remove();
				$("#message_body").removeAttr("readonly");
				$("#message_body").val("");
				$("#message_body").focus();
				resetAjaxLock();
			},
		});
	});

	// Appel du layer de nouvelle discussion
	$("#addTalk a").click(function(e) {
		e.preventDefault();
		$.ajax({
			url: $(this).attr("href") + "?getpagecontent",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("div#add").css({ position: "relative", "z-index": "20" });
				$("div#formTalk").remove();
				$("div#addTalk").append('<div id="formTalk" />');
				$("div#formTalk").html(response);
				$(".backlink").remove();
				$("h1.write").remove();
				$(".onglets").remove();
				$("div#formTalk").prepend(
					'<div id="closeResult"><span class="icons">X</span></div><div class="arrowTop icons"></div>'
				);
			},
		});
	});

	//Post du formulaire nouvelle discussion
	$(document).on("submit", "#addTalk #community_message", function(e) {
		e.preventDefault();
		if (isAjaxLocked()) {
			return false;
		}
		initAjaxLock();
		$.ajax({
			url: $(this).attr("action"),
			type: "post",
			data: $(this).serialize(),
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("#formTalk").remove();
				if ($("#threadsForm").length > 0) {
					$(".community_messaging list")
						.html("")
						.html(
							$(response)
								.find(".community_messaging list")
								.html()
						);
					setTimeout(function() {
						$("div.resume a.detailAction")
							.eq(1)
							.click();
					}, 2000);
					$(".tab").html(
						$(response)
							.find(".tab")
							.html()
					);
				}
				resetAjaxLock();
			},
		});
	});

	// Fermeture de la fenêtre de création de discussion
	$(document).on("click", "#closeResult", function(e) {
		$("div#formTalk").remove();
	});

	$(document).on("click", "#closeResult", function(e) {
		$("div#formTalk").remove();
	});

	// Submit sur la touche Entree
	$(document).on("keypress", "#contextAjaxMessaging #message_body", function(e) {
		if (e.keyCode == 13 && e.shiftKey == false && e.ctrlKey == false && e.altKey == false) {
			e.preventDefault();
			$('form[name="response_form"]').submit();
		}
	});

	// ---------------------------------------------------------------------------
	// Mini-notifications
	var isMessagesOpen = false,
		isNotificationsOpen = false,
		isContactsOpen = false;

	$("#messagesNew").on("click", function() {
		if (isMessagesOpen) {
			$(this)
				.siblings("#messagesResume")
				.hide()
				.find(".arrow")
				.remove();
			isMessagesOpen = false;
		} else {
			$(this)
				.siblings("#messagesResume")
				.show()
				.append('<div class="arrow" />');
			$("#notificationResume")
				.hide()
				.find(".arrow")
				.remove();
			$("#contactsResume")
				.hide()
				.find(".arrow")
				.remove();
			isMessagesOpen = true;
			isNotificationsOpen = false;
			isContactsOpen = false;
		}
	});
	$("#notificationsNew").on("click", function() {
		if (isNotificationsOpen) {
			$(this)
				.siblings("#notificationResume")
				.hide()
				.find(".arrow")
				.remove();
			isNotificationsOpen = false;
		} else {
			$(this)
				.siblings("#notificationResume")
				.show()
				.append('<div class="arrow" />');
			$("#messagesResume")
				.hide()
				.find(".arrow")
				.remove();
			$("#contactsResume")
				.hide()
				.find(".arrow")
				.remove();
			isNotificationsOpen = true;
			isMessagesOpen = false;
			isContactsOpen = false;
		}
	});
	$("#contactsNew").on("click", function() {
		if (isContactsOpen) {
			$(this)
				.siblings("#contactsResume")
				.hide()
				.find(".arrow")
				.remove();
			isContactsOpen = false;
		} else {
			$(this)
				.siblings("#contactsResume")
				.show()
				.append('<div class="arrow" />');
			$("#notificationResume")
				.hide()
				.find(".arrow")
				.remove();
			$("#messagesResume")
				.hide()
				.find(".arrow")
				.remove();
			isContactsOpen = true;
			isNotificationsOpen = false;
			isMessagesOpen = false;
		}
	});
	$("body").on("click", ".wallNotification", function(e) {
		if (
			$(e.target.parentElement).hasClass("ignoreOne") ||
			$(e.target.parentElement).hasClass("ignoreOneMessage") ||
			$(e.target.parentElement).hasClass("ignoreOneNotification")
		) {
			return;
		}
		if ($(this).hasClass("contactResumes")) {
			window.location = "account-relationship-management.html";
		} else {
			window.location = $("a.linkMessage", this).attr("href");
		}
		return true;
	});

	// Gère le widget de recherche communautaire
	if ($("#searchCommunityResults").length > 0) {
		widgetSearchCommunityManager();
	}
});

/**
 * Initialisation du comportement du mur d'activité
 */
function activityWallManager() {
	var isVisibilityOpen = false;

	if (isInitTag()) {
		// Gestion de la mention de personnes dans un message
		initTagData();

		// Application aux champs textarea du mur
		$("textarea.comment").textcomplete(behaviorTag, optionsTag);
	}

	// Pendant le submit d'un formulaire, les boutons sont inactifs
	$(".profile_wall form").submit(function() {
		$("input[type=submit]")
			.attr("disabled", true)
			.addClass("disabled");
		$("textarea").addClass("disabled");

		var submitedText = $(this)
				.find("textarea")
				.val(),
			hiddenElements = $(this).find("input:hidden");

		for (var i = hiddenElements.length - 1; i >= 0; i--) {
			if ($(hiddenElements[i]).attr("class") == "tagName") {
				if (submitedText.indexOf("@" + $(hiddenElements[i]).attr("tag")) === -1) {
					$(hiddenElements[i]).remove();
				}
			}
		}
		return true;
	});

	// Teste si l'utilisateur a bien un avatar sinon le remplace par celui par défaut
	if ($(".person .personImg", ".form_wall").length == 0) {
		$(".person", ".form_wall").append('<img src="/common_images/community/default_user.png" alt="" width="40" />');
	}

	if ($(".visibilityPeople > .multi_radio").length < 2) {
		$(".visibilityPeople").remove();
	} else {
		$(".multi_radio", ".form_wall .visibilityPeople").each(function() {
			$("label", this)
				.unbind("click")
				.on("click", function() {
					if (isVisibilityOpen) {
						$(this)
							.closest(".visibilityPeople")
							.height(20);
						$(".multi_radio:first", ".form_wall .visibilityPeople").css({
							"margin-top": -($(".multi_radio").index(this) * 20) + "px",
						});

						isVisibilityOpen = false;
					} else {
						$(this)
							.closest(".visibilityPeople")
							.height($(".multi_radio", $(this).closest(".visibilityPeople")).length * 20);
						$(".multi_radio:first", ".form_wall .visibilityPeople").css({
							"margin-top": 0,
						});

						isVisibilityOpen = true;
					}
				});
		});
	}

	// Agrandissement de la zone de saisie lorsqu'on l'on souhaite publier
	$(".form_wall textarea")
		.unbind("click")
		.on("click", function() {
			$(this).height(130);
		});

	$('.form_wall input[type="submit"]')
		.unbind("click")
		.on("click", function(e) {
			var serializeData = $("#newStatusForm").serialize(),
				tmp = serializeData.split("&"),
				data = {},
				emptyMessage = true,
				emptyPicture = true,
				emptyDoc = true,
				emptyLink = true;
			emptyCode = true;

			$.each(tmp, function(index, value) {
				var tmpData = value.split("=");

				data[tmpData[0]] = tmpData[1];
			});

			// Vérification des fichiers
			$.each($("#newStatusForm").find(".newMedia"), function() {
				if ($(this).hasClass("wall_picture") && $(this).prop("files").length > 0) {
					emptyPicture = false;
				} else if ($(this).prop("files").length > 0) {
					emptyDoc = false;
				}
			});

			$.each(data, function(index, value) {
				if (index == "wall_message" && value) {
					emptyMessage = false;
				}

				if (index.indexOf("codes") >= 0 && value) {
					emptyCode = false;
				}

				if (index.indexOf("links") >= 0 && value) {
					emptyLink = false;
				}
			});

			if ($("#errorStatus").length > 0) {
				$("#errorStatus").hide();
			}

			if (emptyMessage && emptyPicture && emptyDoc && emptyCode && emptyLink) {
				if ($("#errorStatus").length > 0) {
					$("#errorStatus").show();
				} else {
					$("#newStatusForm").append(
						$("<span>")
							.attr("id", "errorStatus")
							.text("Vous devez renseigner un message ou ajouter un élément pour publier un statut")
							.addClass("error")
							.show()
					);
				}

				return false;
			}

			$(".form_wall textarea").height(20);
			return true;
		});

	$(".trashImage")
		.hide()
		.click(function() {
			$(this)
				.hide()
				.parent()
				.find(".wall_picture")
				.val("");
		});

	// S'il n'y a pas d'images associées au message, on supprime la zone d'images
	$(".wall_picture").on("change", function() {
		$(this)
			.parent()
			.next(".divwall_picture")
			.css({
				display: "block",
			});
		$(this)
			.parent()
			.find(".trashImage")
			.show();
	});

	$("#addPicture")
		.unbind("click")
		.on("click", function() {
			if ($("#listPictures").length > 0) {
				addPicture();
				$(".linkedElements").show();
				$("#listPictures").show();
			} else {
				$(".pictures > div:first").css({
					display: "block",
				});
				$(this).css({
					display: "none",
				});
			}
		});

	$("#addDoc")
		.unbind("click")
		.on("click", function() {
			addDoc();
			$(".linkedElements").show();
			$("#listDocs").show();
		});

	$("#addLink")
		.unbind("click")
		.on("click", function() {
			addLink();
			$(".linkedElements").show();
			$("#listLink").show();
		});

	$("#addCode")
		.unbind("click")
		.on("click", function() {
			addCode();
			$(".linkedElements").show();
			$("#listCodes").show();
		});

	// Gestion des commentaires
	activityWallCommentManager();

	// Gestion des statuts
	activityWallStatusManager();

	// champs de statut du mur d'activité
	$(".comment").each(function() {
		commentManager($(this));
	});
}

/**
 * Supprime les tags a l'exception des iframes
 *
 * @param string html Code HTML à traiter
 *
 * @return string
 */
function stripTagsExceptIframe(html) {
	var tmp = $('<div id="tmpElement"></div>').append(html);

	$("*", tmp)
		.not("iframe")
		.each(function() {
			$(this).replaceWith($(this).text());
		});

	return tmp.html();
}

/**
 * Supprime les tags a l'exception des iframes
 *
 * @param string html Code HTML à traiter
 *
 * @return string
 */
function stripTagsExceptIframeOld(html) {
	var tmp = $('<div id="tmpElement"></div>').append(html);

	$("*", tmp)
		.not("iframe")
		.each(function() {
			if (typeof $(this).attr("href") != "undefined") {
				$(this).replaceWith($(this).text());
			} else {
				$(this).remove();
			}
		});

	return tmp.html();
}

/**
 * Gère l'affichage des statuts du mur
 */
function activityWallStatusManager() {
	var statusLinkActions = $(".messageActionsToggle", document),
		followUpActions = $(".followUpActions"),
		sharedElements = $(".sharedElement");

	// Initialisation des actions sur le statut
	statusActionsInit(statusLinkActions);
	// Gestion du comportement sur les actions
	statusActionsManager(statusLinkActions);
	// Initialisation des actions pour suivre/ne pas suivre
	followUpActionsInit(followUpActions);
	// Gestion des actions de suivi
	followUpActionsManager(followUpActions);
	// Gestion des éléments partagés
	statusSharedElementManager(sharedElements);
}

/**
 * Initialisation pour les actions contextuels à un statut
 *
 * @param  object statusLinkActions lien pour le menu d'actions
 */
function statusActionsInit(statusLinkActions) {
	// On définit le parent pour menu d'actions
	statusLinkActions.each(function() {
		var self = $(this);

		self.data({
			parent: self.parent(),
		});
		self.next(".blocMessageActions").data({
			parent: self.parent(),
		});
	});
}
/**
 * Gestion du comportement sur les actions
 *
 * @param  object statusLinkActions lien pour le menu d'actions
 */
function statusActionsManager(statusLinkActions) {
	statusLinkActions.unbind("click").on("click", function(e) {
		var self = $(this),
			container = self.closest(".blocMessage"),
			actions = $(".blocMessageActions", container);

		e.preventDefault();

		// On récupère la position actuelle du lien pour positionner le menu
		self.data({
			top: self.offset().top + self.outerHeight(true) - 1,
			left: $(window).width() - (self.offset().left + self.outerWidth(true)),
		});

		// On retire à tous les statusLinkActions la classe active
		if (self.attr("class").indexOf("active") != -1) {
			self.removeClass("active");
		} else {
			statusLinkActions.removeClass("active");
			self.addClass("active");
		}

		// On vérifie s'il existe déjà un menu d'actions au niveau du body
		if ($("body").children(".blocMessageActions").length > 0) {
			var actionsOld = $("body").children(".blocMessageActions");

			// On replace le menu dans son parent d'origine
			actionsOld.appendTo(actionsOld.data("parent")).removeAttr("style");

			// On teste si on a le même parent, auquel cas on ne veut pas ajouter le menu dans le body
			if (
				actionsOld
					.data("parent")
					.parent()
					.attr("id") == self.closest(".aMessage").attr("id")
			) {
				return;
			}
		}

		// On ajoute le menu d'actions au body
		actions
			.appendTo($("body"))
			.css({
				top: self.data("top"),
				right: self.data("left"),
			})
			.show();
	});

	$(".blocMessageActions a")
		.unbind("click")
		.on("click", function(e) {
			var container = $(this).parent();

			e.preventDefault();

			if (
				$(this).hasClass("detailLink") ||
				$(this).hasClass("validMessage") ||
				$(this).hasClass("cancelMessage")
			) {
				location.href = $(this).attr("href");
			}

			if ($(this).hasClass("updateAction")) {
				editMessage(e, $(this));
			}

			// On replace le menu dans son parent d'origine
			container.appendTo(container.data("parent")).removeAttr("style");
		});

	// Gestion de la fermeture du menu d'actions
	$("body")
		.unbind("click")
		.on("click", function(e) {
			if ($(e.target).hasClass("messageActionsToggle")) {
				return;
			}
			statusActionsClose();
		});

	// au vote, on est ajouté à la liste des suiveurs
	$("div.rating a.linkLike")
		.unbind("click")
		.on("click", function() {
			actionToFollow($(this));
		});
	$("div.rating a.linkDislike")
		.unbind("click")
		.on("click", function() {
			actionToFollow($(this));
		});
}

/**
 * Ferme le menu d'actions ouvert
 */
function statusActionsClose() {
	var actions = $("body").children(".blocMessageActions"),
		parent = null;

	if (actions.length == 0) {
		return;
	}

	// On récupère le parent du menu d'actions
	parent = actions.data("parent");

	// On remet le menu d'actions à son emplacement d'origine
	actions.appendTo(parent).removeAttr("style");

	$(".messageActionsToggle").removeClass("active");
}

function activityWallCommentManager() {
	var editComment = function(e, element) {
		e.preventDefault();
		e.stopPropagation();

		var link = element,
			comment = link.closest(".row_comment"),
			message = comment.find(".comment_wall"),
			rating = message.find(".rating").detach(),
			author = message.find(".author").detach(),
			timer = message.find(".message_time").detach(),
			data = stripTagsExceptIframe($.trim(message.text())),
			editor = $("<textarea>").addClass("editComment"),
			tags = message.find(".wall_tags"),
			btn = $('<input type="submit">').val("Publier");

		if (message.find(".ratingMessage").length > 0) {
			message.find(".ratingMessage").remove();
			data = stripTagsExceptIframe($.trim(message.text()));
		}

		comment.find(".commentActions").remove();
		comment.unbind("mouseenter").unbind("mouseleave");
		message
			.text("")
			.append(editor.text($.trim(data)))
			.append(tags)
			.append(
				$("<div>")
					.addClass("submit")
					.append(btn)
			);

		editor.focus();
		editor.on("keypress", submitOnEnter);
		if (isInitTag()) {
			editor.textcomplete(behaviorTag, optionsTag);
		}

		btn.on("click", function() {
			data = $.trim(editor.val());
			editTags = [];

			// réactualisation des tags
			message.find(".tagName").each(function() {
				if (data.indexOf("@" + $(this).attr("tag")) === -1) {
					$(this).remove();
				}
			});
			// Récupération des valeurs des tags
			message.find(".tagName").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editTags.push($(this).val());
				}
			});

			$.ajax({
				url: link.attr("href"),
				type: "post",
				data: { text: data, mentioned: editTags },
				success: function(jsonData, textStatus, xhr) {
					comment.html($(jsonData).html());
					comment.on({
						mouseenter: showAction,
						mouseleave: hideAction,
					});
					comment.find(".updateAction").on("click", function(e) {
						editComment(e, $(this));
					});
					initCommentsBehaviors();
				},
			});
		});
	};

	$(".aMessage")
		.unbind("mouseenter")
		.unbind("mouseleave")
		.on({
			mouseenter: showAction,
			mouseleave: hideAction,
		})
		.trigger("mouseleave")
		.find(".blocMessageActions > .updateAction")
		.on("click", function(e) {
			editMessage(e, $(this));
		});

	$(".row_comment")
		.unbind("mouseenter")
		.unbind("mouseleave")
		.on({
			mouseenter: showAction,
			mouseleave: hideAction,
		})
		.trigger("mouseleave")
		.find(".updateAction")
		.on("click", function(e) {
			editComment(e, $(this));
		});

	// à l'ajout d'un commentaire, l'utilisateur est ajouté à la liste des suiveurs
	$("form.formComment").on("submit", function() {
		actionToFollow($(this));
	});

	// gestion des commentaires
	initCommentsBehaviors();

	// Submit par la touche Entree
	$(".blocMessage .formComment .comment")
		.unbind("keypress")
		.on("keypress", submitOnEnter);
}

function hideAction(e) {
	if (e) {
		e.stopPropagation();
	}
}

function showAction(e) {
	if (e) {
		e.stopPropagation();
	}
}

function submitOnEnter(e) {
	if (e.keyCode == 13 && e.shiftKey == false && e.ctrlKey == false && e.altKey == false) {
		e.preventDefault();

		if (
			$(this).hasClass("editStatus") ||
			$(this).hasClass("editComment") ||
			$(this).hasClass("codes") ||
			$(this).hasClass("links")
		) {
			if (
				$(this)
					.parents(".statusBody")
					.find('input[type="submit"]').length > 0
			) {
				$(this)
					.parents(".statusBody")
					.find('input[type="submit"]')
					.trigger("click");
			} else if (
				$(this)
					.parent()
					.find('input[type="submit"]').length > 0
			) {
				$(this)
					.parent()
					.find('input[type="submit"]')
					.trigger("click");
			}
		} else {
			$(this)
				.closest(".formComment")
				.submit();
		}
	}
}

// Fonction permettant de modifier un status
function editMessage(e, element) {
	e.preventDefault();
	e.stopPropagation();

	// Si l'on trouve cette classe c'est le nouveau système de statut
	// Sinon c'est ancien
	if (element.closest("body").find(".statusBody, .commentBody").length > 0) {
		var link = element,
			idStatus = link.attr("href").substring(link.attr("href").lastIndexOf("-") + 1);
		(comment =
			typeof link.parent().data("parent") !== "undefined"
				? link
						.parent()
						.data("parent")
						.closest(".aMessage")
				: link.closest(".blocMessage")),
			(message = comment.find(".message_body")),
			(picture = message.find(".wall_picture").detach()),
			(picturesCounter = message.find(".picturesCounter").detach()),
			(docs = message.find(".wall_docs").detach()),
			(links = message.find(".wall_links").detach()),
			(codes = message.find(".wall_codes").detach()),
			(sharedElement = message.find(".wall_shared_element").detach()),
			(data = stripTagsExceptIframe($.trim(message.html()))),
			(editor = $("<textarea>")
				.addClass("editStatus")
				.attr("name", "text")),
			(btn = $('<input type="submit">').val("Publier")),
			(tags = message.find(".wall_tags")),
			(divAddLinks = $("<div>").addClass("addLinkedElements"));

		comment.find(".message_actions").hide();
		comment.unbind("mouseenter").unbind("mouseleave");
		message.text("").append($("<div>").addClass("linkedElements"));

		// Listes des images
		divAddPicture = formEditionPictures(message, picture, idStatus);

		// Listes des docs
		divAddDoc = formEditionDocs(message, docs, idStatus);

		// Listes des liens
		divAddListLink = formEditionLinks(message, links, submitOnEnter);

		// Listes des codes embarqués
		divAddCode = formEditionCodes(message, codes, submitOnEnter);

		if ($("#addDoc").length > 0) {
			divAddLinks.append(
				$("<a>")
					.addClass("docIn")
					.attr("href", "javascript:void(0)")
					.append($("<span>").addClass("icons"))
					.append(
						$("<span>")
							.addClass("addText")
							.text("Ajouter un fichier")
					)
					.on("click", function() {
						addDoc(divAddDoc);
					})
			);
		}

		if ($("#addLink").length > 0) {
			divAddLinks.append(
				$("<a>")
					.addClass("linkIn")
					.attr("href", "javascript:void(0)")
					.append($("<span>").addClass("icons"))
					.append(
						$("<span>")
							.addClass("addText")
							.text("Ajouter un lien")
					)
					.on("click", function(e) {
						addLink(divAddListLink, submitOnEnter, "");
					})
			);
		}

		if ($("#addCode").length > 0) {
			divAddLinks.append(
				$("<a>")
					.addClass("codeIn")
					.attr("href", "javascript:void(0)")
					.append($("<span>").addClass("icons"))
					.append(
						$("<span>")
							.addClass("addText")
							.text("Ajouter un code embarqué")
					)
					.on("click", function() {
						addCode(divAddCode, submitOnEnter, "");
					})
			);
		}

		if ($("#addPicture").length > 0) {
			divAddLinks.append(
				$("<a>")
					.addClass("pictureIn")
					.attr("href", "javascript:void(0)")
					.append($("<span>").addClass("icons"))
					.append(
						$("<span>")
							.addClass("addText")
							.text("Ajouter une image")
					)
					.on("click", function() {
						addPicture(divAddPicture);
					})
			);
		}

		message.prepend(
			$("<div>")
				.addClass("displayIfCommentEditing")
				.append(divAddLinks)
				.prepend(
					$("<div>")
						.addClass("submit")
						.append(btn)
				)
		);
		// Les tags
		message.prepend(tags);

		// Le message
		message.prepend(editor.text($.trim(data)));

		editor.focus();
		editor.on("keypress", submitOnEnter);
		if (isInitTag()) {
			editor.textcomplete(behaviorTag, optionsTag);
		}

		btn.on("click", function() {
			var contentStatus = $.trim(editor.val()),
				editPictures = "",
				editMedias = "",
				editLinks = [],
				editCodes = "",
				editTags = [];

			// Récupération des valeurs des anciens docs
			message.find(".pics").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editPictures += $.trim($(this).val()) + ",";
				}
			});
			// Suppression du derniers caractères
			if (editPictures.length > 0) {
				editPictures = editPictures.substring(0, editPictures.length - 1);
			}

			// Récupération des valeurs des anciens docs
			message.find(".docs").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editMedias += $.trim($(this).val()) + ",";
				}
			});
			// Suppression du derniers caractères
			if (editMedias.length > 0) {
				editMedias = editMedias.substring(0, editMedias.length - 1);
			}

			// Récupération des valeurs des liens
			message.find(".links").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editLinks.push($.trim($(this).val()));
				}
			});

			// réactualisation des tags
			message.find(".tagName").each(function() {
				if (contentStatus.indexOf("@" + $(this).attr("tag")) === -1) {
					$(this).remove();
				}
			});
			// Récupération des valeurs des tags
			message.find(".tagName").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editTags.push($(this).val());
				}
			});

			// Récupération des valeurs des codes embarques
			message.find(".codes").each(function() {
				if ($.trim($(this).val()).length > 0) {
					editCodes += $.trim($(this).val()) + "@!@";
				}
			});

			// Suppression des trois derniers caractères
			if (editCodes.length > 0) {
				editCodes = editCodes.substring(0, editCodes.length - 3);
			}

			var submitElement = {
				link: link.attr("href") + "?type=" + $(".profile_wall").data("type"),
				contentStatus: contentStatus,
				editLinks: editLinks,
				editCodes: editCodes,
				comment: comment,
				editMessage: editMessage,
				showAction: showAction,
				hideAction: hideAction,
				editTags: editTags,
			};

			// Ajout d'une métaphore temporelle
			message.append(
				$("<div>")
					.addClass("ajaxLoading")
					.append('<img src="/common_images/community/ajax-loader.gif" alt="" />')
			);
			sendNewMedia(idStatus, divAddPicture, "pictures", editPictures, submitElement);
			sendNewMedia(idStatus, divAddDoc, "file", editMedias, submitElement);
		});
	} else {
		var link = $(this),
			comment = link.closest(".aMessage"),
			message = comment.find(".message_body"),
			picture = message.find(".wall_picture").detach(),
			pictureToEdit = picture.html(),
			data = stripTagsExceptIframe($.trim(message.html())),
			editor = $("<textarea>").addClass("editStatus"),
			tags = message.find(".wall_tags"),
			btn = $('<input type="submit">').val("Publier");

		link[0].style.visibility = "hidden";
		hideAction.apply(comment);
		comment.unbind("mouseenter").unbind("mouseleave");
		message
			.text("")
			.append(editor.text($.trim(data)))
			.append(tags)
			.append(
				$("<div>")
					.addClass("submit")
					.append(btn)
			);

		message.append(picture);
		editor.focus();
		editor.on("keypress", submitOnEnter);

		btn.click(function() {
			data = $.trim(editor.val());
			$.ajax({
				url: link.attr("href"),
				type: "post",
				data: { text: data },
				success: function(jsonData, textStatus, xhr) {
					comment.html($(jsonData).html());
					comment.on({
						mouseenter: showAction,
						mouseleave: hideAction,
					});
					comment.find(".updateAction").on("click", function(e) {
						editComment(e, $(this));
					});
					initCommentsBehaviors();
				},
			});
		});
	}
}

/**
 * Initialisation des actions pour suivre/ne pas suivre
 */
function followUpActionsInit(followUpActions) {
	followUpActions.each(function() {
		var self = $(this);

		if (self.hasClass("active")) {
			self.show().attr({
				title: self
					.parent()
					.find(".unfollowAction")
					.text(),
			});
		} else {
			self.hide().attr({
				title: self
					.parent()
					.find(".followAction")
					.text(),
			});
		}
	});
}

/**
 * Gère les actions de suivi d'un statut
 *
 * @param  object followUpActions les boutons suivre/ne pas suivre
 */
function followUpActionsManager(followUpActions) {
	if (
		followUpActions.length == 0 ||
		followUpActions.parent().length == 0 ||
		typeof followUpActions.parent().data("parent") == "undefined"
	) {
		return;
	}

	var followShortLink = followUpActions
		.parent()
		.data("parent")
		.find(".messageActionFollow");

	// Gère le clic sur les actions dans le menu
	followUpActions.on("click", function(e) {
		e.preventDefault();
		toggleFollowUpActions($(this));
	});

	// Gère le clic sur l'action rapide pour suivre/ne pas suivre
	$(".messageActionFollow").on("click", function(e) {
		var self = $(this),
			id = self
				.closest(".aMessage")
				.attr("id")
				.split("message")[1];

		e.preventDefault();

		if (self.hasClass("active")) {
			// On joue l'action du lien de référence
			$("#unfollow-" + id).trigger("click");
		} else {
			// On joue l'action du lien de référence
			$("#follow-" + id).trigger("click");
		}
	});
}

/**
 * Gestion des éléments partagés
 *
 * @param  object sharedElements l'élément partagé
 */
function statusSharedElementManager(sharedElements) {
	sharedElements.on("click", function() {
		var urlToGo = $(".sharedElementLink a", this).attr("href");
		if (urlToGo !== undefined) {
			location.href = urlToGo;
		}
	});
}

/**
 * Gère le comportement suite au clic sur les boutons pour suivre/ne pas suivre
 *
 * @param  object clickedElement le lien direct pour suivre/ne pas suivre
 */
function toggleFollowUpActions(clickedElement) {
	var forcefollow = true;
	if (clickedElement.attr("data-force") === "false") {
		forcefollow = false;
	}
	$.ajax({
		url: clickedElement.attr("href"),
		type: "POST",
		data: { forcefollow: forcefollow },
		dataType: "json",
		success: function(response, status) {
			if (response.result) {
				clickedElement.each(function() {
					var self = $(this),
						newText = response.content,
						id = self.attr("id").split("-")[1],
						text = self.text();

					// On inverse les classes et l'affichage des actions
					$("#message" + id)
						.find(".followUpActions")
						.toggle()
						.toggleClass("active");
					$("#message" + id)
						.find(".messageActionFollow")
						.toggleClass("active");

					// On met le bon texte dans la tooltip
					$("#message" + id)
						.find(".messageActionFollow .arrowContent")
						.contents()
						.filter(function() {
							return this.nodeType === 3;
						})
						.each(function() {
							this.textContent = this.textContent.replace(text, newText);
						});
				});
			}
		},
		error: function(response, status, error) {},
		complete: function(response, status) {
			clickedElement.removeAttr("data-force");
		},
	});
}

// lorsqu'une action sur un statut (vote, commentaire) engendre un suivi, on le déclenche visuellement
function actionToFollow(element) {
	var parentMessage = $(element).parents("div.blocMessage");
	if (parentMessage.find("div.message_actions a.messageActionFollow.active").length == 0) {
		followLink = parentMessage.find(
			"div.message_actions div.blocMessageActions a.followUpActions.followAction.active"
		);
		followLink.attr("data-force", false);
		followLink.click();
	}
}

function initCommentsBehaviors() {
	$(".respons").each(function() {
		var commentNumber = $(".row_comment", this).length;

		if (commentNumber > 0 && commentNumber < 3) {
			$(this).css("display", "block");
		} else if (commentNumber >= 3) {
			$(this)
				.prev()
				.find(".commentStatus")
				.html(commentNumber + " commentaires");
		}
	});

	$(".blocMessage a.commentStatus")
		.data("open", "no")
		.unbind("click")
		.on("click", function(e) {
			e.preventDefault();
			if ($(this).data("open") == "no") {
				$(this)
					.closest(".blocMessage")
					.find(".respons")
					.css("display", "block");
				$(this).data("open", "yes");
			} else {
				$(this)
					.closest(".blocMessage")
					.find(".respons")
					.css("display", "none");
				$(this).data("open", "no");
			}
		});
}

// Fonction de recadrage des images dans leur conteneur
function replacementImage(e, f) {
	$(e, f).each(function() {
		$(this).css({
			"margin-left":
				($(this)
					.parent()
					.width() -
					$(this).width()) /
					2 +
				"px",
			"margin-top":
				($(this)
					.parent()
					.height() -
					$(this).height()) /
					2 +
				"px",
		});
	});
}

function positionCalculation() {
	// Verification de la présence d'une map
	if (typeof map !== undefined) {
		var calculation = function() {
			var address = "",
				defaultLang = $("#defaultlang").val();

			// Récupération des champs pour la construction de l'adresse
			if ($("#adr1id").val() !== undefined && $("#adr1id").val() != "") {
				address += $("#adr1id").val() + ",";
			}
			if ($("#cpid").val() !== undefined && $("#cpid").val() != "") {
				address += $("#cpid").val() + ",";
			}
			if ($("#villeid").val() !== undefined && $("#villeid").val() != "") {
				address += $("#villeid").val() + ",";
			}
			if ($("#paysid").val() !== undefined && $("#paysid").val() != "") {
				address += $("#paysid").val() + ",";
			} else if (defaultLang !== undefined && defaultLang == "fr") {
				address += "france,";
			}

			// Suppression du dernier caractère (la virgule)
			address = address.substring(0, address.length - 1);

			// Avec position calcul la longitude lattidue
			// Google_Map->Calcul
			if (address != "") {
				var geocoder = new google.maps.Geocoder();
				geocoder.geocode({ address: address }, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						updateCoord(results[0].geometry.location);
						if (typeof map !== "undefined") {
							initMarker(results[0].geometry.location);
							map.setZoom(12);
						}
					}
				});
			}
		};
		// Pour lancer la fonction lorsqu'on appuye sur une touche
		$("#adr1id, #cpid, #villeid, #paysid").keypress(function() {
			calculation();
		});

		// Pour relancer la fonction après avoir appuyé sur une touche
		$("#adr1id, #cpid, #villeid, #paysid").keyup(function() {
			calculation();
		});
	}
}

$(window).load(function() {
	// ---------------------------------------------------------------------------
	// Messagerie Instantanée
	var chatContent,
		strUrl,
		idRoom,
		isRead = new Array(),
		lastMessageCheck,
		currentItemIndex = 0,
		lengthChatTabs = 0,
		posTab = 0,
		tabsContentSize = 83,
		checkForNewChatConversationDelay = 5000;

	positionCalculation();

	function hasNewChatConversation() {
		$.ajax({
			url: "/action-CommunityChat-check",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				if (response == "yes" && $("#liveShortcut").length == 0) {
					$("#liveInfo").remove();
					$("#wrapper").append(
						'<div id="liveShortcut"><a id="linkLive" href="/action-CommunityChat-load">Discussion instantan&eacute;e</a><div id="liveRoom"></div></div>'
					);
					isChatActive = true;
					checkForNewMessages();
				} else if (response == "no" && $("#liveShortcut").length > 0) {
					$("#liveShortcut").remove();
					$("#wrapper").append(
						'<div id="liveInfo"><a id="linkLive" href="javascript:;">Votre interlocuteur est d&eacute;connect&eacute;</a></div>'
					);
					isChatActive = false;
				}
				if (checkForNewChatConversationDelay < 120000) {
					checkForNewChatConversationDelay += 5000;
				}
				setTimeout(function() {
					hasNewChatConversation();
				}, checkForNewChatConversationDelay);
			},
		});
	}

	// Test si la variable globale existe sinon défini sa version locale à désactivée
	if (!window.hasOwnProperty("checkForNewChatConversation")) {
		var checkForNewChatConversation = false;
	}

	// Trigger qui détecte si l'on doit afficher un bouton messagerie instantanée
	if (checkForNewChatConversation) {
		setTimeout(function() {
			hasNewChatConversation();
		}, checkForNewChatConversationDelay);
	}

	// Action pour lancer un chat
	$(document).on("click", ".actionChat a.loadChat", function(e) {
		e.preventDefault();
		if ($("#liveShortcut a#linkLive").length > 0) {
			$("#liveShortcut a#linkLive").click();
		}
	});

	// Création du layer contenant le contenu du chat
	$(document).on("click", "#liveShortcut a#linkLive", function(e) {
		var container = $("#liveRoom");

		e.preventDefault();
		e.stopPropagation();
		currentItemIndex = 0;

		if (chatContent) {
			chatContent.appendTo("#liveShortcut");
			$("h1, #submitid", container).css("display", "none");
			$("#listMessages", container).scrollTop($("#liveRoom").height());
			$("#listTabsThreads_content ul li", container).removeClass("chatActiveTab");
			$("#listTabsThreads_content ul li:first", container).addClass("chatActiveTab");

			if ($("#reduceFormInstantTalk").length <= 0) {
				$("#liveShortcut").prepend(
					$("<div>")
						.addClass("icons")
						.attr({
							id: "reduceFormInstantTalk",
						})
						.text("-")
				);
			}

			chatContent = null;
		} else {
			var myDate = new Date().getTime();
			$.ajax({
				url: "/action-CommunityChat-load",
				type: "get",
				dataType: "html",
				success: function(response, textStatus, xhr) {
					container.html(response);
					$("#listTabsThreads_content ul li", container).removeClass("chatActiveTab");
					$("#listTabsThreads_content ul li:first", container).addClass("chatActiveTab");
					strUrl = $("a.items:first").attr("href");

					if ($("#reduceFormInstantTalk").length <= 0) {
						$("#liveShortcut").prepend(
							$("<div>")
								.addClass("icons")
								.attr({
									id: "reduceFormInstantTalk",
								})
								.text("-")
						);
					}

					$("h1, #submitid", container).css("display", "none");

					$("#currentThread", container).scrollTop($("#listMessages", container).height());
				},
			});
		}
		var totalWidth = 71 * lengthChatTabs;
		$(chatContent)
			.find("#liveRoom #listTabsThreads_content ul")
			.width(totalWidth);
	});

	$(document).on("click", "#liveRoom div#nextThread", function() {
		if (posTab < lengthChatTabs / 3 - 1) {
			posTab++;
			$("ul", "#liveRoom #listTabsThreads_content").animate(
				{
					marginLeft: -tabsContentSize * posTab,
				},
				500
			);
		}
	});

	$(document).on("click", "#liveRoom div#prevThread", function() {
		if (posTab > 0) {
			posTab--;
			$("ul", "#liveRoom #listTabsThreads_content").animate(
				{
					marginLeft: -tabsContentSize * posTab,
				},
				500
			);
		}
	});

	// Réduction du layer au clic sur la fermeture
	$(document).on("click", "#liveShortcut div#reduceFormInstantTalk", function(e) {
		chatContent = $("#liveRoom").detach();
		$(this).remove();
	});

	// Changement d'instance de chat
	$(document).on("click", "#liveRoom a.items", function(e) {
		e.preventDefault();
		e.stopPropagation();
		var linkList = $("#liveRoom").find("a.items");
		currentItemIndex = linkList.index($(this));
		$("#liveRoom #listTabsThreads_content ul li").removeClass("chatActiveTab");
		$(this)
			.parent()
			.addClass("chatActiveTab");
		strUrl = $(this).attr("href");
		$('#liveRoom input[name="parentMessage"]').val($(this).attr("rel"));
		if (chatContent) {
			chatContent.appendTo("#liveShortcut");
			chatContent = null;
		} else {
			$.ajax({
				url: $(this).attr("href"),
				type: "get",
				dataType: "json",
				success: function(jsonData, textStatus, xhr) {
					var tabMessage = jsonData.messages;
					$("#liveRoom #listMessages").html("");
					for (i = 0; i < tabMessage.length; i++) {
						var htmlCode = atob(tabMessage[i]);
						$("#liveRoom #listMessages").append(htmlCode);
						htmlCode = null;
					}

					$("#liveRoom #currentThread").scrollTop($("#liveRoom #listMessages").height());
				},
			});
		}
	});

	// Ré-actualisation ajax de la discussion
	setTimeout(function() {
		var interval2 = setInterval(function() {
			if ($("a.items").length > 0) {
				if (strUrl == "" || strUrl == undefined) {
					strUrl = $("a.items:first").attr("href");
				}
				if (strUrl != "") {
					var myDate = new Date().getTime();
					$.ajax({
						url: strUrl,
						type: "get",
						dataType: "json",
						success: function(jsonData, textStatus, xhr) {
							var tabMessage = jsonData.messages;
							$("#liveRoom #listMessages").html("");
							for (i = 0; i < tabMessage.length; i++) {
								var htmlCode = atob(tabMessage[i]);
								$("#liveRoom #listMessages").append(htmlCode);
								htmlCode = null;
							}

							$("#liveRoom #currentThread").scrollTop($("#liveRoom #listMessages").height());
						},
					});
				}
			}
		}, 8000);
	}, 3000);

	function checkForNewMessages() {
		$.ajax({
			url: "/action-CommunityChat-checkMessage",
			type: "get",
			dataType: "json",
			success: function(response, textStatus, xhr) {
				var threadsIds = response.tabThreadIds,
					lastMessagesIds = response.lastMessageCheckIds,
					itemTab = response.itemTabs,
					nbElements = 0,
					nbItem = 0,
					htmlCode = "";

				if (response.inactive) {
					isChatActive = false;
				}

				//Mise à jour des onglets
				if (itemTab) {
					nbItem = itemTab.length;
					lengthChatTabs = nbItem;
				}

				for (i = 0; i < nbItem; i++) {
					strCss = "";
					if (itemTab[i]) {
						if (currentItemIndex == i) {
							strCss = 'class = "chatActiveTab"';
						}
						if (itemTab[i].minlabel) {
							var tabLabel = itemTab[i].minlabel;
						} else {
							var tabLabel = itemTab[i].label;
						}

						if (tabLabel.length > 20) {
							tabLabel = tabLabel.substr(0, 20) + "...";
						}
						htmlCode +=
							"<li " +
							strCss +
							'><a href="' +
							itemTab[i].link +
							'" rel="' +
							itemTab[i].rel +
							'" class="items">' +
							tabLabel +
							"</a><span>" +
							itemTab[i].label +
							"</span></li>";
					}
				}
				$("#listTabsThreads_content").html("<ul>" + htmlCode + "</ul>");
				$("ul", "#liveRoom #listTabsThreads_content").css({
					marginLeft: -tabsContentSize * posTab,
				});

				if (threadsIds) {
					nbElements = threadsIds.length;
				}

				var general = false;
				for (i = 0; i < nbElements; i++) {
					if (lastMessagesIds[i] != isRead[i]) {
						isRead[i] = false;
					}
					if (isRead[i] == false) {
						$('a[rel="' + threadsIds[i] + '"]')
							.parent()
							.addClass("newChatMessage");
						isRead[i] = lastMessagesIds[i];
						general = true;
					}
				}

				if (general == true) {
					$("#linkLive")
						.fadeOut(400)
						.fadeIn(800)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400);
					$("#liveRoom .chatTitle span")
						.fadeOut(400)
						.fadeIn(800)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400)
						.fadeOut(400)
						.fadeIn(400);
				}

				if (response.disconnect == true) {
				}
				if (isChatActive) {
					setTimeout(function() {
						checkForNewMessages();
					}, 5000);
				}
			},
		});
	}

	// On capte l'événement du submit
	$(document).on("submit", '#liveRoom form[name="response_form"]', function(e) {
		e.preventDefault();
		$("#liveRoom #listMessages").append(
			'<div id="loadingAjax"><img src="/common_images/community/ajax-loader.gif></div>'
		);
		$("#loadingAjax").css({
			position: "absolute",
			top: $("#liveRoom #listMessages").height() / 2,
			left: $("#liveRoom #listMessages").width() / 2,
		});
		$("#liveRoom #message_body").attr("readonly", "readonly");
		if (isAjaxLocked()) {
			return false;
		}
		initAjaxLock();
		$.ajax({
			url: "account-messaging-live-" + $('input[name="parentMessage"]').val() + "?getpagecontent",
			type: "post",
			data: $(this).serialize(),
			dataType: "json",
			success: function(jsonData, textStatus, xhr) {
				var tabMessage = jsonData.messages;
				$("#liveRoom #listMessages").html("");
				for (i = 0; i < tabMessage.length; i++) {
					var htmlCode = atob(tabMessage[i]);
					$("#liveRoom #listMessages").append(htmlCode);
					htmlCode = null;
				}

				$("#liveRoom #currentThread").scrollTop($("#liveRoom #listMessages").height());
				$("#loadingAjax").remove();
				$("#liveRoom #message_body").removeAttr("readonly");
				$("#liveRoom #message_body").val("");
				resetAjaxLock();
			},
		});
	});

	// Submit par la touche Entree
	$(document).on("keypress", "#liveRoom textarea#message_body", function(e) {
		if (e.keyCode == 13 && e.shiftKey == false && e.ctrlKey == false && e.altKey == false) {
			e.preventDefault();
			$('#liveRoom form[name="response_form"]').submit();
		}
	});

	// Post d'un nouveau message dans le chat
	$(document).on("submit", ".formComment", function(e) {
		e.preventDefault();
		var id = $(this).attr("id");
		if (isAjaxLocked()) {
			return false;
		}
		var form = $(this);
		form.addClass("pending");
		initAjaxLock();
		$.ajax({
			url: form.attr("action"),
			type: "post",
			data: form.serialize(),
			dataType: "html",
			success: function(response, textStatus, xhr) {
				resetAjaxLock();
				var idCom = "com" + id.substr(5, id.length);
				var comment = $(response);

				$("div#" + idCom).append(comment);
				$("#wall_comment_" + id.substr(5, id.length)).val("");
				$("input[type=submit]")
					.removeClass("disabled")
					.attr("disabled", false);
				$("textarea").removeClass("disabled");
				clickedButtons = new Array();
				activityWallCommentManager();
				form.removeClass("pending");
			},
		});
	});

	$(document).ready(function() {
		var hashChangeEvent = function() {
			var hash = document.location.hash;
			if (hash.substring(0, 7) == "#detail") {
				var data = hash.split("-");
				var contentId = data[1];
				var clicked = false;
				$(".messagesBoard .rowMessage input.delThread").each(function() {
					if ($(this).val() == contentId) {
						var parent = $(this).closest(".rowMessage");
						clicked = true;
						if (!parent.hasClass("selectedTalk")) {
							parent.find(".resumeContent a").trigger("click");
						}
					}
				});
				if (!clicked) {
					document.location.href = "account-messaging-detail-" + contentId + "#" + data[2];
				}
			}
		};
		hashChangeEvent();
		$(window).on("hashchange", hashChangeEvent);
	});
});

//------------------------------------------------------------------------------
// PLUGIN PRELOAD IMAGE

(function($) {
	var settings = {
		scale: "contain", // cover
		prefix: "prev_",
		types: ["image/gif", "image/png", "image/jpeg"],
		mime: {
			jpe: "image/jpeg",
			jpeg: "image/jpeg",
			jpg: "image/jpeg",
			gif: "image/gif",
			png: "image/png",
			"x-png": "image/png",
			tif: "image/tiff",
			tiff: "image/tiff",
		},
	};

	var methods = {
		init: function(options) {
			settings = $.extend(settings, options);

			return this.each(function() {
				$(this).on("change", methods.change);
				$("#" + settings["prefix"] + this.id).addClass(settings["prefix"] + "container");
			});
		},
		destroy: function() {
			return this.each(function() {
				$(this).unbind("change");
			});
		},
		base64_encode: function(data) {
			var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
			var o1,
				o2,
				o3,
				h1,
				h2,
				h3,
				h4,
				bits,
				i = 0,
				ac = 0,
				enc = "",
				tmp_arr = [];

			if (!data) {
				return data;
			}

			do {
				// pack three octets into four hexets
				o1 = data.charCodeAt(i++);
				o2 = data.charCodeAt(i++);
				o3 = data.charCodeAt(i++);

				bits = (o1 << 16) | (o2 << 8) | o3;

				h1 = (bits >> 18) & 0x3f;
				h2 = (bits >> 12) & 0x3f;
				h3 = (bits >> 6) & 0x3f;
				h4 = bits & 0x3f;

				// use hexets to index into b64, and append result to encoded string
				tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
			} while (i < data.length);

			enc = tmp_arr.join("");

			var r = data.length % 3;

			return (r ? enc.slice(0, r - 3) : enc) + "===".slice(r || 3);
		},
		change: function(event) {
			var id = this.id;

			$("#" + settings["prefix"] + id).html("");

			if (window.FileReader) {
				for (i = 0; i < this.files.length; i++) {
					var reader = new FileReader();
					reader.onload = function(e) {
						$("<img />")
							.attr({ src: e.target.result, alt: "Image preview" })
							.addClass(settings["prefix"] + "thumb")
							.appendTo($("#" + settings["prefix"] + id));
					};
					reader.readAsDataURL(this.files[i]);
				}
			} else {
				var ForReading = 1,
					ForWriting = 2;
				var fso = new ActiveXObject("Scripting.FileSystemObject");

				for (i = 0; i < this.files.length; i++) {
					f = fso.OpenTextFile(this.files[i], ForReading);
					var cnt = f.AtEndOfStream ? "" : f.ReadAll();
					f.Close();
					var ext = fso.GetExtensionName(this.files[i]);
					$("<img />")
						.attr({ src: "data:image/" + ext + ";" + this.base64_encode(cnt), alt: "Image preview" })
						.addClass(settings["prefix"] + "thumb")
						.appendTo($("#" + settings["prefix"] + id));
				}
			}
		},
	};
	$.fn.preimage = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === "object" || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error("Method " + method + " does not exist on jQuery.preimage");
		}
	};
})(jQuery);

var ajaxLock = false;

function isAjaxLocked() {
	if (ajaxLock === false) {
		return false;
	}
	// Si le lock a été posé il y a plus de 5sec, on le supprime
	var cacheDuraction = new Date().getTime() - 5;
	if (ajaxLock.getTime() > cacheDuraction) {
		resetAjaxLock();
		return false;
	}
	return true;
}
function initAjaxLock() {
	ajaxLock = new Date();
}
function resetAjaxLock() {
	ajaxLock = false;
}

// Fonction permettant la gestion des votes sur les messages du mur
function ratingMemberManager(idElement) {
	var idMember =
			"ratingMembers_" +
			$(idElement)
				.attr("id")
				.substr(12),
		isVisible = $("#" + idMember).is(":visible");

	$(".ratingUsers").hide();
	if ($("#" + idMember).length > 0 && !isVisible) {
		$("#" + idMember).show();
	}
}

// Fonction ajax de mise à jour lors d'une action sur le vote
function ratingManager(url, idElement) {
	$.ajax({ url: url })
		.success(function(response) {
			if ($(idElement).length > 0) {
				$(idElement).replaceWith(response);
			}
			$(".ratingMessage")
				.delay(4000)
				.fadeOut(500, function() {
					$(this).remove();
				});
		})
		.fail(function() {
			if (false) {
				console.log("erreur rating");
			}
		});
}

function changeOrderMessage(selectId, url) {
	if ($("#" + selectId).length > 0) {
		url += $("#" + selectId).val();

		$.ajax({ url: url })
			.success(function(response) {
				if ($(".wallMessage").length > 0) {
					$(".wallMessage").replaceWith(response);
					$("div.aMessage").hover(
						function() {
							$(this).addClass("over");
						},
						function() {
							$(this).removeClass("over");
						}
					);
					var gallery = $("div.gallery a.lightbox");
					if (gallery && typeof gallery.lightbox !== "undefined") {
						gallery.lightbox({ fileLoadingImage: false });
					}

					// Gestion du mur d'activité
					activityWallManager();
				}
			})
			.fail(function() {
				if (false) {
					console.log("erreur rating");
				}
			});
	}
}

//Ajout à la liste des documents un nouveau champ file pour en upload un autre
function addPicture(listElement) {
	if (typeof listElement === "undefined") {
		listElement = $("#listPictures");
	}
	listElement.append(
		$("<div>")
			.addClass("div_wall_bloc")
			.addClass("div_wall_picture")
			.addClass("relative")
			.append(
				$("<span>")
					.addClass("icons")
					.addClass("divAddPictureImg")
			)
			.append(
				$("<input>")
					.attr({
						type: "hidden",
						name: "MAX_FILE_SIZE[]",
					})
					.val("20971520")
			)
			.append(
				$("<input>")
					.attr({
						type: "file",
						name: "pictures[]",
						accept: "image/*",
						multiple: "multiple",
					})
					.addClass("wall_picture")
					.addClass("newMedia")
			)
	);

	loadDeleteAction(listElement);
}

// Ajout à la liste des documents un nouveau champ file pour en upload un autre
function addDoc(listElement) {
	if (typeof listElement === "undefined") {
		listElement = $("#listDocs");
		var name = "file[]";
	} else {
		var name = "editFile[]";
	}

	listElement.append(
		$("<div>")
			.addClass("div_wall_bloc")
			.addClass("div_wall_doc")
			.addClass("relative")
			.append(
				$("<span>")
					.addClass("icons")
					.addClass("divAddDocImg")
			)
			.append(
				$("<input>").attr({
					type: "file",
					class: "newMedia",
					name: name,
					multiple: "multiple",
				})
			)
	);

	loadDeleteAction(listElement, true);
}

// Se charge d'envoyer les nouveaux contenus du statut
function sendNewMedia(idStatus, listElement, name, oldData, submitElement) {
	var data = new FormData();

	if (typeof listElement !== "undefined") {
		listElement.find(".newMedia").each(function() {
			$.each($(this).prop("files"), function(i, file) {
				data.append(name + "[]", file);
			});
		});
	}

	// Ajoute les anciennes données
	data.append("old" + name, oldData);
	data.append("type", name);

	$.ajax({
		url: "account-activitywall-sendMedia-" + idStatus,
		data: data,
		cache: false,
		contentType: false,
		processData: false,
		type: "POST",
		success: function(data) {
			if (name == "file") {
				editStatus(submitElement, idStatus);
			}
		},
	});
}

function editStatus(submitElement, idStatus) {
	var link = submitElement["link"],
		data = submitElement["contentStatus"],
		editLinks = submitElement["editLinks"],
		editCodes = submitElement["editCodes"],
		comment = submitElement["comment"],
		editMessage = submitElement["editMessage"],
		showAction = submitElement["showAction"],
		hideAction = submitElement["hideAction"],
		editTags = submitElement["editTags"];

	$.ajax({
		url: link,
		type: "post",
		dataType: "html",
		data: {
			text: data,
			links: editLinks,
			codes: editCodes,
			mentioned: editTags,
		},
		success: function(jsonData, textStatus, xhr) {
			comment.html($(jsonData).html());
			comment.on({
				mouseenter: showAction,
				mouseleave: hideAction,
			});

			// On rebranche les fonctionnalités d'édition
			comment.find(".updateAction").on("click", function(e) {
				editMessage(e, $(this));
			});

			statusActionsInit(comment.find(".messageActionsToggle"));
			statusActionsManager(comment.find(".messageActionsToggle"));
			followUpActionsInit(comment.find(".followUpActions"));
			followUpActionsManager(comment.find(".followUpActions"));

			initCommentsBehaviors();
			$(".ajaxLoading").remove();
			callbackEditStatus(idStatus);
		},
	});
}

// Déclaration de la callback à vide
function callbackEditStatus(idStatus) {}

// Déclaration de la callback à vide
function callbackPager(elements) {}

function feedbackErrorMessage(idStatus) {
	$("#message" + idStatus)
		.find(".statusEditionError")
		.delay(10000)
		.fadeOut(400, function() {
			$(this).remove();
		});
}

// Edition des docs d'un status
function editMedia(listElement, element) {
	if (typeof listElement === "undefined") {
		listElement = $("#listDocs");
	}

	listElement.append(
		$("<div>")
			.addClass("div_wall_media")
			.addClass("div_wall_bloc")
			.append(element)
	);

	loadDeleteAction(listElement);
}

// Ajoute à la liste des liens un nouveau champ text
function addLink(listElement, onKeyPress, text) {
	if (typeof listElement === "undefined") {
		listElement = $("#listLink");
		onKeyPress = null;
		text = "";
		name = "links[]";
	} else {
		name = "editLinks[]";
	}

	listElement.append(
		$("<div>")
			.addClass("div_wall_bloc")
			.addClass("div_wall_link")
			.addClass("relative")
			.append(
				$("<span>")
					.addClass("icons")
					.addClass("divAddLinkImg")
			)
			.append(
				$("<input>")
					.attr("type", "text")
					.attr("name", name)
					.addClass("links")
					.on("keypress", onKeyPress)
					.val(text)
			)
	);

	loadDeleteAction(listElement);
}

// Ajoute à la liste des codes embarqués un nouveau champ textarea
function addCode(listElement, onKeyPress, text) {
	if (typeof listElement === "undefined") {
		listElement = $("#listCodes");
		onKeyPress = null;
		text = "";
		name = "codes[]";
	} else {
		name = "editCodes[]";
	}

	listElement.append(
		$("<div>")
			.addClass("div_wall_bloc")
			.addClass("div_wall_code")
			.addClass("relative")
			.append(
				$("<span>")
					.addClass("icons")
					.addClass("divAddCodeImg"),
				$("<textarea>")
					.addClass("codes")
					.attr("name", name)
					.on("keypress", onKeyPress)
					.val(text)
			)
	);

	loadDeleteAction(listElement);
}

// Ajoute le lien de suppression pour un champ de pièce jointe au statut
function loadDeleteAction(listElement) {
	$("div:last", listElement).append(
		$("<a>")
			.attr({
				onclick: "deleteBloc(this);",
				href: "javascript:void(0)",
			})
			.addClass("LinkIn")
			.addClass("deleteElement")
			.addClass("relative")
			.append(
				$("<span>")
					.addClass("arrowContent")
					.text("Supprimer")
					.append($("<span>").addClass("arrowBlack"))
			)
	);
}

// Suppression du champ media
function deleteBloc(element) {
	if ($(element).closest(".div_wall_bloc").length > 0) {
		$(element)
			.closest(".div_wall_bloc")
			.remove();
	}
}

// Création du formulaire pour les images d'un status
function formEditionPictures(message, picture, idStatus) {
	if (picture.find(".statusPics").length > 0 || $("#addPicture").length > 0) {
		var div = $("<div>"),
			formPicture = $("<form>"),
			divAddPicture = $("<div>").addClass("listAddPictures");

		formPicture.attr({
			type: "post",
			enctype: "multipart/form-data",
			action: "account-activitywall-sendMedia-" + idStatus,
		});

		formPicture.append(divAddPicture);

		// On remplit le formulaire avec les anciennes images
		if (picture.find(".statusPics").length > 0) {
			$.each(picture.find(".statusPics"), function(i, elementPicture) {
				editMedia($(divAddPicture), elementPicture);
			});
		}

		div.append(formPicture);
		message.find(".linkedElements").append(div);

		return $(divAddPicture);
	}
}

// Création du formulaire pour les docs d'un status
function formEditionDocs(message, docs, idStatus) {
	if (docs.find(".statusDocs").length > 0 || $("#addDoc").length > 0) {
		var div = $("<div>"),
			formDoc = $("<form>"),
			divAddDoc = $("<div>").addClass("listAddDocs");

		formDoc.attr({
			type: "post",
			enctype: "multipart/form-data",
			action: "account-activitywall-sendMedia-" + idStatus,
		});

		formDoc.append(divAddDoc);

		// On remplit le formulaire avec les anciens documents
		if (docs.find(".statusDocs").length > 0) {
			$.each(docs.find(".statusDocs"), function(i, elementDoc) {
				editMedia($(divAddDoc), elementDoc);
			});
		}

		div.append(formDoc);
		message.find(".linkedElements").append(div);

		return $(divAddDoc);
	}
}

// Création du formulaire pour les liens d'un status
function formEditionLinks(message, links, submitOnEnter) {
	if (links.find(".statusLinks").length > 0 || $("#addLink").length > 0) {
		var div = $("<div>"),
			divAddLink = $("<div>").addClass("listAddLinks");

		div.append(divAddLink);
		for (var i = 0; i < links.find(".statusLinks").length; i++) {
			var elementLink = $(links.find(".statusLinks")[i]);
			addLink($(divAddLink), submitOnEnter, $.trim(elementLink.text()));
		}

		message.find(".linkedElements").append(div);

		return $(divAddLink);
	}
}

// Création du formulaire pour les code embarqués d'un status
function formEditionCodes(message, codes, submitOnEnter) {
	if (codes.find(".statusCodes").length > 0 || $("#addCode").length > 0) {
		var div = $("<div>"),
			divAddCode = $("<div>").addClass("listAddCodes");

		div.append(divAddCode);
		for (var i = 0; i < codes.find(".statusCodes").length; i++) {
			var code = $(codes.find(".statusCodes")[i]);
			addCode($(divAddCode), submitOnEnter, $.trim(code.html()));
		}

		message.find(".linkedElements").append(div);

		return $(divAddCode);
	}
}

/**
 * Retourne si une touche frappé au clavier est une touche qui inscrit du texte
 *
 * @param Event e
 *
 * @return bool
 */
function isKeyboardChange(e) {
	if (e.type == "input") {
		return true;
	}

	if (navigator.appName.indexOf("Internet Explorer") == -1 || navigator.appName.indexOf("Netscape") == -1) {
		return false;
	}

	if (!e || !e.keyCode || !e.which) {
		return true;
	}

	var code = e.which ? e.which : e.keyCode;

	switch (e.keyCode) {
		case 9: // tab
		case 13: // enter
		case 16: // shift
		case 17: // ctrl
		case 18: // alt
		case 19: // pause/break
		case 20: // caps lock
		case 27: // escape
		case 33: // page up
		case 34: // page down
		case 35: // end
		case 36: // home
		case 37: // left arrow
		case 38: // up arrow
		case 39: // right arrow
		case 40: // down arrow
		case 45: // insert
		case 91: // left window key
		case 92: // right window key
		case 93: // select key
		case 112: // F1
		case 113: // F2
		case 114: // F3
		case 115: // F4
		case 115: // F5
		case 117: // F6
		case 118: // F7
		case 119: // F8
		case 120: // F9
		case 121: // F10
		case 122: // F11
		case 123: // F12
		case 144: // num lock
		case 145: // scroll lock
			return false;
	}

	return true;
}

function groupFormManager() {
	var context = $("#createGroup");

	var updatePublicationValue = function() {
		var chec = $(".optionPublicationApproval", context);
		if ($(".optionsPublicationItem input:checked", context).val() == "1") {
			chec.show();
		} else {
			chec.hide();
		}
	};

	var updateCommentValue = function() {
		var chec = $(".optionCommentApproval", context);
		if ($(".optionsCommentItem input:checked", context).val() == "1") {
			chec.show();
		} else {
			chec.hide();
		}
	};

	var updateAdhesionValue = function() {
		var chec = $(".optionAdhesionApproval", context);
		if ($(".optionsAdhesionItem input:checked", context).val() == "1") {
			$(".optionsAdhesionItem", context)
				.first()
				.after($(".optionAdhesionApproval", context));
			$(".optionsInvitation", context).hide();
			chec.show();
		} else {
			$(".optionsInvitationItem", context)
				.first()
				.after($(".optionAdhesionApproval", context));
			$(".optionsInvitation", context).show();
			if ($(".optionsInvitationItem input:checked", context).val() == "1") {
				chec.show();
			} else {
				chec.hide();
			}
		}
	};

	var updateGroupTypeValue = function() {
		var val = $(".optionsGroupTypeItem input:checked", context).val();

		if (val == "1") {
			// groupe public sélectionné
			$(".optionAdhesionApproval input", context).prop("disabled", false);
			$("#adhesions1", context).prop("disabled", false);
			$("#invitations1", context).prop("disabled", false);
		} else if (val == "2") {
			// groupe privé sélectionné
			$(".optionAdhesionApproval input", context)
				.prop("checked", true)
				.prop("disabled", true);
			$("#adhesions1", context).prop("disabled", false);
			$("#invitations1", context).prop("disabled", false);
		} else {
			// groupe secret sélectionné
			$(".optionAdhesionApproval input", context).prop("disabled", true);
			$("#adhesions3", context).prop("checked", true);
			$("#adhesions1", context).prop("disabled", true);
			$("#invitations2", context).prop("checked", true);
			$("#invitations1", context).prop("disabled", true);
			updateAdhesionValue();
		}
	};

	updatePublicationValue();
	updateCommentValue();
	updateAdhesionValue();
	updateGroupTypeValue();

	$(".optionsPublicationItem input", context).change(updatePublicationValue);
	$(".optionsCommentItem input", context).change(updateCommentValue);
	$(".optionsAdhesionItem input", context).change(updateAdhesionValue);
	$(".optionsInvitationItem input", context).change(updateAdhesionValue);
	$(".optionsGroupTypeItem input", context).change(updateGroupTypeValue);

	$(".optionsPublicationItem", context)
		.first()
		.after($(".optionPublicationApproval", context));
	$(".optionsCommentItem", context)
		.first()
		.after($(".optionCommentApproval", context));
}

function commentManager(element) {
	var text = element.html(),
		maxLength = element.attr("maxlength");

	if (typeof text === "undefined") {
		return;
	}

	if (typeof maxLength !== typeof undefined && maxLength !== false) {
		var valueLength = element.val().length + element.val().split("\n").length - 1;

		$(".informationMaxLength")
			.show()
			.html(valueLength + " / " + maxLength);
	}

	element.on({
		"keyup change": function(e) {
			if (isKeyboardChange(e)) {
				return;
			}

			var text = element.html();

			// Reconstruction des éléments html en texte
			text = text
				.replace("<div>", "")
				.split("<div>")
				.join("\n")
				.split("<br></div>")
				.join("")
				.split("</div>")
				.join("")
				.split('<span style="font-size: 1.3em;">')
				.join("")
				.split("</span>")
				.join("");
			element.html(text);

			if (maxLength > 0) {
				information = element.parent().find(".informationMaxLength");
				submitBtn = element
					.parent()
					.parent()
					.find("#submitid");
				valueLength = element.val().length + element.val().split("\n").length - 1;
				information.html(valueLength + " / " + maxLength);
				if (valueLength > maxLength) {
					// on empeche le submit
					submitBtn.attr("disabled", "disabled");
				} else {
					//on reactive le submit
					submitBtn.removeAttr("disabled");
				}
			}
		},
	});
}

function modalConfirmManager(e, title, msg, callback, params, validText, type) {
	var modal = $("#overDiv"),
		modalWrapper = $("<div>"),
		modalTitle = $("<div>"),
		modalContent = $("<div>"),
		modalActions = $("<div>"),
		modalClose = $("<a>"),
		modalValidBtn = $("<a>"),
		modalCancelBtn = $("<a>");

	e.preventDefault();
	e.stopPropagation();

	if (!validText) {
		validText = "Valider";
	}

	if (typeof type !== "undefined") {
		modal.addClass(type);
	}

	modal.addClass("od_community");

	modalWrapper.addClass("modalWrapper");

	// Entete de la modal
	modalTitle.addClass("modalTitle").append(
		modalClose
			.addClass("modalClose")
			.text("×")
			.on("click", function() {
				modalConfirmClose();
			}),
		$("<span>").text(title)
	);

	// Contenu de la modal
	modalContent.addClass("modalContent").html(msg);

	// Footer de la modal
	modalActions.addClass("modalActions").append(
		modalValidBtn.addClass("actionValid").text(validText),
		modalCancelBtn
			.addClass("actionCancel")
			.text("Annuler")
			.on("click", function() {
				modalConfirmClose();
			})
	);

	modal.html("").append(modalWrapper.append(modalTitle, modalContent, modalActions));

	if ($(".modalWrapper").css("position") == "static" || modal.length == 0) {
		$("#overDiv")
			.removeClass()
			.html("&nbsp;");

		if (confirm(msg)) {
			if (typeof callback == "function") {
				callback.apply(modal, params);
			} else {
				eval(callback);
			}
		}
	}

	modalValidBtn.on("click", function() {
		if (typeof callback == "function") {
			callback.apply(modal, params);
		} else {
			eval(callback);
		}
	});

	setTimeout(function() {
		modal.find(".modalWrapper").height(Math.ceil(modal.find(".modalWrapper").height() / 2) * 2);
	}, 100);

	return false; // parce que c’est aussi appelé sur du onclick
}

function modalConfirmClose() {
	$("#overDiv")
		.html("")
		.removeClass();
}

function tooltipManager(container, isWithoutIcon, selector) {
	var tooltipClose = function() {
		$("#tooltip").remove();
	};

	var tooltipHide = function(e, self, isWithoutIcon) {
		if (typeof self == "undefined") {
			return;
		}

		if (!isWithoutIcon && self.text && $.trim(self.text()) != "") {
			return;
		}

		$("body > .arrowContent").remove();

		if (!self.attr("title")) {
			self.attr("title", self.data("title"));
		}

		if (self.data("tooltipTimeout")) {
			clearTimeout(self.data("tooltipTimeout"));
		}
	};
	var tooltipShow = function(e, self, isWithoutIcon) {
		var actionPositionT = self.offset().top - 30,
			actionPositionL = self.offset().left,
			actionText = self.attr("title"),
			gap = 10;

		if (!isWithoutIcon && self.find(".icons").length == 0) {
			return;
		}

		// On quitte la fonction si absence de title ou présence de texte
		if (typeof actionText == "undefined" || actionText == false) {
			return;
		}

		if (!isWithoutIcon && self.text().trim() != "") {
			return;
		}

		if (!isWithoutIcon) {
			actionPositionL = actionPositionL + self.innerWidth() / 2 - gap;
		}

		self.find("span").attr("title", "");

		if ($(this).data("tooltipTimeout")) {
			clearTimeout($(this).data("tooltipTimeout"));
		}

		// Suppression standard de la tooltip et remise du texte en attribut title du parent
		self.attr("title", "")
			.data("title", actionText)
			.data(
				"tooltipTimeout",
				setTimeout(function() {
					tooltipHide(self);
				}, 5000)
			);

		var parent = self.closest(".tooltipZone"),
			mousePositionL = (e ? e.pageX : 0) - (parent.offset() ? parent.offset().left : 0),
			tooltip = $("<div>")
				.attr("id", "tooltip")
				.addClass("arrowContent")
				.attr("style", "top: " + actionPositionT + "px; left: " + actionPositionL + "px")
				.html(actionText)
				.append($("<span>").addClass("arrowBlack"));

		if (parent.length > 0 && mousePositionL > parent.innerWidth() / 2) {
			tooltip
				.removeAttr("style")
				.attr(
					"style",
					"top: " +
						actionPositionT +
						"px; left: auto; right: " +
						($(window).width() - actionPositionL - 20) +
						"px"
				)
				.find(".arrowBlack")
				.addClass("reverse");
		}

		if (actionPositionT < 0) {
			tooltip
				.attr("style", "top: " + parseInt(actionPositionT + 70) + "px; left: " + actionPositionL + "px")
				.find(".arrowBlack")
				.addClass("flip");
		}

		tooltipClose();
		$("body").append(tooltip);

		// Sécurité, si la tooltip n'a pas été supprimée en 6 secondes, elle dégage.
		setTimeout(function() {
			if (typeof tooltip.remove == "function") {
				tooltip.remove();
			}
		}, 6000);
	};

	selector = selector ? selector : "a";

	container
		.delegate(selector, "mouseleave", function(e) {
			tooltipHide(e, $(this), isWithoutIcon);
		})
		.delegate(selector, "mouseenter", function(e) {
			tooltipShow(e, $(this), isWithoutIcon);
		});
}

function redirectTo(url, hasReason) {
	if (hasReason) {
		url += "&data=" + $("#modalReason").val();
	}
	window.location.href = url;
}

/**
 * Charge les statuts de la page suivante du mur d'activités
 *
 * @changelog 2020-12-18 [FIX] 2.13m (Faly) l'injection des résultats de paginations se faisait deux fois si on a 2 mure d'activité sur une même page (202012150006)
 *
 * @param  string  url         [description]
 * @param  integer nbPage      [description]
 * @param  integer currentPage [description]
 */
function goToNextWallPage(url, nbPage, currentPage, currentClic) {
	var filter = url.split("filter=")[1].split("&userId")[0],
		userId = url.split("userId=")[1].split("&groupId")[0],
		groupId = url.split("groupId=")[1].split("&elementId")[0],
		elementId = url.split("elementId=")[1].split("&elementType")[0],
		elementType = url.split("elementType=")[1].split("&type")[0],
		type = url.split("type=")[1].split("&limit")[0],
		limit = url.split("limit=")[1].split("&offset")[0],
		offset = parseInt(url.split("offset=")[1].split("&order")[0]) + parseInt(limit),
		order = url.split("order=")[1];

	currentPage++;
	$("#wall_loading").show();

	var wall = $(currentClic)
		.closest(".profile_wall")
		.find(".wWall");

	$.ajax({
		url: url,
		type: "GET",
		success: function(data) {
			var html = $(data)
				.find(".wWall")
				.children();
			pagerRenderOnSuccess(html, wall);

			if (currentPage < nbPage) {
				// On met à jour l'action
				$("#wall_pager a").attr({
					onclick:
						"goToNextWallPage('action-CommunityWallUpdate?" +
						"filter=" +
						filter +
						"&userId=" +
						userId +
						"&groupId=" +
						groupId +
						"&elementId=" +
						elementId +
						"&elementType=" +
						elementType +
						"&type=" +
						type +
						"&limit=" +
						limit +
						"&offset=" +
						offset +
						"&order=" +
						order +
						"', " +
						nbPage +
						", " +
						currentPage +
						", this)",
				});
			} else {
				$("#wall_pager").remove();
			}

			activityWallManager();
			callbackPager(html);
		},
		always: function() {
			$("#wall_loading").hide();
		},
	});
}

/**
 * Charge les statuts de la page suivante du mur d'activités
 *
 * @param  string  url         [description]
 * @param  integer nbPage      [description]
 */
function goToNextNotificationsWallPage(url, nbPage) {
	var currentPage = parseInt(url.split("page=")[1]) + 1;
	$("#wall_loading").show();

	$.get(url)
		.success(function(data) {
			var html = $(data).children();
			pagerRenderOnSuccess(html, ".wWall");

			if (currentPage <= nbPage) {
				// On met à jour l'action
				$("#wall_pager a").attr({
					onclick:
						"goToNextNotificationsWallPage('account-showAllNotifications?" +
						"page=" +
						currentPage +
						"', " +
						nbPage +
						")",
				});
			} else {
				$("#wall_pager").remove();
			}

			callbackPager(html);
		})
		.always(function() {
			$("#wall_loading").hide();
		});
}

/**
 * Ajoute les messages à la fin de la page courante
 *
 * @param  string  html     Les éléments à intégrer à la page
 * @param  string  element  L'élément dans lequel il faut insérer les données
 */
function pagerRenderOnSuccess(html, element) {
	$(element).append(html);
	$("div.aMessage").hover(
		function() {
			$(this).addClass("over");
		},
		function() {
			$(this).removeClass("over");
		}
	);
}

function banishment(event, label, elmentId) {
	event.preventDefault();
	var becauseOfBanishment = prompt(label);

	if (becauseOfBanishment != null) {
		var href = $("#member" + elmentId).attr("href");
		href += "&data=" + becauseOfBanishment;
		$("#member" + elmentId).attr("href", href);
		window.location.href = href;
	}
}

/**
 * variabilisation des données des membres pouvant être mentionnés
 */
function initTagData() {
	// tagsMembersIds, tagsMembersData, nbMaxTags et noResultsMsg sont définies dans le template main.html et initialisées en php

	// Description du comportement
	behaviorTag = [
		{
			mentions: tagsMembersIds,
			match: /\B@([a-zA-Z0-9áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ_\-']*)$/,
			search: function(term, callback) {
				term = cleanString(term);
				callback(
					$.map(this.mentions, function(mention) {
						var RegExpTerm = new RegExp(term, "i");
						if (
							tagsMembersData[mention]["firstname"] !== null &&
							tagsMembersData[mention]["firstname"] !== "undefined"
						) {
							(firstname = cleanString(tagsMembersData[mention]["firstname"].replace(/ /g, ""))),
								(lastname = cleanString(tagsMembersData[mention]["lastname"].replace(/ /g, "")));
						}

						return (
							(firstname.search(RegExpTerm) === 0 ? mention : null) ||
							(lastname.search(RegExpTerm) === 0 ? mention : null) ||
							((firstname + lastname).search(RegExpTerm) === 0 ? mention : null)
						);
					})
				);
			},
			template: function(id) {
				return (
					'<span class="personImg posLeft"><img src="' +
					tagsMembersData[id]["picture"] +
					'"/></span><span>' +
					tagsMembersData[id]["firstname"] +
					" " +
					tagsMembersData[id]["lastname"] +
					"</span>"
				);
			},
			replace: function(id) {
				var form = this.$el.hasClass("comment") ? this.$el.parent().parent() : this.$el.parent(),
					tagName = (tagsMembersData[id]["firstname"] + tagsMembersData[id]["lastname"]).replace(/ /g, ""),
					createInputTxt = true,
					divTags = form.find(".wall_tags");

				if (divTags.length === 0) {
					$("<div>")
						.addClass("wall_tags")
						.appendTo(form);
				}
				// Si un input hidden avec les mêmes valeurs existe déjà, il ne faut pas en créer un nouveau
				form.find(".tagName").each(function() {
					if ($(this).val() == id) {
						createInputTxt = false;
					}
				});

				if (createInputTxt) {
					$("<input>")
						.attr({
							type: "hidden",
							class: "tagName",
							name: "mentioned[]",
							value: id,
							tag: tagName,
						})
						.appendTo(form.find(".wall_tags"));
				}
				return "@" + tagName + " ";
			},
			index: 1,
		},
	];

	// Options
	optionsTag = {
		maxCount: nbMaxTags,
		noResultsMessage: noResultsMsg,
		placement: "absbottom",
	};
}

/**
 * Fonction permettant de tester si l'initialisation des variables de tag a été réalisée afin de gérer la rétro-compatibilité
 */
function isInitTag() {
	if (typeof tagsMembersIds == "undefined") {
		return false;
	}
	return true;
}

/**
 * Fonction retournant la chaîne passée en paramètre en minuscule et sans accents
 */
function cleanString(stringToCorrect) {
	var correctedString = stringToCorrect.toLowerCase();
	correctedString = correctedString.replace(/[áàâäãå]/, "a");
	correctedString = correctedString.replace(/[éèêë]/, "e");
	correctedString = correctedString.replace(/[íìîï]/, "i");
	correctedString = correctedString.replace(/[óòôöõ]/, "o");
	correctedString = correctedString.replace(/[úùûü]/, "u");
	correctedString = correctedString.replace(/[ýÿ]/, "y");
	correctedString = correctedString.replace(/[ç]/, "c");
	correctedString = correctedString.replace(/[ñ]/, "n");
	correctedString = correctedString.replace(/[æ]/, "ae");
	correctedString = correctedString.replace(/[œ]/, "oe");

	return correctedString;
}

/**
 * Fonction enregistrant un partage en Base
 */
function saveSharedElement(shareLink, elementType, elementId, elementUrl, elementTitle) {
	mentioned = "";
	$('div.sharePopup form input[name="mentioned[]"]').each(function() {
		if (mentioned != "") {
			mentioned += ",";
		}
		mentioned += $(this).val();
	});

	$.ajax({
		url: "/action-CommunityAction-postSharedElementStatus",
		type: "post",
		dataType: "json",
		data: {
			elementId: elementId,
			elementType: elementType,
			elementUrl: elementUrl,
			elementTitle: elementTitle,
			wall_message: $("div.sharePopup form textarea#wall_message").val(),
			"mentioned[]": mentioned,
		},
		success: function(result, status) {
			updateDisplayAfterSharing(
				shareLink,
				$(result.content.html).find(".sharingFeedbackMessage"),
				result.content.messageId
			);
		},
		complete: function(result, status) {
			$("div#overDiv a.modalClose").click();
		},
	});
}

/**
 * Fonction de mise à jour de l'interface après partage (compteur + feedback)
 */
function updateDisplayAfterSharing(shareLink, response, messageId) {
	if (shareLink.parents(".blocMessage .message_actions").length == 0) {
		// Cas général de partage
		var nbShares = $(".shareLinkNumber");
		shareLink
			.closest(".shareLink")
			.parent()
			.append(response);
		nbShares.text(parseInt(nbShares.text()) + 1);

		$(".sharingFeedbackMessage")
			.delay(4000)
			.fadeOut(500, function() {
				$(this).remove();
			});
	} else {
		// Cas où l'utilisateur partage un statut
		window.location.href =
			location.protocol +
			"//" +
			location.host +
			location.pathname +
			"?r=" +
			new Date().getTime() +
			"#message" +
			messageId;
	}
}

/**
 * Fonction d'initialisation du javascript de la popup de partage
 */
function initSharePopup() {
	if (isInitTag()) {
		// Gestion de la mention de personnes dans un message
		initTagData();
	}
	// Application au champ de saisie de la popup
	$("div.sharePopup textarea.comment").focus();
	$("div.sharePopup textarea.comment").textcomplete(behaviorTag, optionsTag);
}

/**
 * Gère le widget de recherche communautaire
 */
function widgetSearchCommunityManager() {
	var results = $("#searchCommunityResultsList");

	$(".searchCommunityResult", results).on("click", function() {
		var urlToGo = $(".searchCommunityResultLink a", this).attr("href");

		location.href = urlToGo;
	});

	var search = $("#searchCommunityResultsList > h3").text();

	// Récupération du terme recherché
	search = search.substr(search.indexOf('"') + 1);
	search = search.substr(0, search.indexOf('"'));

	// Récupération des divs contenant les résultats
	$("#searchCommunityResultsList > div").each(function() {
		var item = $(this).find(".searchCommunityResult");

		replaceTagInElement(search, item);
	});
}

/**
 * Efface la recherche en cours
 */
function cleanMessagingSearch() {
	$("#threadsForm #searchWord").val("");
	$("#threadsForm").submit();
}

/**
 * On remplace le terme recherché dans tous les textes présents dans les resultats
 *
 * @param search Terme recherché
 * @param item   Item recherché
 */
function replaceTagInElement(search, item) {
	item.children().each(function() {
		var element = $(this),
			regex = new RegExp(search, "igm"),
			regex2 = /<br>/gi,
			regex3 = /@br@/gi;

		// On remplace les <br> par @br@ puis on les remettra après
		element.html(element.html().replace(regex2, "@br@"));

		if (element.children().length > 0) {
			element.html(element.html().replace(regex3, "<br>"));
			replaceTagInElement(search, element);
		} else {
			element.html(element.html().replace(regex3, "<br>"));
			// On recherche un hastag ?
			if (search.charAt(0) == "#") {
				// Si c'est le cas on va rechercher le texte sans le #
				// Et les #'<strong class="highlight">' + search.substring(1) + '</strong>'
				var regex = new RegExp('#<strong class="highlight">' + search.substring(1) + "</strong>", "igm"),
					regex4 = new RegExp(search.substring(1), "igm");

				element.html(
					element.html().replace(regex4, '<strong class="highlight">' + search.substring(1) + "</strong>")
				);
				element.html(element.html().replace(regex, '<strong class="highlight">' + search + "</strong>"));
			} else {
				element.html(element.html().replace(regex, '<strong class="highlight">' + search + "</strong>"));
			}
		}
	});
}

// Chargement de toutes les notifications non lues avec restriction
function showNotReadNotifications() {
	var container = $("#notificationResume");

	$(document).on("click", ".showNotReadNotifications", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data") + "?all=1",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				$(".showNotReadNotifications", container).hide();
				$(".showAllNotifications", container).show();
			},
		});
	});
}

// Chargement de toutes les messages non lus avec restriction
function showMessagesNotRead() {
	var container = $("#messagesResume");

	$(document).on("click", ".showMessagesNotRead", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data") + "?all=1",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				$(".showMessagesNotRead", container).hide();
				$(".showAllMessages", container).show();
			},
		});
	});
}

// Ignorer tous les messages
function ignoreAllNotifications() {
	var container = $("#notificationResume");

	$(document).on("click", ".ignoreAllNotifications", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data"),
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				$(".manageMessage", container).remove();
				$(".notification_number").remove();
			},
		});
	});
}
// Ignorer un message particulier
function ignoreOneNotification() {
	var container = $("#notificationResume");

	$(document).on("click", ".ignoreOneNotification", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data"),
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				updateNotificationIndicator($(".notification_number"), 1);
				window.location.reload();
			},
		});
	});
}

// Ignorer tous les messages de la discussion instantanée
function ignoreAllMessages() {
	var container = $("#messagesResume");

	$(document).on("click", ".ignoreAllMessages", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data"),
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				$(".message_number").remove();
				$(".manageMessage", container).remove();
			},
		});
	});
}
// Ignorer un message particulier
function ignoreOneMessage() {
	var container = $("#messagesResume");

	$(document).on("click", "#messagesResume .ignoreOneMessage", function(e) {
		e.preventDefault();
		e.stopPropagation();

		$.ajax({
			url: $(this).attr("data"),
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$(".contentMessage", container).html(response);
				updateNotificationIndicator($(".message_number"), 1);
			},
		});
	});

	// Gère de le cas d’être sur la page de discussion et de cliquer dans les notifs non lues
	// vu que c’est une ancre nommée qui est changée dans l’url la page n’est pas rechargée.
	$(document).on("click", "#messagesResume .wallNotification", function(e) {
		var message = $(this);
		if (message.hasClass("unread")) {
			updateNotificationIndicator($(".message_number"), 1);
			message.addClass("read").removeClass("unread");
			message.find(".action").remove();
		}
	});
}

//Mis à jour du nombre de notification
function updateNotificationIndicator(value, qty) {
	value.html(value.html() - qty);
	if (value.html() == 0) {
		value.remove();
		$(".manageMessage").remove(); // la modale
	}
}

/**
 * Suppression d'un gpe sur la gestion specifique des groupes
 * la suppresion se fait par ajax account-delgroupnotify
 */
function deleteSpecificSettings(id) {
	window.location = "account-delgroupnotify-" + id;
}

/**
 *Affiche le popup pour ajouter un groupe dans la liste à configurer
 */
$(document).ready(function() {
	$(document).on("click", ".deleteThread", function(e) {
		var id = $(this)
			.attr("rel")
			.split("deleteGroup-")[1];

		modalConfirmManager(
			e,
			"Suppression du réglage spécifique",
			"Êtes-vous sûr de vouloir supprimer le réglage spécifique pour ce groupe ?",
			deleteSpecificSettings,
			[id],
			"Supprimer"
		);
	});
	$(document).on("click", "#groupAddSpecificConfig", function(e) {
		e.preventDefault();

		// Un groupe à configuer ou à lister dans la lsite des gpes qui n'a pas de configuration , par ajax
		$.ajax({
			url: $(this).attr("href") + "?new=1",
			type: "get",
			dataType: "html",
			success: function(response, textStatus, xhr) {
				$("#groupSpecificAdd").css({
					position: "relative",
					"z-index": 20,
				});
				$("#result").remove();
				$("#groupSpecificAdd").append(
					$("<div>")
						.attr({
							id: "result",
						})
						.addClass("modalAddContact")
						.html(
							$(response)
								.find("#community_group")
								.html()
						)
						.prepend(
							$("<div>")
								.attr({
									id: "closeResult",
								})
								.append(
									$("<span>")
										.addClass("icons")
										.text("X"),
									$("<div>").addClass("arrowTop icons")
								)
						)
				);
				$("#tabsSearch li:first").addClass("active_section");
			},
		});
	});
});

/**
 * Fonction lancée à chaque changement de statut des checkbox
 * Affiche ou masque les zones de notifications en fonction de la checkbox "réception mail"
 **/
function updateNotificationsManager() {
	// si on est sur la page de gestion de notifications
	if ($("#allowedgroupnotif").length > 0) {
		$("#allowedemailnotif").change(function() {
			if ($("#allowedemailnotif").attr("checked")) {
				showGlobalNotifications();
			} else {
				hideGlobalNotifications();
			}
			showNotificationsManager();
		});

		// changement état de la case à cocher wall
		$("#allowedactivitywallnotif").change(function() {
			if ($("#allowedactivitywallnotif").attr("checked")) {
				$("#divallowedactivitywalltypenotif").show();
				$("#allowedactivitywalltypenotifinstant").attr("checked", "checked");
			} else {
				$("#divallowedactivitywalltypenotif").hide();
				$("#allowedactivitywalltypenotifnever").attr("checked", "checked");
			}
		});

		// changement état de la case à cocher groupes
		$("#allowedgroupnotif").change(function() {
			if ($("#allowedgroupnotif").attr("checked")) {
				$("#divallowedgrouptypenotif").show();
				$(".divallownotifmygroup").show();
				$("#groupsSpecificSettings").show();
				$("#allowedgrouptypenotifinstant").attr("checked", "checked");
				$("#divallownotifmygroup").show();
			} else {
				$("#divallowedgrouptypenotif").hide();
				$(".divallownotifmygroup").hide();
				$("#groupsSpecificSettings").hide();
				$("#allowedgrouptypenotifnever").attr("checked", "checked");
				$("#divallownotifmygroup").hide();
			}
		});

		// changement état de la case à cocher message
		$("#allowedmessagingnotif").change(function() {
			if ($("#allowedmessagingnotif").attr("checked")) {
				$("#divallowedmessagingtypenotif").show();
				$("#allowedmessagingtypenotifinstant").attr("checked", "checked");
			} else {
				$("#divallowedmessagingtypenotif").hide();
				$("#allowedmessagingtypenotifnever").attr("checked", "checked");
			}
		});

		// changement état de la case à cocher relations
		$("#allowedrelationshipnotif").change(function() {
			if ($("#allowedrelationshipnotif").attr("checked")) {
				$("#divallowedrelationshiptypenotif").show();
				$("#allowedrelationshiptypenotifinstant").attr("checked", "checked");
			} else {
				$("#divallowedrelationshiptypenotif").hide();
				$("#allowedrelationshiptypenotifnever").attr("checked", "checked");
			}
		});

		$(document).on("click", ".groupLabel", function(e) {
			e.preventDefault();
			var uri = $(this).attr("href");

			// Un groupe à configuer ou à lister dans la lsite des gpes qui n'a pas de configuration , par ajax
			$.ajax({
				url: uri,
				type: "GET",
				dataType: "html",
				beforeSend: function(response, textStatus, xhr) {
					var groupId = uri.substring(uri.indexOf("account-groupnotify-"));
					$("input[name=hiddenRedirect]").attr("value", "0");
					$("input[name=hiddenDelete]").attr("value", "0");
					$("input[name=hiddenGroup]").attr("value", groupId);
				},
				complete: function(response, textStatus, xhr) {
					window.location.reload();
				},
			});
		});

		$("#saveid").click(function() {
			$("input[name=hiddenRedirect]").attr("value", "1");
		});
	}
}

/**
 * Fonction lancée au chargement de la page
 * Affiche ou masque les zones de notifications en fonction de la checkbox "réception mail"
 **/
function showNotificationsManager() {
	// si on est sur la page de gestion de notifications
	if ($("#allowedgroupnotif").length > 0) {
		if ($("#allowedemailnotif").attr("checked")) {
			showGlobalNotifications();
		} else {
			hideGlobalNotifications();
		}

		// vérification notifications wall
		if ($("#allowedactivitywallnotif").attr("checked")) {
			$("#divallowedactivitywalltypenotif").show();
		} else {
			$("#divallowedactivitywalltypenotif").hide();
		}

		// vérification notifications groups
		if ($("#allowedgroupnotif").attr("checked")) {
			$("#divallowedgrouptypenotif").show();
			$(".divallownotifmygroup").show();
			$("#groupsSpecificSettings").show();
			$("#divallownotifmygroup").show();
		} else {
			$("#divallowedgrouptypenotif").hide();
			$(".divallownotifmygroup").hide();
			$("#groupsSpecificSettings").hide();
			$("#divallownotifmygroup").hide();
		}

		// vérification notifications messages
		if ($("#allowedmessagingnotif").attr("checked")) {
			$("#divallowedmessagingtypenotif").show();
		} else {
			$("#divallowedmessagingtypenotif").hide();
		}

		// vérification notifications relation
		if ($("#allowedrelationshipnotif").attr("checked")) {
			$("#divallowedrelationshiptypenotif").show();
		} else {
			$("#divallowedrelationshiptypenotif").hide();
		}
	}
}

/**
 * Affiche les éléments de notifications globaux
 **/
function showGlobalNotifications() {
	$("#activityWallNotifications").show();
	$("#groupsNotifications").show();
	$("#messagingNotifications").show();
	$("#relationshipNotifications").show();
	$("#groupAddSpecificConfig").show();
	$("#groupsSpecificSettings").show();
	$("#divallownotifmygroup").show();

	$("#allowedactivitywallnotif").attr("checked", "checked");
	$("#allowedgroupnotif").attr("checked", "checked");
	$("#allowedmessagingnotif").attr("checked", "checked");
	$("#allowedrelationshipnotif").attr("checked", "checked");
}

/**
 * Cache les éléments de notifications globaux
 **/
function hideGlobalNotifications() {
	$("#activityWallNotifications").hide();
	$("#groupsNotifications").hide();
	$("#messagingNotifications").hide();
	$("#relationshipNotifications").hide();
	$("#groupsSpecificSettings").hide();
	$("#divallownotifmygroup").hide();
	$("#groupAddSpecificConfig").hide();
	$("#allowedactivitywallnotif").removeAttr("checked");
	$("#allowedgroupnotif").removeAttr("checked");
	$("#allowedmessagingnotif").removeAttr("checked");
	$("#allowedrelationshipnotif").removeAttr("checked");
	$("#allowedrelationshiptypenotifnever").attr("checked", "checked");
	$("#allowedmessagingtypenotifnever").attr("checked", "checked");
	$("#allowedgrouptypenotifnever").attr("checked", "checked");
	$("#allowedactivitywalltypenotifnever").attr("checked", "checked");
}

/**
 * Vérifie que toutes les checkboxes de notifications sont décochées
 *
 * @return boolean
 **/
function checkAllBoxesUnchecked() {
	var groupsList = $(".groupTableBody"),
		wallChecked = $("#allowedactivitywallnotif").attr("checked"),
		groupChecked = $("#allowedgroupnotif").attr("checked"),
		messagingChecked = $("#allowedmessagingnotif").attr("checked"),
		relationChecked = $("#allowedrelationshipnotif").attr("checked");

	return groupsList.length == 0 && !wallChecked && !groupChecked && !messagingChecked && !relationChecked;
}
