/**
* NewFoxZen - Main JavaScript
*/
const USD_TO_INR = 83.50;
let currentCurrency = 'INR';
document.addEventListener('DOMContentLoaded', function() {
// Initialize Lucide icons
lucide.createIcons();
// Initialize components
initNavbar();
initMobileMenu();
initSearch();
initCart();
initAnimations();
initCurrencySwitcher();
// Apply saved currency on load
applyCurrency(currentCurrency);
});
/**
* Navbar scroll effect
*/
function initNavbar() {
const navbar = document.getElementById('navbar');
if (!navbar) return;
let lastScroll = 0;
window.addEventListener('scroll', () => {
const currentScroll = window.pageYOffset;
if (currentScroll > 50) {
navbar.classList.add('scrolled');
} else {
navbar.classList.remove('scrolled');
}
lastScroll = currentScroll;
});
}
/**
* Mobile menu toggle
*/
function initMobileMenu() {
const menuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');
if (!menuBtn || !mobileMenu) return;
menuBtn.addEventListener('click', () => {
mobileMenu.classList.toggle('active');
const icon = menuBtn.querySelector('svg');
if (mobileMenu.classList.contains('active')) {
icon.setAttribute('data-lucide', 'x');
} else {
icon.setAttribute('data-lucide', 'menu');
}
lucide.createIcons();
});
}
/**
* Search modal
*/
function initSearch() {
const searchBtn = document.getElementById('searchBtn');
const searchModal = document.getElementById('searchModal');
const searchClose = document.getElementById('searchClose');
if (!searchBtn || !searchModal || !searchClose) return;
searchBtn.addEventListener('click', () => {
searchModal.classList.add('active');
searchModal.querySelector('input').focus();
});
searchClose.addEventListener('click', () => {
searchModal.classList.remove('active');
});
searchModal.addEventListener('click', (e) => {
if (e.target === searchModal) {
searchModal.classList.remove('active');
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && searchModal.classList.contains('active')) {
searchModal.classList.remove('active');
}
});
}
/**
* Cart drawer
*/
function initCart() {
const cartBtn = document.getElementById('cartBtn');
const cartDrawer = document.getElementById('cartDrawer');
const cartClose = document.getElementById('cartClose');
const cartOverlay = document.getElementById('cartOverlay');
if (!cartBtn || !cartDrawer || !cartClose || !cartOverlay) return;
function openCart() {
cartDrawer.classList.add('active');
cartOverlay.classList.add('active');
document.body.style.overflow = 'hidden';
}
function closeCart() {
cartDrawer.classList.remove('active');
cartOverlay.classList.remove('active');
document.body.style.overflow = '';
}
cartBtn.addEventListener('click', openCart);
cartClose.addEventListener('click', closeCart);
cartOverlay.addEventListener('click', closeCart);
// Load cart items
loadCartItems();
// Add to cart functionality
document.querySelectorAll('.add-to-cart').forEach(btn => {
btn.addEventListener('click', function() {
const productId = this.dataset.productId;
const quantity = document.querySelector('.quantity-input')?.value || 1;
addToCart(productId, quantity);
});
});
// Quick add to cart
document.querySelectorAll('.quick-add-cart').forEach(btn => {
btn.addEventListener('click', function() {
const productId = this.dataset.productId;
addToCart(productId, 1);
});
});
}
/**
* Load cart items via AJAX
*/
function loadCartItems() {
const cartItems = document.getElementById('cartItems');
const cartTotal = document.getElementById('cartTotal');
const cartBadge = document.getElementById('cartBadge');
if (!cartItems) return;
fetch('api/cart-api.php?action=get')
.then(res => res.json())
.then(data => {
if (data.items.length === 0) {
cartItems.innerHTML = `
`;
if (cartBadge) cartBadge.style.display = 'none';
} else {
let html = '';
let total = 0;
data.items.forEach(item => {
const subtotal = parseFloat(item.price) * item.quantity;
total += subtotal;
const currency = currentCurrency;
const priceDisplay = currency === 'INR'
? '₹' + (subtotal * USD_TO_INR).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
: '$' + subtotal.toFixed(2);
html += `
${item.name}
Qty: ${item.quantity}
${priceDisplay}
`;
});
cartItems.innerHTML = html;
if (cartTotal) {
cartTotal.textContent = currentCurrency === 'INR'
? '₹' + (total * USD_TO_INR).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
: '$' + total.toFixed(2);
}
if (cartBadge) {
cartBadge.textContent = data.count;
cartBadge.style.display = 'flex';
}
lucide.createIcons();
}
})
.catch(err => console.error('Cart load error:', err));
}
/**
* Add item to cart
*/
function addToCart(productId, quantity = 1) {
const formData = new FormData();
formData.append('action', 'add');
formData.append('product_id', productId);
formData.append('quantity', quantity);
fetch('api/cart-api.php', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => {
if (data.success) {
showToast('Added to cart!', 'success');
loadCartItems();
// Update cart badge
const cartBadge = document.getElementById('cartBadge');
if (cartBadge) {
cartBadge.textContent = data.cart_count;
cartBadge.style.display = 'flex';
}
} else {
showToast('Failed to add item', 'error');
}
})
.catch(err => {
console.error('Add to cart error:', err);
showToast('Failed to add item', 'error');
});
}
/**
* Remove from cart
*/
function removeFromCart(productId) {
const formData = new FormData();
formData.append('action', 'remove');
formData.append('product_id', productId);
fetch('api/cart-api.php', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => {
if (data.success) {
showToast('Item removed', 'info');
loadCartItems();
}
})
.catch(err => console.error('Remove from cart error:', err));
}
/**
* Toast notifications
*/
function showToast(message, type = 'info') {
const container = document.getElementById('toastContainer');
if (!container) return;
const icons = {
success: 'check-circle',
error: 'x-circle',
info: 'info'
};
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
${message}
`;
container.appendChild(toast);
lucide.createIcons();
// Auto remove
setTimeout(() => {
toast.style.animation = 'slideIn 300ms ease reverse';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
/**
* Scroll animations
*/
function initAnimations() {
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-in');
}
});
}, observerOptions);
document.querySelectorAll('.feature-card, .category-card, .testimonial-card').forEach(el => {
observer.observe(el);
});
}
/**
* Filter products
*/
function filterProducts(category) {
const cards = document.querySelectorAll('.product-card');
const pills = document.querySelectorAll('.filter-pill');
pills.forEach(p => p.classList.remove('active'));
event.target.classList.add('active');
cards.forEach(card => {
const cardCategory = card.dataset.category;
if (category === 'all' || cardCategory === category) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
}
/**
* Sort products
*/
function sortProducts(sortBy) {
const grid = document.querySelector('.products-grid');
const cards = Array.from(grid.querySelectorAll('.product-card'));
cards.sort((a, b) => {
const priceA = parseFloat(a.dataset.price);
const priceB = parseFloat(b.dataset.price);
const nameA = a.dataset.name.toLowerCase();
const nameB = b.dataset.name.toLowerCase();
switch(sortBy) {
case 'price-low':
return priceA - priceB;
case 'price-high':
return priceB - priceA;
case 'name':
return nameA.localeCompare(nameB);
default:
return 0;
}
});
cards.forEach(card => grid.appendChild(card));
}
/**
* Quantity selector
*/
document.addEventListener('click', function(e) {
if (e.target.matches('.quantity-btn')) {
const input = e.target.parentElement.querySelector('input');
const current = parseInt(input.value) || 1;
if (e.target.dataset.action === 'increase') {
input.value = current + 1;
} else if (e.target.dataset.action === 'decrease' && current > 1) {
input.value = current - 1;
}
}
});
/**
* Admin: Delete confirmation
*/
function confirmDelete(message = 'Are you sure?') {
return confirm(message);
}
/**
* Currency Switcher
*/
function initCurrencySwitcher() {
const currencyBtn = document.getElementById('currencyBtn');
const currencyDropdown = document.getElementById('currencyDropdown');
const currencyLabel = document.getElementById('currencyLabel');
if (!currencyBtn || !currencyDropdown) return;
// Toggle dropdown
currencyBtn.addEventListener('click', (e) => {
e.stopPropagation();
currencyDropdown.classList.toggle('show');
});
// Handle currency selection
document.querySelectorAll('.currency-option').forEach(option => {
option.addEventListener('click', (e) => {
e.preventDefault();
const currency = option.dataset.currency;
// Send to server
fetch(`api/settings-api.php?action=set-currency`, {
method: 'POST',
body: new URLSearchParams({ currency })
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log('Currency changed to:', currency);
currentCurrency = currency;
// Update label immediately
if (currencyLabel) {
currencyLabel.textContent = currency;
}
// Apply currency conversion without reload
applyCurrency(currency);
currencyDropdown.classList.remove('show');
}
});
});
});
// Close on outside click
document.addEventListener('click', () => {
currencyDropdown.classList.remove('show');
});
}
/**
* Theme Switcher
*/
function initThemeSwitcher() {
const themeBtn = document.getElementById('themeBtn');
const themeDropdown = document.getElementById('themeDropdown');
if (!themeBtn || !themeDropdown) return;
// Toggle dropdown
themeBtn.addEventListener('click', (e) => {
e.stopPropagation();
themeDropdown.classList.toggle('show');
});
// Handle theme selection
document.querySelectorAll('.theme-option').forEach(option => {
option.addEventListener('click', (e) => {
e.preventDefault();
const theme = option.dataset.theme;
// Send to server
fetch(`api/settings-api.php?action=set-theme`, {
method: 'POST',
body: new URLSearchParams({ theme })
})
.then(res => res.json())
.then(data => {
if (data.success) {
// Update active state
document.querySelectorAll('.theme-option').forEach(opt => opt.classList.remove('active'));
option.classList.add('active');
// Reload to apply theme
location.reload();
}
});
themeDropdown.classList.remove('show');
});
});
// Close on outside click
document.addEventListener('click', () => {
themeDropdown.classList.remove('show');
});
}
/**
* Apply currency conversion to all prices on page
*/
function applyCurrency(currency) {
currentCurrency = currency;
console.log('Applying currency:', currency);
// Update all prices
document.querySelectorAll('.price-current, .price-original').forEach(el => {
const text = el.textContent;
console.log('Original price:', text);
// Get the numeric value, handling both comma-separated and plain formats
const cleanText = text.replace(/,/g, '').replace(/[^\d.]/g, '');
const price = parseFloat(cleanText);
if (isNaN(price)) return;
// Determine current display format
const currentIsInr = text.includes('₹');
const currentIsUsd = text.includes('$');
// Calculate USD base price
let usdPrice;
if (currentIsInr) {
// If showing INR, convert back to USD first
usdPrice = price / USD_TO_INR;
} else {
// Already USD
usdPrice = price;
}
// Display in requested currency
if (currency === 'INR') {
const inrPrice = usdPrice * USD_TO_INR;
el.textContent = '₹' + inrPrice.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
} else {
el.textContent = '$' + usdPrice.toFixed(2);
}
console.log('New price:', el.textContent);
});
// Update cart total
const cartTotal = document.getElementById('cartTotal');
if (cartTotal) {
const text = cartTotal.textContent;
const cleanText = text.replace(/,/g, '').replace(/[^\d.]/g, '');
const price = parseFloat(cleanText);
if (!isNaN(price)) {
const currentIsInr = text.includes('₹');
const currentIsUsd = text.includes('$');
let usdPrice;
if (currentIsInr) {
usdPrice = price / USD_TO_INR;
} else {
usdPrice = price;
}
if (currency === 'INR') {
cartTotal.textContent = '₹' + (usdPrice * USD_TO_INR).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
} else {
cartTotal.textContent = '$' + usdPrice.toFixed(2);
}
}
}
// Update currency label
const currencyLabel = document.getElementById('currencyLabel');
if (currencyLabel) {
currencyLabel.textContent = currency;
}
}
/**
* Convert price based on currency
*/
function convertPrice(usdPrice) {
if (currentCurrency === 'INR') {
return '₹' + (usdPrice * USD_TO_INR).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}
return '$' + usdPrice.toFixed(2);
}