');
$('foot').textContent = 'views = views here on LinkSpin; network = the partner ad network; partner zones = other members\u2019 zones on their own sites' + (synN0 > 1 ? ' (network and partner-zone views cost 1/' + synN0 + ' of the rate here, so ' + synN0 + ' of them cost what 1 view here does' + (synT !== synN0 ? '; text ads 1/' + synT : '') + ')' : '') + ' · a paused ad keeps its credits · unspent credits return when an ad ends';
$('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause')));
$('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume')));
// An ad pays from ONE position (the contract burns from that member id). When the ad's own position cannot
// cover a top-up but another of the member's positions can, the server says so (switchOptions) and the member
// can move the ad to that position and pay from there (Michael Camire 2026-11-14, ported from InstantAdPay).
const topUpReq = async (id, credits, switchTo) => (await fetch('/api/my/campaigns/' + id + '/topup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(switchTo ? { credits, switchTo } : { credits }) })).json();
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => {
const multi = (D.positionCount || 0) > 1;
const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available' + (multi ? ' across your positions; an ad pays from one position' : '') + '.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return;
const credits = Number(v.credits);
try {
let r = await topUpReq(b.dataset.top, credits);
if (r.error && r.switchOptions && r.switchOptions.length) {
const o = r.switchOptions[0];
const ok = await dialog({ title: 'Pay from position #' + o.memberId + '?', text: r.error + ' Move this ad to position #' + o.memberId + ' (' + fmt(o.free) + ' free) and add the ' + fmt(credits) + ' credits from there? Views from now on are paid from #' + o.memberId + '; what the ad already ran up stays on its old position.', ok: 'Pay from #' + o.memberId });
if (!ok) return;
r = await topUpReq(b.dataset.top, credits, o.memberId);
}
if (r.error) throw new Error(r.error);
toast('Topped up: ' + fmt(r.added) + ' credits added' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The ad is live again.' : '.')); load();
} catch (e) { toast(e.message, true); }
}));
$('rows').querySelectorAll('[data-qcancel]').forEach(b => b.addEventListener('click', () => cancelReservation(Number(b.dataset.qcancel))));
$('rows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openEdit(Number(b.dataset.edit))));
{ const w = $('loginWhere'); if (w) w.textContent = 'full screen to every member right after they sign in: ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day slot, ' + slotInfo().max + ' slots at a time. When all are taken, reserve the next one: pay now, it starts when a slot frees, and a cancel before then refunds in full'; }
{ const cl = D.creditLog || []; const box = $('creditLog'); if (box) { box.parentElement.hidden = !cl.length; box.innerHTML = cl.map(x => '
').join(''); } }
slotChip(); if (!$('composer').hidden) setType(TYPE);
earnPaint();
{ const hm = /^#edit=(\d+)$/.exec(location.hash || ''); if (hm) { history.replaceState(null, '', location.pathname + location.search); openEdit(Number(hm[1])); } } // /tools campaign list links here
}
// -- edit an ad (2026-10-18): fix the link, the image or the text. The first edit of each ad is free, then D.editFee credits.
// Type, size, budget, countries, schedule and audience are the buy itself and stay a new campaign.
const feeNote = c => c.status === 'queued' ? 'Edits are free while this ad waits in line, and your one free correction stays for when it runs.' : !c.edits ? 'This edit is free (your one free correction).' : (D.editFee ? 'This edit costs ' + fmt(D.editFee) + ' credits.' : 'Edits are free right now.');
async function openEdit(id) {
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) { toast('That ad is not in your list.', true); return; }
const fields = [{ k: 'name', label: 'Name', value: c.name, max: 60 }, { k: 'targetUrl', label: 'Where the click goes', value: c.targetUrl, mono: true }];
if (c.type === 'banner') fields.push({ k: 'imageUrl', label: 'Image URL (' + c.width + 'x' + c.height + ')', value: c.imageUrl || '', mono: true });
if (c.type === 'text') fields.push({ k: 'title', label: 'Headline (60)', value: c.title || '', max: 60 }, { k: 'body', label: 'One line (140)', value: c.body || '', max: 140 });
const last = (c.editLog || []).slice(-1)[0];
const html = '
' + esc(feeNote(c)) + ' ' + (c.status === 'queued' ? '' : c.edits ? 'Your free correction on this ad is used.' : 'After this one, each edit costs ' + fmt(D.editFee) + ' credits.') + '
'
+ '
The type, size, budget, countries, schedule and audience stay as they are. To change those, start a new ad.' + (last ? ' Last edited ' + new Date(last.ts).toLocaleString() + '.' : '') + '
'
+ (c.type === 'banner' ? '
Preview at real size
' : '')
+ (c.type === 'login' ? '
A login ad shows the page itself, full screen, so the link is the ad.
' : '');
const wait = dialog({ title: 'Edit ad #' + c.id + ' (' + c.type + ')', html, fields, ok: 'Review changes' });
if (c.type === 'banner') { // the dialog is in the page now: wire the preview and the uploader
const host = $('crModalHost'), inp = host.querySelector('#dlg-imageUrl'), prev = host.querySelector('#edPrev');
const paint = () => { const u = inp.value.trim(); prev.innerHTML = /^https?:\/\//i.test(u) ? '' : 'No image yet'; };
inp.addEventListener('input', paint); paint();
host.querySelector('#edFile').addEventListener('change', async e => { const f = e.target.files[0]; if (!f) return; try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); inp.value = location.origin + r.url; paint(); toast('Uploaded.'); } catch (er) { toast(er.message, true); } });
}
const v = await wait; if (!v) return;
const label = { name: 'name', targetUrl: 'link', imageUrl: 'image', title: 'headline', body: 'text line' };
const changed = Object.keys(v).filter(k => String(v[k]).trim() !== String(c[k] || '').trim());
if (!changed.length) { toast('Nothing changed.'); return; }
const paidEdit = c.status !== 'queued' && c.edits && D.editFee;
const ok = await dialog({ title: 'Save the new ' + changed.map(k => label[k]).join(', ') + '?', text: feeNote(c) + (paidEdit ? ' It comes out of your earned credits first, then purchased.' : ''), ok: paidEdit ? 'Save and pay ' + fmt(D.editFee) : 'Save' });
if (!ok) return;
const body = {}; changed.forEach(k => { body[k] = v[k].trim(); });
try { const r = await api('/api/my/campaigns/' + c.id + '/edit', body); toast('Saved.' + (r.fee ? ' ' + fmt(r.fee) + ' credits charged.' : '') + (r.warn ? ' ' + r.warn : '')); load(); }
catch (e) { toast(e.message, true); }
}
async function cancelReservation(id) {
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) return;
const q = (D.loginQueue || []).find(x => x.id === id);
const ok = await dialog({ title: 'Cancel reservation #' + id + '?', text: 'You leave the line' + (q ? ' (you are #' + q.place + ')' : '') + ' and the ' + fmt(c.budget) + ' credits you paid come back to you in full, as purchased credits. If you reserve again later, you join at the back of the line.', ok: 'Cancel and refund', no: 'Keep my place', danger: true });
if (!ok) return;
try { const r = await api('/api/my/campaigns/' + id + '/cancel-reservation', {}); toast('Cancelled. ' + fmt(r.refunded) + ' credits refunded.'); load(); } catch (e) { toast(e.message, true); }
}
async function act(path) { try { await api(path, {}); load(); } catch (e) { toast(e.message, true); } }
// -- earn by viewing: the engine's fraud-guarded flow (server-timed dwell + a human check) runs inside /view/
function earnPaint() {
const s = EARN; if (!s) return;
{ const g = $('earnGauge'); if (g) { const n = Math.max(1, s.target); g.innerHTML = Array.from({ length: n }, (_, i) => '').join(''); g.style.gridTemplateColumns = 'repeat(' + n + ',1fr)'; } }
const done = s.views >= s.target;
$('earnLine').textContent = s.claimed ? 'Claimed for today' + (s.streakDay > 1 ? ' (streak day ' + s.streakDay + ')' : '') + '. Tomorrow pays ' + s.nextClaim + '.' : done ? 'Set complete. Claim your ' + s.claimCredits + ' credits.' : s.views + ' of ' + s.target + ' viewed. Then claim ' + s.claimCredits + ' credits' + (s.streakDay > 1 ? ' (streak day ' + s.streakDay + ')' : '') + '.';
$('earnClaim').hidden = !(done && !s.claimed); $('earnNext').hidden = done;
$('earnNote').textContent = (s.earnedAvailable != null ? s.earnedAvailable : s.earned) + ' earned credits free to spend' + (s.reserved ? ', ' + s.reserved + ' working in live ads' : '') + '. Each view is a full page, timed on the server, with a quick check at the end.';
}
async function earnRefresh() { try { EARN = await CR.get('/api/my/earn'); earnPaint(); } catch (e) {} }
let vt = 0;
$('earnNext').addEventListener('click', async () => {
const type = ['banner', 'text'][vt++ % 2]; let r = null;
try { r = await CR.get('/api/my/earnview?type=' + type); } catch (e) { toast(e.message, true); return; }
if (!r || !r.ad || !r.viewUrl) { toast(r && r.status && r.status.views >= r.status.target ? 'Set complete for today.' : 'No member ads are live right now. Views resume the moment a campaign runs.', true); earnRefresh(); return; }
openView(r.viewUrl);
});
function openView(url) {
closeView(); const back = document.createElement('div'); back.id = 'adOverlay'; back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050912;display:flex;flex-direction:column';
const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); x.textContent = '✕'; x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; x.addEventListener('click', closeView);
const f = document.createElement('iframe'); f.src = url; f.style.cssText = 'flex:1;width:100%;border:0;background:#050912'; back.appendChild(f); back.appendChild(x); document.body.appendChild(back); document.body.style.overflow = 'hidden';
}
function closeView() { const m = $('adOverlay'); if (m) m.remove(); document.body.style.overflow = ''; earnRefresh(); }
window.addEventListener('message', e => { if (e.origin !== location.origin || !e.data) return; if (e.data.t === 'iap-view-close') closeView(); else if (e.data.t === 'iap-view-done') earnRefresh(); });
window.addEventListener('storage', e => { if (e.key === 'iap-view-done') earnRefresh(); });
$('earnClaim').addEventListener('click', async () => { try { const r = await api('/api/my/claim', {}); toast('+' + r.credited + ' credits' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Spend them on an ad.'); load(); } catch (e) { toast(e.message, true); } });
// -- composer
function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login';
const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget');
if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; }
$('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : '';
cost(); preview(); }
// a login slot is paid from ONE position (2026-11-04): say what each position has free and stop the buy up front when none covers it
const loginShort = () => { const F = D && D.loginFunds; return !!(F && F.best < slotInfo().credits); };
function fundsLine() { const F = D && D.loginFunds; if (!F) return ''; const L = slotInfo();
const per = (F.per || []).length > 1 ? ' (' + F.per.map(x => '#' + x.memberId + ': ' + fmt(x.avail)).join(', ') + ')' : '';
return 'Paid from one position. '
+ (loginShort() ? 'None of yours has ' + fmt(L.credits) + ' purchased credits free on its own' + per + '. Buy a package on one position to bring it to ' + fmt(L.credits) + ', then come back.'
: 'Your best-funded position has ' + fmt(F.best) + ' purchased credits free' + per + '.') + ''; }
function fundsGate() { if (TYPE !== 'login') return; const b = $('fGo'); b.disabled = loginShort(); if (loginShort()) b.title = 'No single position has ' + fmt(slotInfo().credits) + ' purchased credits free'; }
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full, reserve the next)'); }
function cost() { const b = Math.floor(Number($('fBudget').value) || 0); const r = D ? D.rates : {}; let s = '';
if (TYPE === 'banner') s = 'about ' + fmt(Math.floor(b / (r.bannerCreditsPerBatch || 2) * (r.bannerBatch || 10))) + ' timed views';
else if (TYPE === 'text') s = 'about ' + fmt(Math.floor(b / (r.textCreditsPerBatch || 1) * (r.textBatch || 10))) + ' timed views';
else { const L = slotInfo(); $('fCost').innerHTML = (L.free
? '' + fmt(L.credits) + ' purchased credits for ' + L.days + ' days of unlimited sign-in impressions · ' + L.free + ' of ' + L.max + ' slots open'
: 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ', ' + L.queued + ' paid reservation' + (L.queued === 1 ? '' : 's') + ' in line' : '') + '. Reserve the next one: ' + fmt(L.credits) + ' purchased credits now and you would be #' + nextPlace().place + ' in line. ' + esc(estText(nextPlace().estStartCt)) + ' Cancel before it starts for a full refund.') + fundsLine(); fundsGate(); return; }
$('fCost').innerHTML = b >= 10 ? s.replace(/(about )([\d,]+)/, '$1$2') : 'minimum 10 credits'; }
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = '