/**
* Temu Affiliate Funnel
* Main JavaScript File
*/
// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
// Language selector functionality
const languageSelector = document.querySelector('.language-selector');
if (languageSelector) {
const selectedLanguage = languageSelector.querySelector('.selected-language');
const languageDropdown = languageSelector.querySelector('.language-dropdown');
// Toggle dropdown on click
selectedLanguage.addEventListener('click', function(e) {
e.stopPropagation();
const isOpen = languageDropdown.classList.contains('show');
if (isOpen) {
languageDropdown.classList.remove('show');
languageSelector.classList.remove('active');
} else {
languageDropdown.classList.add('show');
languageSelector.classList.add('active');
}
});
// Close dropdown when clicking outside
document.addEventListener('click', function() {
languageDropdown.classList.remove('show');
languageSelector.classList.remove('active');
});
// Prevent dropdown from closing when clicking inside
languageDropdown.addEventListener('click', function(e) {
e.stopPropagation();
});
}
// Form validation
const funnelForms = document.querySelectorAll('.funnel-form');
funnelForms.forEach(form => {
form.addEventListener('submit', function(e) {
// Step 1: Shopping frequency validation
const frequencyInputs = form.querySelectorAll('input[name="shopping_frequency"]');
if (frequencyInputs.length > 0) {
let frequencySelected = false;
frequencyInputs.forEach(input => {
if (input.checked) frequencySelected = true;
});
if (!frequencySelected) {
e.preventDefault();
alert('Please select a shopping frequency option.');
return;
}
}
// Step 2: Interests validation
const interestInputs = form.querySelectorAll('input[name="interests[]"]');
if (interestInputs.length > 0) {
let interestSelected = false;
interestInputs.forEach(input => {
if (input.checked) interestSelected = true;
});
if (!interestSelected) {
e.preventDefault();
alert('Please select at least one interest.');
return;
}
}
// Step 3: Budget validation
const budgetInputs = form.querySelectorAll('input[name="budget"]');
if (budgetInputs.length > 0) {
let budgetSelected = false;
budgetInputs.forEach(input => {
if (input.checked) budgetSelected = true;
});
if (!budgetSelected) {
e.preventDefault();
alert('Please select a budget option.');
return;
}
}
// Step 4: Device validation
const deviceInputs = form.querySelectorAll('input[name="device"]');
if (deviceInputs.length > 0) {
let deviceSelected = false;
deviceInputs.forEach(input => {
if (input.checked) deviceSelected = true;
});
if (!deviceSelected) {
e.preventDefault();
alert('Please select a device option.');
return;
}
}
});
});
// Copy promotion code functionality (original)
const copyButtons = document.querySelectorAll('.copy-button[data-code]');
copyButtons.forEach(button => {
button.addEventListener('click', function() {
const code = this.getAttribute('data-code');
// Use modern clipboard API if available
if (navigator.clipboard) {
navigator.clipboard.writeText(code)
.then(() => {
showCopyFeedback(button);
})
.catch(() => {
fallbackCopyTextToClipboard(code, button);
});
} else {
fallbackCopyTextToClipboard(code, button);
}
});
});
// Single-page landing: Copy coupon code functionality
const singlePageCopyBtn = document.getElementById('copyBtn');
if (singlePageCopyBtn) {
singlePageCopyBtn.addEventListener('click', function() {
const couponCodeElement = document.getElementById('couponCode');
if (couponCodeElement) {
const code = couponCodeElement.innerText.trim();
// Use modern clipboard API if available
if (navigator.clipboard) {
navigator.clipboard.writeText(code)
.then(() => {
showSinglePageCopyFeedback(singlePageCopyBtn);
})
.catch(() => {
fallbackCopyTextToClipboard(code, singlePageCopyBtn);
});
} else {
fallbackCopyTextToClipboard(code, singlePageCopyBtn);
}
}
});
}
// Fallback for older browsers that don't support clipboard API
function fallbackCopyTextToClipboard(text, button) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
if (successful) {
showCopyFeedback(button);
}
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
// Show feedback when code is copied (original)
function showCopyFeedback(button) {
const originalIcon = button.innerHTML;
button.innerHTML = '';
button.style.backgroundColor = 'var(--color-success)';
setTimeout(() => {
button.innerHTML = originalIcon;
button.style.backgroundColor = '';
}, 2000);
}
// Show feedback for single-page copy button
function showSinglePageCopyFeedback(button) {
const originalContent = button.innerHTML;
button.innerHTML = ' Copied!';
button.style.backgroundColor = '#10b981';
button.style.color = 'white';
// Track coupon copy event
if (typeof ttq !== 'undefined') {
try {
ttq.track('Contact', {
content_id: 'voucher_magnet_coupon',
content_type: 'product',
currency: 'USD',
value: 0
});
console.log('✅ TikTok Contact event tracked');
} catch (error) {
console.error('❌ TikTok Contact tracking failed:', error);
}
}
setTimeout(() => {
button.innerHTML = originalContent;
button.style.backgroundColor = '';
button.style.color = '';
}, 2000);
}
// Single-page analytics tracking
function initializeSinglePageAnalytics() {
// Track conversion links with proper events
document.addEventListener('click', function(e) {
if (e.target.closest('.conversion-link')) {
const link = e.target.closest('.conversion-link');
const href = link.getAttribute('href');
console.log('Conversion link clicked:', href);
// Fire TikTok conversion event (proper conversion tracking)
if (typeof ttq !== 'undefined') {
try {
ttq.track('CompleteRegistration', {
content_id: 'voucher_magnet_conversion',
content_type: 'product',
value: 0,
currency: 'USD'
});
console.log('✅ TikTok CompleteRegistration tracked for:', href);
} catch (error) {
console.error('❌ TikTok conversion tracking failed:', error);
}
} else {
console.warn('⚠️ TikTok pixel not available');
}
}
});
}
// Sharing functionality
window.sharePromotion = function(platform) {
const promoLink = document.getElementById('promoLink');
let shareUrl = '';
if (!promoLink) return;
const url = promoLink.getAttribute('href');
const title = document.title;
const text = 'Check out this amazing deal on Temu!';
switch (platform) {
case 'facebook':
shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`;
break;
case 'twitter':
shareUrl = `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`;
break;
case 'whatsapp':
shareUrl = `https://wa.me/?text=${encodeURIComponent(text + ' ' + url)}`;
break;
case 'telegram':
shareUrl = `https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`;
break;
}
if (shareUrl) {
window.open(shareUrl, '_blank', 'width=600,height=400');
}
};
// Add touch support for mobile devices
if ('ontouchstart' in window) {
document.body.classList.add('touch-device');
}
// Countdown Timer for Single-Page Landing with persistent cookie storage
function initializeCountdownTimer() {
const countdownElement = document.getElementById('countdown');
if (!countdownElement) return;
const cookieName = 'voucher_magnet_timer_end';
let endTime;
// Check if timer end time exists in cookie
const savedEndTime = getCookie(cookieName);
const currentTime = new Date().getTime();
if (savedEndTime) {
// Cookie exists, continue from saved end time
endTime = parseInt(savedEndTime);
} else {
// No saved timer, start new 24-hour countdown
endTime = currentTime + (24 * 60 * 60 * 1000); // 24 hours in milliseconds
setCookie(cookieName, endTime.toString(), 12); // Cookie expires in 12 hours
}
const timerInterval = setInterval(function() {
const now = new Date().getTime();
const remainingTime = endTime - now;
// Check if timer has expired
if (remainingTime <= 0) {
clearInterval(timerInterval);
countdownElement.textContent = '00:00:00';
// Remove expired cookie
deleteCookie(cookieName);
// Optional: Hide timer or show expired message
const timerContainer = document.getElementById('urgencyTimer');
if (timerContainer) {
timerContainer.style.opacity = '0.5';
const timerLabel = timerContainer.querySelector('.timer-label');
if (timerLabel) {
timerLabel.textContent = 'Offer expired';
}
}
return;
}
// Calculate hours, minutes, seconds from remaining time
const seconds = Math.floor(remainingTime / 1000);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
// Format with leading zeros
const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
countdownElement.textContent = timeString;
}, 1000);
}
// Cookie helper functions for timer
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function setCookie(name, value, hours) {
const expires = new Date();
expires.setTime(expires.getTime() + (hours * 60 * 60 * 1000));
document.cookie = name + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
}
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;';
}
// FAQ Accordion Functionality
function initializeFAQAccordion() {
const faqItems = document.querySelectorAll('.faq-item');
faqItems.forEach(item => {
const question = item.querySelector('.faq-question');
const answer = item.querySelector('.faq-answer');
const icon = question ? question.querySelector('i') : null;
if (question && answer) {
// Initially hide all answers with proper styling
answer.style.display = 'none';
answer.style.maxHeight = '0';
answer.style.overflow = 'hidden';
answer.style.transition = 'all 0.3s ease-in-out';
answer.style.opacity = '0';
question.addEventListener('click', function(e) {
e.preventDefault();
const isOpen = answer.style.display === 'block';
// Close all other FAQ items with animation
faqItems.forEach(otherItem => {
const otherAnswer = otherItem.querySelector('.faq-answer');
const otherIcon = otherItem.querySelector('.faq-question i');
const otherQuestion = otherItem.querySelector('.faq-question');
if (otherAnswer && otherAnswer !== answer) {
otherAnswer.style.maxHeight = '0';
otherAnswer.style.opacity = '0';
setTimeout(() => {
otherAnswer.style.display = 'none';
}, 300);
if (otherIcon) {
otherIcon.style.transform = 'rotate(0deg)';
otherIcon.style.transition = 'transform 0.3s ease';
}
if (otherQuestion) {
otherQuestion.classList.remove('faq-active');
}
}
});
// Toggle current item with smooth animation
if (!isOpen) {
answer.style.display = 'block';
// Get the actual height needed
const scrollHeight = answer.scrollHeight;
answer.style.maxHeight = scrollHeight + 'px';
answer.style.opacity = '1';
if (icon) {
icon.style.transform = 'rotate(180deg)';
icon.style.transition = 'transform 0.3s ease';
}
question.classList.add('faq-active');
} else {
answer.style.maxHeight = '0';
answer.style.opacity = '0';
setTimeout(() => {
answer.style.display = 'none';
}, 300);
if (icon) {
icon.style.transform = 'rotate(0deg)';
}
question.classList.remove('faq-active');
}
});
}
});
}
// Initialize new single-page functionality
initializeCountdownTimer();
initializeFAQAccordion();
initializeSinglePageAnalytics();
// Universal conversion tracking for ALL links (TikTok + Google Ads)
function initializeConversionTracking() {
// Track clicks on ALL links
document.addEventListener('click', function(e) {
// Check if clicked element is any link (a tag or has href)
const link = e.target.closest('a[href]') || e.target.closest('[href]');
if (link && link.getAttribute('href')) {
const href = link.getAttribute('href');
// Skip internal page fragments and javascript links
if (href.startsWith('#') || href.startsWith('javascript:') || href === '') {
return;
}
console.log('🔗 Link clicked, firing pixels for:', href);
// Fire TikTok conversion event for all links
if (typeof ttq !== 'undefined') {
try {
ttq.track('CompleteRegistration', {
content_id: 'voucher_magnet_conversion',
content_type: 'product',
value: 0,
currency: 'USD',
url: href
});
console.log('✅ TikTok pixel fired for:', href);
} catch (error) {
console.error('❌ TikTok pixel failed:', error);
}
} else {
console.warn('⚠️ TikTok pixel not available');
}
// Fire Google Ads conversion event for all links
if (typeof gtag !== 'undefined') {
try {
gtag('event', 'conversion', {
'send_to': 'AW-16748667643/OBKcCLiiofgaEPvFsbI-',
'value': 0,
'currency': 'USD',
'url': href
});
console.log('✅ Google Ads pixel fired for:', href);
} catch (error) {
console.error('❌ Google Ads pixel failed:', error);
}
} else {
console.warn('⚠️ Google Ads pixel not available');
}
// For external links, prevent default and control redirect timing
if (href.startsWith('http') && !href.includes(window.location.hostname)) {
console.log('🌐 External link detected, controlling redirect timing');
e.preventDefault();
// Small delay to ensure pixels fire before redirect
setTimeout(() => {
if (link.target === '_blank') {
window.open(href, '_blank');
} else {
window.location.href = href;
}
}, 300); // Increased delay to ensure pixel firing
return false;
}
// For internal links, let them proceed normally (pixels still fire)
}
});
}
// Initialize conversion tracking
initializeConversionTracking();
// Auto-redirect to Temu promotion after a delay on results page
const resultsPage = document.querySelector('.results-page');
if (resultsPage) {
const promoLink = document.getElementById('promoLink');
if (promoLink) {
// Track when user clicks the promotion link
promoLink.addEventListener('click', function() {
console.log('Promotion link clicked');
});
}
}
// Automatically check first option in each step for better UX
const optionGroups = document.querySelectorAll('.options-container');
optionGroups.forEach(group => {
// Only auto-select if none are already selected
const radioInputs = group.querySelectorAll('input[type="radio"]');
if (radioInputs.length > 0) {
let anyChecked = false;
radioInputs.forEach(input => {
if (input.checked) anyChecked = true;
});
// Auto-select first option if none are checked
if (!anyChecked && !group.classList.contains('interests-grid')) {
radioInputs[0].checked = true;
}
}
});
});