$(function() { $(document).on("click", "[data-ad-favorite]", function(event) { event.preventDefault(); event.stopPropagation(); const button = $(this); const publicId = button.data("ad-id"); if (button.prop("disabled") || button.data("loading")) { return; } if (!publicId) { popZ("Não foi possível identificar este anúncio.", "warning"); return; } setFavoriteButtonsLoading(publicId, true); $.ajax({ type: "POST", url: "/api/favorito", dataType: "json", data: { public_id: publicId }, success: function(response) { handleFavoriteResponse(publicId, response); }, error: function(jqXhr) { handleFavoriteResponse(publicId, jqXhr.responseJSON || {}); }, complete: function() { setFavoriteButtonsLoading(publicId, false); } }); }); }); function setFavoriteButtonsLoading(publicId, isLoading) { $('[data-ad-favorite][data-ad-id="' + publicId + '"]') .data("loading", isLoading) .prop("disabled", isLoading) .attr("aria-busy", isLoading ? "true" : null); } function handleFavoriteResponse(publicId, response) { switch (response.result) { case "favorite_added": updateFavoriteButtons(publicId, true); popZ("Anúncio salvo nos favoritos.", "success"); break; case "favorite_removed": updateFavoriteButtons(publicId, false); popZ("Anúncio removido dos favoritos.", "success"); removeFavoriteCardIfNeeded(publicId); break; case "auth_required": popZ("Entre na sua conta para salvar anúncios nos favoritos.", "warning"); break; case "ad_not_found": popZ("Este anúncio não está mais disponível.", "warning"); break; case "invalid_ad_favorite": popZ("Não foi possível identificar este anúncio.", "warning"); break; default: popZ("Não foi possível atualizar seus favoritos. Tente novamente.", "error"); break; } } function updateFavoriteButtons(publicId, isFavorite) { const buttons = $('[data-ad-favorite][data-ad-id="' + publicId + '"]'); const heart = isFavorite ? "♥" : "♡"; buttons .toggleClass("is-favorite", isFavorite) .attr("aria-pressed", isFavorite ? "true" : "false"); buttons.each(function() { const button = $(this); if (button.hasClass("ad-favorite-detail")) { button.text(heart + " " + (isFavorite ? "Remover dos favoritos" : "Salvar nos favoritos")); return; } button.text(heart); }); } function removeFavoriteCardIfNeeded(publicId) { const favoritesPanel = $('[data-dashboard-panel="favorites"]'); if (!favoritesPanel.hasClass("active")) { return; } favoritesPanel.find('[data-ad-favorite][data-ad-id="' + publicId + '"]') .closest(".card") .fadeOut(160, function() { $(this).remove(); }); }