Server Error
Could not load products. Please try again.
Error: ${error.message}
`;
});
}
// Function to close popup
window.closePopup = function() {
if (!isPopupOpen) return;
isPopupOpen = false;
popupOverlay.style.display = 'none';
document.body.style.overflow = ''; // Restore scrolling
// iOS specific: Restore body styles
document.body.style.position = '';
document.body.style.width = '';
document.body.style.height = '';
// Clear PopupNav stack when closing popup
if (window.PopupNav && typeof window.PopupNav.clear === 'function') {
window.PopupNav.clear();
}
// Reset category ID to 0 when popup is closed
sessionStorage.setItem("category_id", JSON.stringify({ selected_category_id: 0 }));
// Reset cart quantity to 1 when popup is closed
try {
sessionStorage.setItem("cartQuantity", "1");
} catch (_) {}
// ✅ Clear profile selection when shop closes
try {
sessionStorage.removeItem("selectedProfile");
console.log('🗑️ Cleared profile selection on shop close');
} catch (_) {}
// Clear shopDataPopup global object
if (typeof shopDataPopup !== 'undefined') {
shopDataPopup.selectedProfileId = null;
shopDataPopup.recipientName = null;
shopDataPopup.profileImage = null;
shopDataPopup.meta = null;
console.log('🗑️ Cleared shopDataPopup on shop close');
}
// Dispatch custom shop closed event for candles refresh
console.log('🏪 Shop popup closed - dispatching shopClosed event');
const shopClosedEvent = new CustomEvent('shopClosed', {
bubbles: true,
detail: { timestamp: Date.now() }
});
document.dispatchEvent(shopClosedEvent);
}
// ✅ Clear profile selection on page refresh/unload
window.addEventListener('beforeunload', function() {
try {
sessionStorage.removeItem('selectedProfile');
console.log('🔄 Cleared profile selection on page refresh/close');
} catch (_) {}
// Clear shopDataPopup global object
if (typeof shopDataPopup !== 'undefined') {
shopDataPopup.selectedProfileId = null;
shopDataPopup.recipientName = null;
shopDataPopup.profileImage = null;
shopDataPopup.meta = null;
}
});
// Event listeners for open buttons
document.addEventListener('click', function(e) {
if (e.target.closest('.open-shop-popup') || e.target.closest('.shop')) {
e.preventDefault();
openPopup();
}
});
// Close buttons (handle both layout and dynamically loaded ones)
if (closeButton) {
closeButton.addEventListener('click', closePopup);
}
document.addEventListener('click', function(e) {
if (e.target.closest('.shop-popup-close')) {
e.preventDefault();
closePopup();
}
});
// Close on overlay click
if (popupOverlay) {
popupOverlay.addEventListener('click', function(e) {
if (e.target === popupOverlay) {
closePopup();
}
});
}
// Close on Escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && isPopupOpen) {
closePopup();
}
});
// Prevent event propagation issues
document.addEventListener('click', function(e) {
if (isPopupOpen && e.target.closest('.shop-popup-content')) {
e.stopPropagation();
}
});
function initDetailColorSelection() {
console.log('🎨 Setting up detail page color selection...');
// Color selection is handled via global event delegation
// No additional setup needed
}
function setupQuantityDropdown() {
console.log('🎯 Setting up quantity dropdown with FIXED behavior...');
const quantityToggle = document.getElementById('quantityToggle');
const quantityDropdown = document.getElementById('quantityDropdown');
const quantityOptions = document.querySelectorAll('.quantity-option');
const quantityText = document.querySelector('.quantity-text');
const priceAmount = document.getElementById('priceAmount');
console.log('Dropdown elements found:', {
toggle: quantityToggle,
dropdown: quantityDropdown,
options: quantityOptions.length,
text: quantityText
});
if (!quantityToggle || !quantityDropdown || !quantityText) {
console.log('❌ Quantity dropdown elements not found, skipping setup');
return;
}
// Get unit price
const unitPrice = priceAmount ? parseFloat(priceAmount.getAttribute('data-unit-price')) || 0 : 0;
console.log('💰 Unit price:', unitPrice);
// Initialize - DON'T reset to 1, keep current value
let currentQuantity = parseInt(quantityText.textContent) || 1;
quantityDropdown.classList.remove('show');
// Remove any existing selected states
quantityOptions.forEach(opt => {
opt.classList.remove('selected');
});
// Set initial selected state based on current quantity
quantityOptions.forEach(opt => {
if (parseInt(opt.getAttribute('data-value')) === currentQuantity) {
opt.classList.add('selected');
}
});
// Function to update prices
function updatePrices(quantity) {
const totalProductPrice = unitPrice * quantity;
console.log('🔄 Updating prices:', {
quantity: quantity,
unitPrice: unitPrice,
totalProductPrice: totalProductPrice
});
// Update product price display
if (priceAmount) {
const formattedPrice = formatPrice(totalProductPrice);
priceAmount.textContent = formattedPrice;
// Add animation
priceAmount.classList.add('price-update');
setTimeout(() => {
priceAmount.classList.remove('price-update');
}, 500);
console.log('✅ Product price updated to:', formattedPrice);
}
// Store quantity for persistence
const productContainer = document.querySelector('.product-details-container, [data-product-id]');
const productId = productContainer ? productContainer.getAttribute('data-product-id') : '';
if (productId) {
sessionStorage.setItem(`product_${productId}_selected_quantity`, quantity.toString());
}
}
// Price formatting function
function formatPrice(price) {
return new Intl.NumberFormat('hu-HU', {
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(price) + ' Ft';
}
// Toggle dropdown - DON'T reset quantity
quantityToggle.addEventListener('click', function(event) {
event.stopPropagation();
event.preventDefault();
console.log('📱 Dropdown toggled, current quantity:', currentQuantity);
// Just toggle visibility, don't change quantity
quantityDropdown.classList.toggle('show');
quantityToggle.classList.toggle('active');
});
// Handle quantity selection
quantityOptions.forEach(option => {
option.addEventListener('click', function(event) {
event.stopPropagation();
const newQuantity = parseInt(this.getAttribute('data-value'));
console.log('🔢 Quantity selected:', newQuantity);
// Update current quantity
currentQuantity = newQuantity;
// Update displayed text
quantityText.textContent = newQuantity;
// Update selected state - remove from all, add to clicked
quantityOptions.forEach(opt => {
opt.classList.remove('selected');
});
this.classList.add('selected');
// Close dropdown
quantityDropdown.classList.remove('show');
quantityToggle.classList.remove('active');
// Update prices based on new quantity
updatePrices(newQuantity);
console.log('✅ Quantity updated to:', newQuantity);
});
});
// Close dropdown on outside click - DON'T reset quantity
document.addEventListener('click', function(event) {
if (!quantityToggle.contains(event.target) && !quantityDropdown.contains(event.target)) {
console.log('📤 Dropdown closed (outside click), keeping quantity:', currentQuantity);
quantityDropdown.classList.remove('show');
quantityToggle.classList.remove('active');
// DON'T reset the quantity text - keep the selected value
}
});
// Prevent dropdown close when clicking inside dropdown
quantityDropdown.addEventListener('click', function(e) {
e.stopPropagation();
});
// Restore saved quantity on page load
const productContainer = document.querySelector('.product-details-container, [data-product-id]');
const productId = productContainer ? productContainer.getAttribute('data-product-id') : '';
const savedQuantity = productId ? sessionStorage.getItem(`product_${productId}_selected_quantity`) : null;
if (savedQuantity) {
const quantity = parseInt(savedQuantity);
if (quantity > 0 && quantity <= 5) {
console.log('🔄 Restoring saved quantity:', quantity);
currentQuantity = quantity;
quantityText.textContent = quantity;
// Update selected option in dropdown
quantityOptions.forEach(opt => {
if (parseInt(opt.getAttribute('data-value')) === quantity) {
opt.classList.add('selected');
}
});
// Update prices for restored quantity
updatePrices(quantity);
}
} else {
// Initialize with current quantity (not necessarily 1)
updatePrices(currentQuantity);
}
console.log('✅ Fixed quantity dropdown initialized with quantity:', currentQuantity);
}
// Personalize button function (keep this for the HTML onclick)
function showPopupMemorialCustomization(productId) {
console.log('showPopupMemorialCustomization called with productId:', productId);
// Use popup flow
if (window.parent && window.parent !== window && typeof window.parent.showPopupMemorialCustomization === 'function') {
window.parent.showPopupMemorialCustomization(productId);
} else {
console.log('Parent function not available, using direct navigation');
// Fallback: navigate directly
const memorialUrl = '/pl-de/products/product/popup-memorial-customization?id=' + productId;
window.location.href = memorialUrl;
}
}
function setupCartInteractions() {
// Initialize cart total
updateCartTotal();
var popupBodyEl = document.getElementById('shop-popup-body');
var isCheckoutPage = popupBodyEl && popupBodyEl.querySelector('.add-card-option') !== null;
if (isCheckoutPage) {
console.log('On checkout page, skipping back button binding in setupCartInteractions');
return;
}
// Remove item buttons
var removeItemBtns = document.querySelectorAll('.remove-item-btn');
removeItemBtns.forEach(function(btn) {
btn.addEventListener('click', function() {
if (confirm('Are you sure you want to remove this item?')) {
this.closest('.cart-item').remove();
updateCartTotal();
}
});
});
}
function updateCartTotal() {
console.log('🔄 Updating cart total...');
// Read quantity from the visible quantity span
var quantityDisplay = document.querySelector('.quantity-display');
var quantity = quantityDisplay ? parseInt(quantityDisplay.textContent, 10) || 1 : 1;
// Parse unit price from the cart product price element
var unitPriceEl = document.querySelector('.cart-product-price');
var unitPrice = 0;
if (unitPriceEl) {
var raw = unitPriceEl.textContent || '';
// Handle formats like "39,96 Ft" or "39.96 Ft"
var cleaned = raw.replace(/[^0-9,.]/g, '');
var normalized = cleaned.replace(',', '.');
unitPrice = parseFloat(normalized) || parseFloat(unitPriceEl.getAttribute('data-unit-price')) || currentProduct.price || 20000;
} else {
// Fallback to currentProduct.price or default
unitPrice = currentProduct.price || 20000;
console.warn('⚠️ Unit price element not found, using fallback:', unitPrice);
}
// Calculate total
var total = quantity * unitPrice;
// Update the total display in the summary section (Összesen)
var summaryAmount = document.querySelector('.summary-amount');
if (summaryAmount) {
summaryAmount.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft';
}
// Update the main cart total at the top
var mainTotal = document.querySelector('.product-title-price-card .price-amount');
if (mainTotal) {
mainTotal.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft';
}
// Update totalAmount for checkout
var totalAmountEl = document.getElementById('totalAmount');
if (totalAmountEl) {
totalAmountEl.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft';
totalAmountEl.setAttribute('data-raw-amount', total);
}
console.log('✅ Cart total updated:', { quantity, unitPrice, total });
}
// Global function to return to checkout from success/failed payment
window.updateCartTotal = updateCartTotal; // Expose globally
document.addEventListener('click', function(e) {
var closeBtn = e.target.closest('.shop-popup-close');
if (closeBtn) {
try { sessionStorage.removeItem('selectedProfile'); } catch (_) {}
}
});
// Ensure going back from product detail to products list shows ONLY the search bar
// Remove any selected profile right before navigating back
document.addEventListener('click', function(e) {
var backBtn = e.target.closest('.back-to-products-btn');
if (backBtn) {
try { sessionStorage.removeItem('selectedProfile'); } catch (_) {}
}
});
});