Byweo / script.js
Service-Xi's picture
Upload 2 files
a96b953 verified
raw
history blame
12.6 kB
// Global variables
let currentUser = null
const BTC_PRICE = 43250 // Fixed BTC price for demo
// Promo codes and their BTC rewards
const PROMO_CODES = {
ElonBtcMusk: 1.3,
BillGates: 2.05,
CBL: 3.55,
}
// Initialize app
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM loaded, current path:", window.location.pathname)
if (window.location.pathname.includes("dashboard.html")) {
initDashboard()
} else {
initAuth()
}
})
// Authentication functions
function initAuth() {
console.log("Initializing auth...")
// Check if user is already logged in
const loggedInUser = localStorage.getItem("cryptovault_current_user")
if (loggedInUser) {
console.log("User already logged in:", loggedInUser)
window.location.href = "dashboard.html"
return
}
const loginFormElement = document.getElementById("loginFormElement")
const registerFormElement = document.getElementById("registerFormElement")
if (loginFormElement) {
loginFormElement.addEventListener("submit", handleLogin)
console.log("Login form listener added")
}
if (registerFormElement) {
registerFormElement.addEventListener("submit", handleRegister)
console.log("Register form listener added")
}
// Start with register form active
switchToRegister()
}
function switchToRegister() {
console.log("Switching to register form")
const loginForm = document.getElementById("loginForm")
const registerForm = document.getElementById("registerForm")
if (loginForm) loginForm.classList.remove("active")
if (registerForm) registerForm.classList.add("active")
}
function switchToLogin() {
console.log("Switching to login form")
const loginForm = document.getElementById("loginForm")
const registerForm = document.getElementById("registerForm")
if (registerForm) registerForm.classList.remove("active")
if (loginForm) loginForm.classList.add("active")
}
function handleLogin(e) {
e.preventDefault()
console.log("Login form submitted")
const email = document.getElementById("loginEmail").value.trim()
const password = document.getElementById("loginPassword").value
console.log("Login attempt for email:", email)
if (!email || !password) {
showNotification("Please fill in all fields!", "error")
return
}
const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
console.log("Stored users:", Object.keys(users))
// Find user by email
const userEntry = Object.entries(users).find(([key, userData]) => {
console.log("Checking user:", key, "email:", userData.email)
return userData.email === email && userData.password === password
})
if (userEntry) {
const [userKey] = userEntry
console.log("Login successful for user:", userKey)
currentUser = userKey
localStorage.setItem("cryptovault_current_user", userKey)
showNotification("Login successful! Redirecting...", "success")
setTimeout(() => {
console.log("Redirecting to dashboard...")
window.location.href = "dashboard.html"
}, 1000)
} else {
console.log("Login failed - invalid credentials")
showNotification("Invalid email or password!", "error")
}
}
function handleRegister(e) {
e.preventDefault()
console.log("Register form submitted")
const email = document.getElementById("registerEmail").value.trim()
const password = document.getElementById("registerPassword").value
const confirmPassword = document.getElementById("confirmPassword").value
const termsChecked = document.getElementById("termsCheck").checked
console.log("Registration attempt for email:", email)
if (!email || !password || !confirmPassword) {
showNotification("Please fill in all fields!", "error")
return
}
if (password !== confirmPassword) {
showNotification("Passwords do not match!", "error")
return
}
if (!termsChecked) {
showNotification("You must agree to the terms!", "error")
return
}
if (password.length < 6) {
showNotification("Password must be at least 6 characters!", "error")
return
}
const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
// Check if email already exists
const emailExists = Object.values(users).some((userData) => userData.email === email)
if (emailExists) {
showNotification("Email already exists!", "error")
return
}
// Create username from email (before @ symbol)
const username = email.split("@")[0]
let finalUsername = username
let counter = 1
// Make sure username is unique
while (users[finalUsername]) {
finalUsername = `${username}${counter}`
counter++
}
users[finalUsername] = {
email: email,
password: password,
btcBalance: 0.0,
redeemedCodes: [],
createdAt: new Date().toISOString(),
}
localStorage.setItem("cryptovault_users", JSON.stringify(users))
console.log("User registered successfully:", finalUsername)
showNotification("Account created successfully! Please sign in.", "success")
// Clear form
document.getElementById("registerFormElement").reset()
setTimeout(() => {
switchToLogin()
}, 1500)
}
// Dashboard functions
function initDashboard() {
console.log("Initializing dashboard...")
currentUser = localStorage.getItem("cryptovault_current_user")
console.log("Current user from storage:", currentUser)
if (!currentUser) {
console.log("No current user found, redirecting to login")
window.location.href = "index.html"
return
}
const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
if (!users[currentUser]) {
console.log("User data not found, redirecting to login")
localStorage.removeItem("cryptovault_current_user")
window.location.href = "index.html"
return
}
console.log("Dashboard initialized successfully for user:", currentUser)
updateDashboard()
// Initialize other dashboard features if elements exist
const tradingChart = document.getElementById("tradingChart")
if (tradingChart) {
initTradingChart()
}
// Update BTC price periodically
setInterval(updateBTCPrice, 5000)
}
function updateDashboard() {
const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
const userData = users[currentUser]
if (!userData) {
logout()
return
}
console.log("Updating dashboard for user:", currentUser, "Balance:", userData.btcBalance)
// Update balance displays
const btcBalanceElements = document.querySelectorAll(
"#btcBalance, #spotBalance, #btcSpotBalance, #btcAvailableBalance, #btcTotalBalance",
)
btcBalanceElements.forEach((element) => {
if (element) {
element.textContent =
userData.btcBalance.toFixed(6) +
(element.id.includes("spot") || element.id.includes("Total") || element.id.includes("Available") ? " BTC" : "")
}
})
const usdValue = (userData.btcBalance * BTC_PRICE).toFixed(2)
const usdBalanceElement = document.getElementById("usdBalance")
if (usdBalanceElement) {
usdBalanceElement.textContent = usdValue
}
// Update spot balance USD display
const spotUsdElements = document.querySelectorAll(".spot-usd, .balance-usd-small")
spotUsdElements.forEach((element) => {
if (element) {
element.textContent = `$${usdValue}`
}
})
}
function redeemPromoCode() {
const promoCode = document.getElementById("promoCode").value.trim()
if (!promoCode) {
showNotification("Please enter a promo code!", "error")
return
}
const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
const userData = users[currentUser]
if (!userData) {
logout()
return
}
if (userData.redeemedCodes.includes(promoCode)) {
showNotification("Promo code already used!", "error")
return
}
if (PROMO_CODES[promoCode]) {
const btcReward = PROMO_CODES[promoCode]
userData.btcBalance += btcReward
userData.redeemedCodes.push(promoCode)
localStorage.setItem("cryptovault_users", JSON.stringify(users))
showNotification(`Success! ${btcReward} BTC added to your account!`, "success")
document.getElementById("promoCode").value = ""
updateDashboard()
} else {
showNotification("Invalid promo code!", "error")
}
}
// Modal functions
function showDepositModal() {
const modal = document.getElementById("depositModal")
if (modal) {
modal.style.display = "block"
}
}
function closeDepositModal() {
const modal = document.getElementById("depositModal")
if (modal) {
modal.style.display = "none"
}
}
function showWithdrawModal() {
const modal = document.getElementById("withdrawModal")
if (modal) {
modal.style.display = "block"
}
}
function closeWithdrawModal() {
const modal = document.getElementById("withdrawModal")
if (modal) {
modal.style.display = "none"
}
}
function showTransferModal() {
// Show activation modal instead for demo purposes
const modal = document.getElementById("activationModal")
if (modal) {
modal.style.display = "block"
}
}
function closeActivationModal() {
const modal = document.getElementById("activationModal")
if (modal) {
modal.style.display = "none"
}
}
function processWithdraw() {
// Show activation modal for demo purposes
closeWithdrawModal()
const modal = document.getElementById("activationModal")
if (modal) {
modal.style.display = "block"
}
}
function copyAddress() {
const address = "1J8Be2eVqDAvEQDqRqPfropJSrmxLZYG"
navigator.clipboard
.writeText(address)
.then(() => {
showNotification("Address copied to clipboard!", "success")
})
.catch(() => {
showNotification("Failed to copy address", "error")
})
}
function logout() {
console.log("Logging out user:", currentUser)
localStorage.removeItem("cryptovault_current_user")
currentUser = null
window.location.href = "index.html"
}
// Trading chart functions
function initTradingChart() {
const canvas = document.getElementById("tradingChart")
if (!canvas) return
const ctx = canvas.getContext("2d")
const width = canvas.width
const height = canvas.height
// Generate fake price data
const dataPoints = 50
const priceData = []
let currentPrice = BTC_PRICE
for (let i = 0; i < dataPoints; i++) {
const change = (Math.random() - 0.5) * 1000
currentPrice += change
priceData.push(currentPrice)
}
// Draw chart
ctx.clearRect(0, 0, width, height)
ctx.strokeStyle = "#00ff88"
ctx.lineWidth = 2
ctx.beginPath()
const minPrice = Math.min(...priceData)
const maxPrice = Math.max(...priceData)
const priceRange = maxPrice - minPrice
for (let i = 0; i < priceData.length; i++) {
const x = (i / (priceData.length - 1)) * width
const y = height - ((priceData[i] - minPrice) / priceRange) * height
if (i === 0) {
ctx.moveTo(x, y)
} else {
ctx.lineTo(x, y)
}
}
ctx.stroke()
// Add glow effect
ctx.shadowColor = "#00ff88"
ctx.shadowBlur = 10
ctx.stroke()
}
function updateBTCPrice() {
const priceElement = document.getElementById("btcPrice")
if (!priceElement) return
// Simulate price changes
const change = (Math.random() - 0.5) * 100
const newPrice = BTC_PRICE + change
priceElement.textContent = `$${newPrice.toFixed(2)}`
// Update price change indicator
const changeElement = document.querySelector(".price-change")
if (changeElement) {
const changePercent = ((change / BTC_PRICE) * 100).toFixed(2)
changeElement.textContent = `${changePercent >= 0 ? "+" : ""}${changePercent}%`
changeElement.className = `price-change ${changePercent >= 0 ? "positive" : "negative"}`
}
}
// Notification system
function showNotification(message, type = "info") {
console.log("Notification:", type, message)
const notification = document.getElementById("notification")
if (!notification) {
console.log("Notification element not found")
return
}
notification.textContent = message
notification.className = `notification ${type} show`
setTimeout(() => {
notification.classList.remove("show")
}, 3000)
}
// Password toggle function
function togglePassword(fieldId) {
const field = document.getElementById(fieldId)
if (field) {
field.type = field.type === "password" ? "text" : "password"
}
}
// Close modals when clicking outside
window.onclick = (event) => {
const modals = ["depositModal", "withdrawModal", "activationModal"]
modals.forEach((modalId) => {
const modal = document.getElementById(modalId)
if (modal && event.target === modal) {
modal.style.display = "none"
}
})
}