// MAGISTA — custom JS (clean rebuild)
// Sections: 1 promo banner (flip) · more are added below, one feature per IIFE.
/* 1 ── Promo banner: rotates MESSAGES with a flip animation. Styles live in the custom CSS (section 6). */
(() => {
// Edit here only. url '' = plain text. Comment a line out to disable it.
const MESSAGES = [
{ text: '✨ أول طلب لك؟ وفّر 5% بكود MAGISTA 👑', url: '' },
{ text: '👑 ذهب معتمد بعيار مضمون وجودة لا تُقارن', url: '' },
{ text: '🚚 شحن مجاني على الطلبات فوق 1000 ريال', url: '' }
];
const INTERVAL_MS = 6000;
function mount() {
if (document.querySelector('.magista-promo-banner')) return;
const link = document.createElement('a');
const dots = document.createElement('span');
dots.className = 'dots';
dots.innerHTML = MESSAGES.map(() => '').join('');
const bar = document.createElement('div');
bar.className = 'magista-promo-banner';
bar.append(link, dots);
const header = document.querySelector('header');
if (header) header.before(bar); else document.body.prepend(bar);
let index = 0;
const render = () => {
const { text, url } = MESSAGES[index];
link.textContent = text;
link.href = url || '#';
[...dots.children].forEach((d, i) => d.classList.toggle('active', i === index));
};
render();
// Flip out → swap text → flip in (driven by animationend, no nested timers)
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
// Timer-driven flip (animationend is unreliable: skipped in background tabs / interrupted animations left the bar blank)
const dur = () => (parseFloat(getComputedStyle(link).animationDuration) * 1000) || 400;
let busy = false;
const flip = () => {
if (busy) return;
busy = true;
link.className = 'flip-out';
setTimeout(() => {
render();
link.className = 'flip-in';
setTimeout(() => { link.className = ''; busy = false; }, dur());
}, dur());
};
setInterval(() => {
index = (index + 1) % MESSAGES.length;
if (reduced || document.hidden) { render(); link.className = ''; busy = false; } else flip();
}, INTERVAL_MS);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount); else mount();
})();
/* 2 — Size & returns notice: shown on rings / bangles / bands; purchase buttons stay locked until ticked (styles: CSS section 7) */
(() => {
// Shown by product category (main or sub): newborn bangles, bangles, premium bangles collection, rings & bands
const CATEGORY_IDS = ['1475434551', '568223536', '905353367', '710181205', '1084888839', '1043952642', '451451659'];
const SIZE_GUIDE = '/ar/دليل-المقاسات/page-1468807608';
const RETURNS = '/ar/الاستبدال-والاسترجاع/page-72675328';
function mount() {
const form = document.querySelector('form.product-form');
const button = form && form.querySelector('salla-add-product-button');
if (!button || form.querySelector('.magista-size-warning')) return;
const box = document.createElement('div');
box.className = 'magista-size-warning';
box.innerHTML =
'
قبل إتمام الطلب
' +
'' +
'- نأمل اختيار المقاس المناسب 🤍، ويمكنك الاستعانة بـ دليل المقاسات
' +
'- السعر يتحدث تلقائيًا حسب سعر الذهب وقت الطلب
' +
'- هذا المنتج غير قابل للاستبدال أو الإرجاع — سياسة الاستبدال والاسترجاع
' +
'
' +
'';
button.before(box);
document.body.classList.add('mg-size-locked'); // also locks the floating cart bar
box.querySelector('input').addEventListener('change', (e) => document.body.classList.toggle('mg-size-locked', !e.target.checked));
// Guard: while locked, swallow clicks / Enter / Space on every purchase control (incl. Apple Pay and keyboard use)
const BUY = 'salla-add-product-button, salla-quick-buy, salla-mini-checkout-widget, apple-pay-button';
const block = (e) => {
if (!document.body.classList.contains('mg-size-locked') || !e.target.closest(BUY)) return;
if (e.type === 'keydown' && e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
e.stopImmediatePropagation();
box.classList.remove('mg-nudge');
void box.offsetWidth;
box.classList.add('mg-nudge');
box.scrollIntoView({ block: 'center', behavior: 'smooth' });
};
['click', 'keydown'].forEach((t) => document.addEventListener(t, block, true));
}
// Match by the category breadcrumb (parent + sub). Breadcrumbs render client-side, so poll briefly instead of observing the DOM.
if (!document.querySelector('form.product-form')) return;
let tries = 0;
const timer = setInterval(() => {
const links = [...document.querySelectorAll('nav.breadcrumbs a')];
if (links.length < 2 && ++tries < 50) return;
clearInterval(timer);
if (links.some((a) => CATEGORY_IDS.some((id) => a.href.includes('/c' + id)))) mount();
}, 100);
})();
/* 3 — Pricing: payment-method price cards on product pages + offer-card fixes (real percentages, Arabic names). Styles: CSS sections 8-9 */
(() => {
// Discount % per payment method. Theme variables --custom-title1/2/3 override the fallbacks.
const cssNumber = (name, fallback) => {
const n = parseFloat(getComputedStyle(document.body).getPropertyValue(name).replace(/['"]/g, ''));
return n > 0 ? n : fallback;
};
const discounts = () => ({ bank: cssNumber('--custom-title1', 7.7), mada: cssNumber('--custom-title2', 6.7), visa: cssNumber('--custom-title3', 5.2) });
const money = (n) => (window.salla && salla.money ? salla.money(n) : n + ' SAR');
const discounted = (price, pct) => money(Math.round(price - price * (pct / 100)));
const toLatin = (s) => s.replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)).replace(/٫/g, '.').replace(/٬/g, '').replace(/،/g, ',');
/* ── Product page: price + weight readers ── */
const PRICE_SELECTORS = [
'.product-price .price_is_on_sale:not(.hidden) .total-price',
'.product-price .starting-or-normal-price:not(.hidden) .total-price',
'.product-price .total-price:not(.sr-only)',
'.price-wrapper h2.total-price',
'.p-price-outer h2'
];
const isVisible = (el) => el.offsetParent !== null && el.textContent.trim() && !el.closest('.hidden, [hidden], .sr-only');
function readPrice(form) {
for (const sel of PRICE_SELECTORS) {
const el = [...document.querySelectorAll(sel)].find(isVisible);
const n = el && parseFloat(toLatin(el.textContent).replace(/[^\d.]/g, ''));
if (n > 0) return n;
}
const amount = parseFloat(form.querySelector('[amount]')?.getAttribute('amount'));
return amount > 0 ? amount : NaN;
}
// Weight in grams from text such as "500 جرام", "وزن: 5", "1 كجم"
function gramsFrom(text) {
const t = toLatin(text || '');
const kg = t.match(/(\d+(?:[.,]\d+)?)\s*(?:كجم|كيلو|kg)/i);
if (kg) return parseFloat(kg[1].replace(',', '.')) * 1000;
const m = t.match(/(?:وزن|weight)\s*[:\-]?\s*(\d+(?:[.,]\d+)?)/i) || t.match(/(\d+(?:[.,]\d+)?)\s*(?:جرام|غرام|جم|gram|grams|gm|g)(?![a-z])/i);
return m ? parseFloat(m[1].replace(',', '.')) : NaN;
}
function readWeight(form) {
const texts = [...form.querySelectorAll('select[name^="options"]')].map((s) => s.options[s.selectedIndex]?.textContent);
const row = [...form.querySelectorAll('.center-between')].find((r) => r.textContent.includes('الوزن'));
texts.push(row?.querySelector('span.text-sm')?.textContent, document.querySelector('.product-weight')?.textContent);
return texts.map(gramsFrom).find((g) => g > 0) || NaN;
}
/* ── Product page: payment price cards ── */
const LOGO = {
mada: 'https://cdn.files.salla.network/homepage/423661514/51e177fe-a0c4-45fe-a27d-f99ab796c8d1.webp',
visa: 'https://cdn.files.salla.network/homepage/423661514/fc09d80e-ab81-4483-8284-9b8fc0fa969c.webp',
tamaraLight: 'https://cdn.salla.sa/AzbgnQ/LTG6hiemdAfivgHsRiSNhSJ0q5x3zuoXo3Z40QqB.png',
tamaraDark: 'https://cdn.salla.sa/AzbgnQ/fZq8i4juxnWNW53b9u9YDCV7FfyfdtFv9Z8GV1qa.png',
tabby: 'https://cdn.salla.sa/AzbgnQ/rz5hx6Jx2YPdZXQAOCClyGzUZbxxIYiFDQoJBSwA.png'
};
const img = (src, alt, cls) => '
';
const card = (key, label, logos) =>
'' + logos + '
' + label + ' ';
// Products that also show the per-gram bank-transfer price
const GRAM_PRODUCTS = ['1750061794'];
const showGram = GRAM_PRODUCTS.includes((location.pathname.match(/p(\d+)$/) || [])[1]);
const box = document.createElement('div');
box.className = 'mg-prices';
box.innerHTML =
(showGram ? '⚖️ سعر الغرام بالتحويل البنكي
' : '') +
card('mada', 'مدى', img(LOGO.mada, 'Mada')) +
card('visa', 'فيزا / ماستركارد', img(LOGO.visa, 'Visa Mastercard')) +
card('tamara', 'تمارا', img(LOGO.tamaraLight, 'تمارا', 'logo-light') + img(LOGO.tamaraDark, 'تمارا', 'logo-dark')) +
card('tabby', 'تابي', img(LOGO.tabby, 'تابي'));
let lastKey = '';
function refreshPrices() {
const form = document.querySelector('form.product-form');
if (!form) return;
const price = readPrice(form);
const weight = readWeight(form);
if (!(price > 0 && (weight > 0 || !showGram))) return; // weight only needed for the per-gram card
if (!box.isConnected) form.before(box);
const key = price + '|' + weight;
if (key === lastKey) return;
lastKey = key;
const d = discounts();
const rounded = money(Math.round(price * 10) / 10);
const values = {
mada: discounted(price, d.mada),
visa: discounted(price, d.visa),
tamara: rounded,
tabby: rounded,
gram: discounted(price / weight, d.bank)
};
box.querySelectorAll('[data-k]').forEach((el) => { el.innerHTML = values[el.dataset.k]; });
}
/* ── Offer cards: Arabic payment names + real percentages (Salla stores them rounded: 6% / 5%) ── */
const METHOD_NAMES = {
mada: 'مدى', creditcard: 'البطاقات الائتمانية', applepay: 'Apple Pay', visa: 'فيزا', mastercard: 'ماستركارد',
stcpay: 'STC Pay', tamara: 'تمارا', tabby: 'تابي', banktransfer: 'تحويل بنكي', cod: 'الدفع عند الاستلام', wallet: 'المحفظة'
};
function fixOffers() {
document.querySelectorAll('.s-offer-payment-method-item').forEach((el) => {
const name = METHOD_NAMES[el.textContent.trim().toLowerCase().replace(/[\s_-]/g, '')];
if (name && el.textContent !== name) el.textContent = name;
});
const d = discounts();
document.querySelectorAll('.s-offer-card-content').forEach((c) => {
const title = c.querySelector('.s-offer-card-title')?.textContent || '';
const desc = c.querySelector('.s-offer-card-description');
const pct = title.includes('مدى') ? d.mada : title.includes('البطاقات') ? d.visa : 0;
if (!desc || !pct) return;
const next = desc.textContent.replace(/[\d.]+\s*%/, pct + '%');
if (desc.textContent !== next) desc.textContent = next;
});
}
/* ── Scheduling: no DOM observers (they caused freezes). Poll while Salla hydrates, then react to events. ── */
const tick = () => { refreshPrices(); fixOffers(); };
let runs = 0;
const timer = setInterval(() => { tick(); if (++runs >= 30) clearInterval(timer); }, 400); // ~12s
setTimeout(() => { if (!box.isConnected) document.body.classList.add('mg-no-prices'); }, 6000); // product without weight: release reserved space
['pointerup', 'change'].forEach((ev) => document.addEventListener(ev, () => { setTimeout(tick, 300); setTimeout(tick, 1000); }));
if (window.salla && salla.event) salla.event.on('product::price.updated', tick);
})();
/* 4 — Cart: bank-transfer note under the totals */
(() => {
if (!document.body.classList.contains('cart')) return;
let tries = 0;
const timer = setInterval(() => {
const wrap = document.querySelector('.cart-total-wrapper');
if (!wrap && ++tries < 10) return;
clearInterval(timer);
if (!wrap || wrap.querySelector('.cart-payment-note')) return;
const note = document.createElement('div');
note.className = 'cart-payment-note t-red dm-text-sec mt-2 mb-4 flex justify-end flex-row-reverse';
note.innerHTML = 'سيظهر سعر التحويل البنكي في صفحة الدفع !';
const total = wrap.querySelector('.total-wrapper');
if (total) total.after(note); else wrap.append(note);
}, 500);
})();
/* 5 — Home: category circles order (ideally set in the Salla dashboard; this overrides it). Ids from the category URLs. */
(() => {
const ORDER = [
'981292379', // سبايك الذهب
'834744127', // أطقم
'905353367', // بناجر
'710181205', // البناجر الفاخرة
'1084888839', // خواتم و دبل
'1479047574', // أساور
'396533271', // عقود
'1263597072', // كفوف
'210241297', // حلقان
'1509743850', // مخنق
'2025380331', // عود
'415963941' // معمول
];
const sort = () => {
const wrapper = document.querySelector('.s-block--circle-links .swiper-wrapper');
if (!wrapper) return;
const slides = [...wrapper.children];
ORDER.forEach((id) => {
const slide = slides.find((s) => s.querySelector('a[href*="' + id + '"]'));
if (slide) wrapper.append(slide);
});
};
sort();
setTimeout(sort, 1200); // again once the slider has rendered
})();
/* 6 — Policy page: turns the plain page text into titles / lists / notes (styles: CSS section 11) */
(() => {
if (!location.href.includes('page-1284462140')) return;
// Paragraph classification by exact title or by opening words
const TITLES = ['مبدأ عام', 'حالات قبول الاستبدال أو الاسترجاع', 'شروط قبول الاستبدال أو الاسترجاع', 'الحالات التي لا يشملها الاسترجاع أو الإلغاء', 'الحالات التي لا يُقبل فيها الاسترجاع أو الإلغاء', 'سياسة إلغاء الطلبات', 'أسباب إلغاء الطلب من المتجر', 'ضوابط الإلغاء', 'تنويه بخصوص الأوزان', 'تنويه هام بخصوص الأوزان', 'الطلبات عبر خدمات التقسيط', 'الطلبات المدفوعة عبر خدمات التقسيط', 'الطلبات المدفوعة بالتقسيط', 'استعادة المبالغ', 'تنبيهات هامة', 'تحديث السياسة', 'فحص الطلبات', 'فحص المنتج'];
const NOTES = ['نظرًا لطبيعة منتجات الذهب', 'نظرًا لأن الذهب', 'نظرًا لأن منتجات الذهب', 'نقدّر ثقتكم الغالية', 'نشكر لكم ثقتكم', 'ويُعتبر إتمام الطلب', 'ويُعد إتمام عملية الشراء', 'لضمان رضاكم'];
const SUBTITLES = ['ويشترط', 'ومن الحالات التي لا يُقبل', 'ويحتفظ المتجر بحقه', 'وفي حال وجود فرق'];
const LIST_ITEMS = ['وجود عيب مصنعي', 'استلام منتج مختلف', 'استلام منتج غير مطابق', 'خطأ من المتجر', 'حدوث خطأ في الطلب', 'تقديم الطلب خلال', 'أن يكون المنتج', 'سلامة التغليف', 'إرفاق إثبات الشراء', 'إرفاق فاتورة', 'تغيّر سعر الذهب', 'تغير أو انخفاض', 'استخدام المنتج', 'إزالة الأختام', 'أي تعديل أو تغيير', 'تعديل أو العبث', 'العبث بالمنتج', 'المنتجات المصنّعة حسب الطلب', 'المنتجات المصنوعة', 'المنتجات المشمولة بعروض', 'المنتجات المخفضة', 'الطلبات التي تم تجهيزها', 'عدم توفر المنتج', 'خطأ تقني في السعر', 'وجود خطأ تقني', 'اشتباه في عملية دفع', 'الاشتباه بعملية دفع', 'يتم تثبيت السعر', 'تثبيت السعر', 'لا يمكن إلغاء الطلب', 'عدم إمكانية إلغاء', 'الطلبات المصنّعة حسب الطلب', 'طلبات المنتجات المصنوعة', 'قد تختلف مدة التجهيز', 'قد تختلف مدة تجهيز', 'يحق لماجيستا تحديث', 'يحق للمتجر تغيير', 'الطلبات المدفوعة عبر خدمات التقسيط', 'يتم استرداد المبلغ', 'يُعاد المبلغ', 'مدة الاسترداد', 'في حال وجود زيادة', 'في حال وجود نقص', 'يُرسل إشعار'];
const starts = (text, list) => list.some((k) => text.startsWith(k));
function classify(text) {
if (TITLES.includes(text)) return 'title';
if (starts(text, SUBTITLES)) return 'subtitle';
if (starts(text, NOTES)) return 'note';
if (starts(text, LIST_ITEMS)) return 'list';
return 'text';
}
function format(entry) {
entry.dataset.formatted = 'true';
document.body.classList.add('magista-policy-page');
const out = [];
let inList = false;
const closeList = () => { if (inList) { out.push(''); inList = false; } };
entry.querySelectorAll('p, h1, h2, h3, h4, ul, ol').forEach((el) => {
const text = el.textContent.trim();
if (!text) return;
const type = /^(UL|OL)$/.test(el.tagName) ? 'existing-list' : /^H[1-4]$/.test(el.tagName) ? 'title' : classify(text);
if (type !== 'list') closeList();
if (type === 'existing-list') {
el.classList.add('magista-policy__list');
out.push(el.outerHTML);
} else if (type === 'list') {
if (!inList) { out.push(''); inList = true; }
out.push('- ' + el.innerHTML + '
');
} else {
const tag = { title: 'h3', subtitle: 'p', note: 'div', text: 'p' }[type];
const cls = { title: 'section-title', subtitle: 'subtitle', note: 'note', text: 'text' }[type];
out.push('<' + tag + ' class="magista-policy__' + cls + '">' + el.innerHTML + '' + tag + '>');
}
});
closeList();
entry.innerHTML = out.join('');
}
// The page content renders after load: poll briefly (no MutationObserver)
let tries = 0;
const timer = setInterval(() => {
const entry = document.querySelector('.content-entry');
if (!entry && ++tries < 50) return;
clearInterval(timer);
if (entry && !entry.dataset.formatted) format(entry);
}, 100);
})();
/* 7 — Empty category message */
(() => {
let tries = 0;
const timer = setInterval(() => {
const found = [...document.querySelectorAll('.s-products-list-placeholder p')].filter((p) => p.textContent.includes('لا توجد منتجات'));
found.forEach((p) => { p.textContent = 'هذا القسم خالٍ الآن، لكن شيئاً استثنائياً في الطريق 👑'; });
if (found.length || ++tries >= 20) clearInterval(timer);
}, 400);
})();
/* 23 — Offer cards: keep "6.7%" reading left-to-right inside Arabic text */
(() => {
const fix = () => document.querySelectorAll('.s-offer-card-description:not([data-pct])').forEach((p) => {
p.dataset.pct = 1;
p.innerHTML = p.innerHTML.replace(/(\d+(?:\.\d+)?%)/g, '$1');
});
new MutationObserver(fix).observe(document.body, { childList: true, subtree: true });
fix();
})();
/* Menu: hover state for the submenu back button (a pseudo-element can't be hovered) */
document.addEventListener('mousemove',e=>{const n=e.target.closest&&e.target.closest('nav.mm-spn');if(!n)return;const r=n.getBoundingClientRect();n.classList.toggle('mg-back-hover',e.clientY-r.top<50&&e.clientX>r.right-64)},{passive:true});