var maxschedule = 366; async function getTokenPrice(mintAddress) { try { const response = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${mintAddress}`); const data = await response.json(); if (!data.pairs || data.pairs.length === 0) { console.log('No trading pairs found for this token'); return null; } // Get the most liquid pair (usually the first one or highest liquidity) const pair = data.pairs[0]; return { symbol: pair.baseToken.symbol, // Get token symbol from baseToken name: pair.baseToken.name, // Get token name priceUSD: pair.priceUsd, priceNative: pair.priceNative, liquidityUSD: pair.liquidity.usd, pairAddress: pair.pairAddress, dex: pair.dexId, baseToken: pair.baseToken, quoteToken: pair.quoteToken }; } catch (error) { console.error('Error fetching token price:', error); return null; } } //var usdtpair = 'BTCUSDT'; function getSPLParameter() { try { const urlParams = new URLSearchParams(window.location.search); const splValue = urlParams.get('spl'); // Check if parameter exists if (splValue === null || splValue === undefined) { console.log('SPL parameter not found in URL'); return null; } return splValue; } catch (error) { console.error('Error getting SPL parameter:', error); return null; } } var usdtpair; var urlpair; const spl = getSPLParameter(); if (spl) { getTokenPrice(spl).then(priceData => { if (priceData) { urlpair = priceData.symbol + "USDT"; usdtpair = priceData.symbol + "USDT"; //console.log(`Price: $${priceData.priceUSD}`); } }); } else{ usdtpair = 'BTCUSDT'; } (function(){ // All DOM queries are scoped to the root container to avoid touching other page elements. const root = document.getElementById('usdt-selector-root'); if (!root) return; const openBtn = root.querySelector('#usdt-openAll'); const list = root.querySelector('#usdt-list'); const card = root.querySelector('#usdt-card'); const selectedEl = root.querySelector('#usdt-selected'); function markSelected(pairEl){ root.querySelectorAll('.pair').forEach(p => { p.style.outline = ''; p.classList.remove('is-selected'); }); if (!pairEl) return; pairEl.style.outline = '2px solid rgba(155,124,255,0.18)'; pairEl.classList.add('is-selected'); const sym = pairEl.querySelector('.sym'); // Use Unicode bullet to avoid encoding issues selectedEl.textContent = (sym ? sym.textContent : pairEl.dataset.pair) + ' \u2022 ' + pairEl.dataset.pair; } // Initialize: keep list closed and select default function init(){ if (!list || !openBtn) return; list.classList.remove('open'); list.style.maxHeight = '0'; list.setAttribute('aria-hidden','true'); openBtn.textContent = 'Show Pairs'; openBtn.setAttribute('aria-expanded','false'); const defaultPair = root.querySelector('.pair[data-pair="BTCUSDT"]'); if (defaultPair) { markSelected(defaultPair); const details = defaultPair.closest('details'); if (details) details.open = true; } } // Toggle open/close if (openBtn && list) { openBtn.addEventListener('click', () => { const isOpen = list.classList.toggle('open'); openBtn.textContent = isOpen ? 'Hide Pairs' : 'Show Pairs'; openBtn.setAttribute('aria-expanded', String(isOpen)); list.setAttribute('aria-hidden', String(!isOpen)); if (isOpen) { list.style.maxHeight = Math.round(window.innerHeight * 0.6) + 'px'; const sel = root.querySelector('.pair.is-selected'); if (sel) sel.scrollIntoView({ behavior: 'smooth', block: 'center' }); } else { list.style.maxHeight = '0'; } }); } // Keep height responsive while open window.addEventListener('resize', () => { if (list && list.classList.contains('open')) { list.style.maxHeight = Math.round(window.innerHeight * 0.6) + 'px'; } }); // Delegated click handler scoped to the card if (card) { card.addEventListener('click', (e) => { const pairEl = e.target.closest('.pair'); if (!pairEl || !card.contains(pairEl)) return; markSelected(pairEl); // Dispatch a scoped custom event on the root so host page can listen if desired root.dispatchEvent(new CustomEvent('usdt:pair-selected', { detail: { pair: pairEl.dataset.pair } })); usdtpair = pairEl.dataset.pair; }); // Keyboard accessibility: Enter/Space selects card.addEventListener('keydown', (e) => { const el = e.target.closest('.pair'); if (!el || !card.contains(el)) return; if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); el.click(); } }); } // Run init after DOM is ready for this block if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })(); var payout = "0.20"; payout = 1 - +payout; var xValues = []; var yValues = []; var x = 0; var pprice; var oldpair = 'BTCUSDT'; const realchart = new Chart("myChart", { type: "line", data: { labels: xValues, datasets: [{ label: '', // no label text next to a color box fill: false, pointRadius: 0, // hide point marker pointHoverRadius: 0, // hide hover marker backgroundColor: "rgba(0,0,255,1.0)", borderColor: "green", data: yValues }] }, options: { spanGaps: true, plugins: { legend: { display: false, labels: { boxWidth: 0 } // extra safety for legend color box }, tooltip: { displayColors: false, // remove the small colored square in tooltip callbacks: { title: () => '', // optional: hide tooltip title label: ctx => { const v = ctx.raw; return (v === null || v === undefined) ? '' : v.toString(); } } } }, interaction: { intersect: true }, hover: { mode: 'nearest' } } }); window.realchart = realchart; setInterval(function(){ pprice = 0; if (oldpair !== usdtpair && window.realchart) { x = 0; xValues.length = 0; yValues.length = 0; realchart.data.labels = xValues; realchart.data.datasets[0].data = yValues; realchart.update(); oldpair = usdtpair; } x = x + 1; const ts = Date.now() - 1000; const url = "https://api.binance.com/api/v3/aggTrades?symbol=" + usdtpair + "&startTime=" + ts + "&limit=1"; if(spl && usdtpair == urlpair){ getTokenPrice(spl).then(priceData => { if (priceData) { //console.log(`Price: $${priceData.priceUSD}`); pprice = priceData.priceUSD; yValues.push(priceData.priceUSD); } }); xValues.push(x); // keep chart arrays in sync and update only after valid push realchart.data.labels = xValues; realchart.data.datasets[0].data = yValues; realchart.update(); } else{ fetch(url, { cache: "no-store" }) .then(r => r.json()) .then(data => { // debug: uncomment to inspect API shape // console.log('api data', data); if (!Array.isArray(data) || data.length === 0 || !data[0] || data[0].p == null) { // no valid price this tick — skip updating the chart return; } const round1 = parseFloat(data[0].p); pprice = round1; if (Number.isNaN(round1)) { return; } yValues.push(round1); xValues.push(x); // keep chart arrays in sync and update only after valid push realchart.data.labels = xValues; realchart.data.datasets[0].data = yValues; realchart.update(); }) .catch(err => { console.error('fetch error', err); }); } // DO NOT call realchart.update() here }, 1000); var plus = 0; var getbudget = "0.01,0.1,0.10,1,10,100,1000" ; var budget = getbudget.split(","); var initialreturn = budget[plus]; var initialprofit = budget[plus]*payout; document.getElementById('amount').setAttribute("min", budget[1]); document.getElementById('amount').setAttribute("max", budget[budget.length-1]); document.getElementById("amount").value = budget[0]; initialreturn = Number(initialreturn) + Number(initialprofit); document.getElementById("return").innerHTML ="$" + initialreturn.toFixed(4); document.getElementById("profit").innerHTML = "+" + initialprofit.toFixed(4); document.getElementById("plus").addEventListener("click", function(){document.getElementById("amount").value = (Number(document.getElementById("amount").value) + Number(budget[plus]/10)).toFixed(4) ;if(Number(document.getElementById("amount").value) >= +budget[budget.length-1]){let maxi = +budget[budget.length-1]; document.getElementById("amount").value = maxi.toFixed(4);} if(+plus == 0){let plus0 = Number(document.getElementById("amount").value) + Number(budget[0]);document.getElementById("amount").value = plus0.toFixed(2);} let profit1 = +document.getElementById("amount").value * payout; let rereturn = profit1 + +document.getElementById("amount").value;document.getElementById("return").innerHTML ="$" + rereturn.toFixed(4); document.getElementById("profit").innerHTML = "+" + (profit1).toFixed(4); }); document.getElementById("minus").addEventListener("click", function(){document.getElementById("amount").value = (Number(document.getElementById("amount").value) - Number(budget[plus]/10)).toFixed(4) ; if(Number(document.getElementById("amount").value) <= budget[0]){let mini = +budget[0]; document.getElementById("amount").value = mini.toFixed(4);} if(plus == 0 && document.getElementById("amount").value != +budget[0]){let minusplus0 = Number(document.getElementById("amount").value) - Number(budget[0]); document.getElementById("amount").value = minusplus0.toFixed(2);} let profit2 = +document.getElementById("amount").value*payout; let rereturn1 = profit2 + +document.getElementById("amount").value;document.getElementById("return").innerHTML ="$" + rereturn1.toFixed(4); document.getElementById("profit").innerHTML = "+" + (profit2).toFixed(4); }); document.getElementById("fastTrade").addEventListener("click", function(){plus++; if(plus>budget.length-1){plus = 0;} document.getElementById("amount").value = budget[plus]; document.getElementById('amount').setAttribute("min", budget[plus-1]); document.getElementById('amount').setAttribute("step", +budget[+plus] / 10); let rereturn2 = +budget[plus]*payout; rereturn2 = rereturn2 + +budget[plus];document.getElementById("return").innerHTML ="$" + rereturn2.toFixed(4); document.getElementById("profit").innerHTML = "+" + (+budget[plus]*payout).toFixed(4); }); document.getElementById("amount").addEventListener('change', function(){ var initialprofit1 = +document.getElementById("amount").value * payout; var initialreturn1 = +document.getElementById("amount").value + initialprofit1; document.getElementById("return").innerHTML ="$" + initialreturn1.toFixed(4); document.getElementById("profit").innerHTML = "+" + initialprofit1.toFixed(4); }); var timer = 30; timer = +timer; var maxtime = 366; var timerange = 5; maxtime = +maxtime; document.getElementById("timer-days").setAttribute("max", maxtime); document.getElementById("days").setAttribute("max", maxschedule); // maxschedule //document.getElementById("timeplus").addEventListener("click", function(){ if(timer>19){ timer = timer+timerange } else{timer = timer + 1;}; if(timer>maxtime){timer=maxtime;};document.getElementById("timing").innerHTML = timer +" " + "seconds";}); //document.getElementById("timeminus").addEventListener("click", function(){ if(timer>24){ timer = timer-timerange } else{timer = timer - 1;}; if(timer<30){timer=30;}; document.getElementById("timing").innerHTML = timer +" "+"seconds";}); const inputs = document.querySelectorAll('#timerblock input'); inputs.forEach(input => { input.addEventListener('blur', function(event) { if(document.getElementById("timer-days").value == 0 && document.getElementById("timer-hours").value == 0 && document.getElementById("timer-minutes").value == 0 && document.getElementById("timer-seconds").value < timer){ document.getElementById("timer-seconds").value = timer; } }); }); var firstprice = []; var lastprice = []; var balance = 1000; document.getElementById('balance').innerHTML = balance.toFixed(4); var hiprice = 0; var bud = +budget[plus]; var nl = 0; var orde = 0; var scheduleprice; var scheduletime; document.getElementById("hi").addEventListener("click", function(){ orde++; bud = +budget[plus]; balance = Number(document.getElementById("balance").textContent.trim()); if(balance>bud || balance == bud){ nl++; // balance = balance - bud; // document.getElementById("balance").innerHTML = balance.toFixed(4) ; var inputamount = document.getElementById('amount').value; var timeup = +timer; let scheduledays = document.getElementById("days").value || 0; scheduleprice = document.getElementById("schedule-price").value; let schedulehours = document.getElementById("hours").value || 0; let scheduleminutes = document.getElementById("minutes").value || 0; let scheduleseconds = document.getElementById("seconds").value || 0; scheduletime = (scheduledays * 24 * 60 * 60) + (schedulehours * 60 * 60) + (scheduleminutes * 60) + scheduleseconds; document.getElementById("schedule-price").value = ""; document.getElementById("hours").value = ""; document.getElementById("minutes").value = ""; document.getElementById("seconds").value = ""; document.getElementById("days").value = ""; let timerdays = document.getElementById("timer-days").value || 0; let timerhours = document.getElementById("timer-hours").value || 0; let timerminutes = document.getElementById("timer-minutes").value || 0; let timerseconds = document.getElementById("timer-seconds").value || 0; timeup = (timerdays * 24 * 60 * 60) + (timerhours * 60 * 60) + (timerminutes * 60) + timerseconds; document.getElementById("timer-days").value = ""; document.getElementById("timer-hours").value = ""; document.getElementById("timer-minutes").value = ""; document.getElementById("timer-seconds").value = ""; /*if(timerdays == 0 && timerhours == 0 && timerminutes == 0 && timerseconds < timer){ timerseconds = timer; }*/ if(spl && usdtpair == urlpair){ if(scheduleprice){ document.getElementById("acceptor").setAttribute("src", "acceptor.php?lohi=hi&amount="+inputamount+"&time="+timeup+"&pair="+usdtpair+"&scheduletime="+scheduletime+"&scheduleprice=" + +scheduleprice + "&spl=" + spl); } else{ document.getElementById("acceptor").setAttribute("src", "acceptor.php?lohi=hi&amount="+inputamount+"&time="+timeup+"&pair="+usdtpair+"&scheduletime="+scheduletime + "&spl=" + spl); } } else{ setTimeout(function(){ if(scheduleprice){ document.getElementById("acceptor").setAttribute("src", "acceptor.php?lohi=hi&amount="+inputamount+"&time="+timeup+"&pair="+usdtpair+"&scheduletime="+scheduletime+"&scheduleprice=" + +scheduleprice); } else{ document.getElementById("acceptor").setAttribute("src", "acceptor.php?lohi=hi&amount="+inputamount+"&time="+timeup+"&pair="+usdtpair+"&scheduletime="+scheduletime); }}, 1000); } // Copy-paste this inside your addEventListener callback. // It defines showSuccess once (if needed) and then shows the message. // It does NOT call preventDefault or stopPropagation. (function () { // Define showSuccess once if (!window.showSuccess) { // inject styles const css = ` #__top_notif_wrap{position:fixed;top:env(safe-area-inset-top,12px);left:50%;transform:translateX(-50%);z-index:2147483647;width:min(96%,640px);pointer-events:none;display:flex;justify-content:center} #__top_notif_card{pointer-events:auto;display:flex;align-items:center;gap:10px;background:linear-gradient(180deg,#1e7e34,#198754);color:#fff;padding:10px 14px;border-radius:10px;box-shadow:0 8px 20px rgba(0,0,0,.18);border:1px solid rgba(0,0,0,0.06);width:100%;max-width:640px;opacity:0;transform:translateY(-6px) scale(.995);transition:opacity .22s ease,transform .22s ease} #__top_notif_icon{width:36px;height:36px;border-radius:50%;background:rgba(255,255,255,.12);display:grid;place-items:center;font-weight:700} #__top_notif_text{line-height:1} #__top_notif_title{font-weight:700;font-size:14px} #__top_notif_msg{font-size:13px;opacity:.95} #__top_notif_close{margin-left:auto;background:transparent;border:none;color:#fff;font-size:20px;cursor:pointer;padding:6px;border-radius:6px} #__top_notif_wrap.show #__top_notif_card{opacity:1;transform:translateY(0) scale(1)} @media (max-width:420px){#__top_notif_icon{width:32px;height:32px;font-size:16px}#__top_notif_title{font-size:13px}#__top_notif_msg{font-size:12px}} @media (prefers-reduced-motion:reduce){#__top_notif_card{transition:none}} `; const style = document.createElement('style'); style.id = '__top_notif_style'; style.appendChild(document.createTextNode(css)); document.head.appendChild(style); // helper: ensure container function ensureWrap() { let wrap = document.getElementById('__top_notif_wrap'); if (!wrap) { wrap = document.createElement('div'); wrap.id = '__top_notif_wrap'; wrap.setAttribute('role', 'status'); wrap.setAttribute('aria-live', 'polite'); document.body.appendChild(wrap); } else { // re-append to body to maximize stacking context document.body.appendChild(wrap); } return wrap; } // simple escape function escapeHtml(str) { if (typeof str !== 'string') return ''; return str.replace(/[&<>"']/g, function (m) { return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[m]; }); } let hideTimer = null; window.showSuccess = function (message = '', options = {}) { const { title = 'Success', duration = 3500, icon = '✔', background = 'linear-gradient(180deg,#1e7e34,#198754)'} = options; const wrap = ensureWrap(); // remove existing card const existing = document.getElementById('__top_notif_card'); if (existing) existing.remove(); const card = document.createElement('div'); card.id = '__top_notif_card'; card.style.background = background; card.innerHTML = `
${escapeHtml(title)}
${escapeHtml(message)}
`; wrap.appendChild(card); // ensure wrap is last in body to beat stacking contexts document.body.appendChild(wrap); // animate in requestAnimationFrame(() => wrap.classList.add('show')); // close button const closeBtn = card.querySelector('#__top_notif_close'); if (closeBtn) closeBtn.addEventListener('click', () => hide(wrap, card)); // auto-hide if (hideTimer) clearTimeout(hideTimer); if (typeof duration === 'number' && duration > 0) { hideTimer = setTimeout(() => hide(wrap, card), duration); } // hide on Escape once const esc = (e) => { if (e.key === 'Escape') hide(wrap, card); document.removeEventListener('keydown', esc); }; document.addEventListener('keydown', esc); }; function hide(wrap, card) { const c = card || document.getElementById('__top_notif_card'); const w = wrap || document.getElementById('__top_notif_wrap'); if (!c) return; if (w) w.classList.remove('show'); const delay = (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) ? 0 : 220; if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; } setTimeout(() => { if (c.parentElement) c.remove(); }, delay); } } // end define showSuccess // Show the notification for this event // (This line is what you paste inside your addEventListener so it runs each time the event fires) if(inputamount && timeup && usdtpair && scheduletime && +scheduletime>0){ showSuccess('Trade is scheduled successfully', { title: 'Success', duration: 3500, icon: '✔' }); } else if(scheduleprice){ showSuccess('Trade is not scheduled, schedule time first', { title: 'Failed', duration: 3500, icon: 'X', background: 'linear-gradient(180deg, #dc3545, #c82333)' }); } })(); }; }); var me = "user95897216"; window.addEventListener("click", function (event) { let myid = event.target.id || ""; let elemid = document.getElementById(myid); let myidnum = 0; let userbalance = 0; let targetamount = 0; if(me && me != 1 && myid.includes("actionBtn") ){ myidnum = parseInt(myid, 10); let timertarget = Number(document.getElementById(myidnum + "timer").textContent.trim()); if(+timertarget > 0){ userbalance = Number(document.getElementById("balance").textContent.trim()); targetamount = Number(document.getElementById(myidnum + "amount").textContent.trim()); let creatorb = document.getElementById(myidnum + "creator").textContent.trim(); if(creatorb == me){ // document.getElementById("balance").innerHTML = +userbalance + +targetamount; // balance = balance + +targetamount; document.getElementById("acceptor").src = "acceptor.php?acceptor=" + me + "&rowid=" + myidnum +"&pair="+usdtpair; } else if(+userbalance - +targetamount >= 0 && creatorb != me){ // document.getElementById("balance").innerHTML = +userbalance - +targetamount; // balance = balance - +targetamount; document.getElementById("acceptor").src = "acceptor.php?acceptor=" + me + "&rowid=" + myidnum +"&pair="+usdtpair; } //userbalance = 0; //targetamount = 0; elemid.style.visibility = "hidden"; //elemid.disabled = true; //elemid.style.opacity = "0.85"; } }; }); function updateBalance() { fetch('/balance.php', { cache: 'no-store' }) .then(response => response.json()) .then(data => { const addme = data.toadd; const balanceEl = document.getElementById("balance"); const currentBalance = Number(balanceEl.textContent.trim()); const newBalance = currentBalance + Number(addme); balanceEl.innerHTML = newBalance.toFixed(4); console.log("toadd", addme); // Schedule the next run AFTER this one finishes setTimeout(updateBalance, 1000); }) .catch(err => { console.error('Fetch error:', err); // Retry after delay even if error setTimeout(updateBalance, 1000); }); } // Start the loop updateBalance(); function updateSchedule() { fetch('/frame.php', { cache: 'no-store' }) .then(response => response.json()) .then(data => { const jobbie = data.myjob; if(jobbie == "work-done"){ // Schedule the next run AFTER this one finishes setTimeout(updateSchedule, 1000); } }) .catch(err => { console.error('Fetch error:', err); // Retry after delay even if error setTimeout(updateSchedule, 1000); }); } // Start the loop //updateSchedule(); // deposit update function depositupdate() { fetch('/deposit.php', { cache: 'no-store' }) .then(response => response.json()) .then(data => { const addme = data.toadd; console.log("toadd", addme); const balanceEl = document.getElementById("balance"); const currentBalance = Number(balanceEl.textContent.trim()); const newBalance = currentBalance + Number(addme); balanceEl.innerHTML = newBalance.toFixed(4); // Schedule the next run AFTER this one finishes setTimeout(depositupdate, 1000); }) .catch(err => { console.error('Fetch error:', err); // Retry after delay even if error setTimeout(depositupdate, 1000); }); } // Start the loop depositupdate(); function tradeschedule() { fetch('/schedule.php', { cache: 'no-store' }) .then(response => response.json()) .then(data => { const jobbie = data.myjob; if(jobbie == "work-done"){ // Schedule the next run AFTER this one finishes setTimeout(tradeschedule, 500); } }) .catch(err => { console.error('Fetch error:', err); // Retry after delay even if error setTimeout(tradeschedule, 500); }); } // Start the loop //tradeschedule(); function updateBalanceschedule() { fetch('/balance-schedule.php', { cache: 'no-store' }) .then(response => response.json()) .then(data => { let addme = data.toadd; console.log("toadd", addme); let balanceEl = document.getElementById("balance"); let currentBalance = Number(balanceEl.textContent.trim()); let newBalance = currentBalance + Number(addme); balanceEl.innerHTML = newBalance.toFixed(4); // Schedule the next run AFTER this one finishes setTimeout(updateBalanceschedule, 1000); }) .catch(err => { console.error('Fetch error:', err); // Retry after delay even if error setTimeout(updateBalanceschedule, 1000); }); } // Start the loop updateBalanceschedule(); // Time Input Auto-Switch with Input Masking document.addEventListener('DOMContentLoaded', function() { const daysInput = document.getElementById('days'); const hoursInput = document.getElementById('hours'); const minutesInput = document.getElementById('minutes'); const secondsInput = document.getElementById('seconds'); // Array of time inputs const timeInputs = [daysInput, hoursInput, minutesInput, secondsInput]; // Set max values for validation const maxValues = [maxschedule, 23, 59, 59]; timeInputs.forEach((input, index) => { const maxVal = maxValues[index]; const maxLen = maxVal.toString().length; // allows 3 digits for days, 2 for others // Only allow numeric input input.addEventListener('keypress', function(e) { const charCode = e.which ? e.which : e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { e.preventDefault(); return false; } return true; }); // Handle input with auto-switch input.addEventListener('input', function(e) { // Get only numbers let value = this.value.replace(/[^0-9]/g, ''); // Limit to maxLen digits if (value.length > maxLen) { value = value.slice(0, maxLen); } // Validate against max value when full length reached if (value.length === maxLen) { const numValue = parseInt(value, 10); if (numValue > maxVal) { value = maxVal.toString().padStart(maxLen, '0'); } } this.value = value; // Auto-switch when reached maxLen and not the last input if (value.length === maxLen && index < timeInputs.length - 1) { const nextInput = timeInputs[index + 1]; setTimeout(() => { nextInput.focus(); nextInput.select(); }, 10); } }); // Handle backspace to go to previous input and arrow navigation input.addEventListener('keydown', function(e) { if (e.key === 'Backspace' && this.value.length === 0 && index > 0) { e.preventDefault(); const prevInput = timeInputs[index - 1]; prevInput.focus(); prevInput.select(); } if (e.key === 'ArrowRight' && index < timeInputs.length - 1) { e.preventDefault(); const nextInput = timeInputs[index + 1]; nextInput.focus(); nextInput.select(); } if (e.key === 'ArrowLeft' && index > 0) { e.preventDefault(); const prevInput = timeInputs[index - 1]; prevInput.focus(); prevInput.select(); } }); // Format with leading zero on blur for 1- or 2-digit fields (hours/min/sec) input.addEventListener('blur', function() { if (!this.value) return; if (maxLen <= 2 && this.value.length === 1) { this.value = '0' + this.value; } }); }); // Prevent drag and drop of text timeInputs.forEach(input => { input.addEventListener('drop', function(e) { e.preventDefault(); return false; }); input.addEventListener('dragover', function(e) { e.preventDefault(); return false; }); }); }); // Timer Input Auto-Switch with Input Masking document.addEventListener('DOMContentLoaded', function() { const timerDays = document.getElementById('timer-days'); const timerHours = document.getElementById('timer-hours'); const timerMinutes = document.getElementById('timer-minutes'); const timerSeconds = document.getElementById('timer-seconds'); // Array of timer inputs const timerInputs = [timerDays, timerHours, timerMinutes, timerSeconds]; // Set max values for validation const maxValues = [maxtime, 23, 59, 59]; // Initialize timer with default value (30 seconds) timerDays.value = ''; timerHours.value = ''; timerMinutes.value = ''; timerSeconds.value = timer; timerInputs.forEach((input, index) => { const maxVal = maxValues[index]; const maxLen = maxVal.toString().length; // allows 3 digits for days, 2 for others // Only allow numeric input input.addEventListener('keypress', function(e) { const charCode = e.which ? e.which : e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { e.preventDefault(); return false; } return true; }); // Handle input with auto-switch input.addEventListener('input', function(e) { // Get only numbers let value = this.value.replace(/[^0-9]/g, ''); // Limit to maxLen digits if (value.length > maxLen) { value = value.slice(0, maxLen); } // Validate against max value when full length reached if (value.length === maxLen) { const numValue = parseInt(value, 10); if (numValue > maxVal) { value = maxVal.toString().padStart(maxLen, '0'); } } this.value = value; // Auto-switch when reached maxLen and not the last input if (value.length === maxLen && index < timerInputs.length - 1) { const nextInput = timerInputs[index + 1]; setTimeout(() => { nextInput.focus(); nextInput.select(); }, 10); } }); // Handle backspace to go to previous input and arrow navigation input.addEventListener('keydown', function(e) { if (e.key === 'Backspace' && this.value.length === 0 && index > 0) { e.preventDefault(); const prevInput = timerInputs[index - 1]; prevInput.focus(); prevInput.select(); } if (e.key === 'ArrowRight' && index < timerInputs.length - 1) { e.preventDefault(); const nextInput = timerInputs[index + 1]; nextInput.focus(); nextInput.select(); } if (e.key === 'ArrowLeft' && index > 0) { e.preventDefault(); const prevInput = timerInputs[index - 1]; prevInput.focus(); prevInput.select(); } }); // Format with leading zero on blur for 1- or 2-digit fields (hours/min/sec) input.addEventListener('blur', function() { if (!this.value) return; if (maxLen <= 2 && this.value.length === 1) { this.value = '0' + this.value; } }); }); // Prevent drag and drop of text timerInputs.forEach(input => { input.addEventListener('drop', function(e) { e.preventDefault(); return false; }); input.addEventListener('dragover', function(e) { e.preventDefault(); return false; }); }); });