<script type="application/javascript">
// Array of random direct links
const links = [
    'https://freepopnews.skin/ppp.php',
    'https://freepopnews.skin/ppp.php',
    'https://freepopnews.skin/sites.php'
];

// Function to set a cookie
function setCookie(name, value, minutes) {
    const expires = new Date();
    expires.setTime(expires.getTime() + (minutes * 60 * 1000)); // Set expiration time to minutes
    document.cookie = name + "=" + value + ";expires=" + expires.toUTCString() + ";path=/";
}

// Function to get a cookie by name
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 to open popunder
function openPopunder() {
    // Select a random link from the array
    const randomLink = links[Math.floor(Math.random() * links.length)];

    // Open a new window/popunder
    const popunder = window.open(randomLink, '_blank');

    // Check for popunder support and focus on the original window
    if (popunder) {
        popunder.blur(); // Optional, move focus away from the new window
        window.focus(); // Bring focus back to the original window
    }
}

// Track the click count
let clickCount = 0;

// Prevent multiple popunders from opening rapidly
let isPopunderOpen = false;

// Attach click event listener to open popunder on the second click
document.addEventListener('click', function() {
    // Increment the click count
    clickCount++;

    // Get the current count of popunders opened per page, including query string
    const pagePath = location.pathname; // Get the full path of the current page
    const pageQuery = location.search; // Get the query string (e.g., ?s=...)
    const cookieKey = 'popunderCount' + pagePath + pageQuery; // Use both path and query for cookie

    let popunderCount = parseInt(getCookie(cookieKey)) || 0;

    // Allow opening popunders until we reach the limit of 3
    if (clickCount === 2 && popunderCount < 3) {
        if (!isPopunderOpen) { // Check if no popunder is currently open
            isPopunderOpen = true; // Disable further popunders for a moment
            openPopunder(); // Open the popunder
            
            // Increment the popunder count and set it in cookie (expire after 10 minutes)
            popunderCount++; // Increment count
            setCookie(cookieKey, popunderCount, 1); // Set/Update cookie for 10 minutes

            // Reset the flag and click count after a brief delay
            setTimeout(() => {
                isPopunderOpen = false; // Allow another popunder to open after 10 seconds
                clickCount = 0; // Reset click count for the next sequence
            }, 5000); // 10000 milliseconds = 10 seconds
        }
    }
});
</script>
