0% found this document useful (0 votes)
2 views

Scripts 2

The document contains JavaScript code for a web application that updates JSON data, filters events by competition, and manages UI elements such as buttons and iframes. It includes functions for counting events, changing styles based on statuses, and dynamically updating content based on user interactions. Additionally, it handles fetching data from external sources and managing background images based on selected events.

Uploaded by

sfssuccess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Scripts 2

The document contains JavaScript code for a web application that updates JSON data, filters events by competition, and manages UI elements such as buttons and iframes. It includes functions for counting events, changing styles based on statuses, and dynamically updating content based on user interactions. Additionally, it handles fetching data from external sources and managing background images based on selected events.

Uploaded by

sfssuccess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

<script>

// Función para actualizar y obtener el JSON


function updateJSON() {
$.ajax({
url: 'js/json.php', // Cambia a la ruta de tu script PHP
method: 'GET',
success: function (data) {
//console.log("JSON actualizado o leído:", data); // Muestra el
JSON actualizado o leído
// Aquí puedes procesar el JSON como necesites
},
error: function (error) {
console.error("Error al actualizar JSON:", error);
}
});
}

// Llama a la función inmediatamente al cargar la página


$(document).ready(function() {
updateJSON(); // Llama a la función al cargar la página

// Configura el intervalo para que se ejecute cada 5 minutos


setInterval(updateJSON, 300000); // 120000 ms = 5 minutos
});

//Cambiar color de los status


function label() {
$(function() {
$('.i-status').each(function(){
//console.log($(this).text());
var text = $(this).text().toLowerCase();
switch (text) {
case 'en vivo':
color = '#d30f0f';
color2 = '#fff';
break;
case 'pronto':
color = '#ff9933';
color2 = '#000';
break;
case 'finalizado':
color = '#000';
color2 = '#fff';
break;
default:
color = '#000';
}
$(this).css('background', color);
$(this).css('color', color2);

});
});
}

//Cargar la lista de ventos y filtro


document.addEventListener('DOMContentLoaded', function() {
// Function to populate the dropdown with competition names
function populateDropdown() {
const navList = document.getElementById('nav');
const competitionFilter = document.getElementById('competitionFilter');
const items = navList.getElementsByTagName('li');

// Extract unique competition names


const competitions = new Set();
for (let item of items) {
const aTag = item.querySelector('a');
if (aTag) {
const competitionName = aTag.textContent.split(':')[0].trim();
competitions.add(competitionName);
}
}

// Convert Set to Array and sort it alphabetically


const sortedCompetitions = Array.from(competitions).sort();

// Clear existing options (except the first one)


competitionFilter.innerHTML = '<option value="">Todos los
Eventos</option>';

// Populate the dropdown with sorted competitions


sortedCompetitions.forEach(competition => {
const option = document.createElement('option');
option.value = competition;
option.textContent = competition;
competitionFilter.appendChild(option);
});
}

// Function to filter the list based on selected competition


function filterList() {
const competitionFilter = document.getElementById('competitionFilter');
const selectedCompetition = competitionFilter.value;
const items = document.getElementById('nav').getElementsByTagName('li');

// Remove the "show" class from all items


for (let item of items) {
item.classList.remove('show');
}

console.log("Selected Competition:", selectedCompetition); // Log selected


competition

for (let item of items) {


const aTag = item.querySelector('a');
if (aTag) {
const competitionName = aTag.textContent.split(':')[0].trim();
console.log("Current Competition Name:", competitionName); // Log
current competition name

// Show or hide the item based on the selected competition


if (selectedCompetition === '' || competitionName ===
selectedCompetition) {
item.style.display = ''; // Show the item
item.classList.add('show'); // Add "show" class back to the
item
} else {
item.style.display = 'none'; // Hide the item
}
}
}
}

// Set up a MutationObserver to watch for changes in the list


const observer = new MutationObserver(() => {
populateDropdown();
});

// Start observing the nav list for child additions


const navList = document.getElementById('nav');
if (navList) {
observer.observe(navList, { childList: true, subtree: true });
} else {
console.error("navList is not found in the DOM.");
}

// Add event listener for the dropdown change


document.getElementById('competitionFilter').addEventListener('change',
filterList);
});

//Cargar numero de eventos a botones


function updateButtonCounts() {
var counts = {
all: 0,
vivo: 0,
futbol: 0,
basketball: 0,
americano: 0,
beis: 0,
tenis: 0,
box: 0,
carreras: 0,
hockey: 0,
otros: 0,
finalizado: 0
};

var x = document.getElementsByClassName("filter");
for (var i = 0; i < x.length; i++) {
counts.all++;
if (x[i].classList.contains("vivo")) counts.vivo++;
if (x[i].classList.contains("fútbol") ||
x[i].classList.contains("fútbol_cup")) counts.futbol++;
if (x[i].classList.contains("basketball") ||
x[i].classList.contains("baloncesto")) counts.basketball++;
if (x[i].classList.contains("americano") || x[i].classList.contains("nfl"))
counts.americano++;
if (x[i].classList.contains("beisbol") || x[i].classList.contains("mlb"))
counts.beis++;
if (x[i].classList.contains("tenis") || x[i].classList.contains("atp") ||
x[i].classList.contains("wta")) counts.tenis++;
if (x[i].classList.contains("box") || x[i].classList.contains("ufc") ||
x[i].classList.contains("wwe") || x[i].classList.contains("aew")) counts.box++;
if (x[i].classList.contains("motor")) counts.carreras++;
if (x[i].classList.contains("hockey") || x[i].classList.contains("nhl"))
counts.hockey++;
if (x[i].classList.contains("otros") || x[i].classList.contains("unknown")
|| x[i].classList.contains("rugby") || x[i].classList.contains("event") ||
x[i].classList.contains("other")) counts.otros++;
if (x[i].classList.contains("finalizado")) counts.finalizado++;
}

// Update button text


document.getElementById("all").innerText = `Todos (${counts.all})`;
document.getElementById("vivo").innerText = `En Vivo (${counts.vivo})`;
document.getElementById("futbol").innerText = `Fútbol (${counts.futbol})`;
document.getElementById("basket").innerText = `Basket (${counts.basketball})`;
document.getElementById("americano").innerText = `NFL (${counts.americano})`;
document.getElementById("beis").innerText = `Baseball (${counts.beis})`;
document.getElementById("tenis").innerText = `Tenis (${counts.tenis})`;
document.getElementById("box").innerText = `Box/UFC (${counts.box})`;
document.getElementById("carreras").innerText = `Carreras ($
{counts.carreras})`;
document.getElementById("hockey").innerText = `Hockey (${counts.hockey})`;
document.getElementById("otros").innerText = `Otros (${counts.otros})`;
document.getElementById("showwidget").innerText = `Ended ($
{counts.finalizado})`;
}

//Aplicar filtro al seleccionar botones


filterSelection(["all"]);
function filterSelection(classes) {
var x, i;
x = document.getElementsByClassName("filter");
if (classes.includes("all")) classes = [" "]; // If "all" is selected, show all
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
for (var j = 0; j < classes.length; j++) {
if (x[i].className.indexOf(classes[j]) > -1) {
w3AddClass(x[i], "show");
}
}
}
}

function w3AddClass(element, name) {


var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}

function w3RemoveClass(element, name) {


var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}

// Add active class to the current button (highlight it)


var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("bton");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}

//Cargar video en el iframe


function setIFrameSrc(theiframe, url) {
var originalFrame = $('#' + theiframe); // Use jQuery to select the iframe

var newFrame = $('<iframe>', {


id: "theiframe",
width: "90%",
height: "76%",
src: url,
class: "frame",
frameborder: "0",
allow: "encrypted-media;fullscreen",
scrolling: "1",
});

// Step 1: Fade out the original iframe


originalFrame.fadeOut(300, function() {
// Step 2: Replace the original iframe with the new one
originalFrame.remove();
// Step 3: Fade in the new iframe
$('#containerf').append(newFrame);
newFrame.hide(); // Hide the new iframe initially
newFrame.fadeIn(300); // Fade in the new iframe

// Step 4: Check for the presence of the element after 10 seconds


setTimeout(function() {
if ($('#widgets-loader_0\\.vnigd5ihlb7').length > 0) { // Check for the
ID
// If the element is present, set the iframe attributes accordingly
newFrame.css({
'top': '31vh',
'position': 'relative', // Ensure position is relative
'z-index': '1000', // Set a high z-index to ensure visibility
'height': '55vh'
});
} else {
// If the element is not present, set the iframe attributes
accordingly
newFrame.css({
'top': '15vh',
'position': 'relative', // Ensure position is relative
'z-index': '1000', // Set a high z-index to ensure visibility
'height': '76%'
});
}
}, 6000); // 10 seconds in milliseconds
});
}

// Al hacer clic en el botón con id 'showwidget', elimina el iframe y crea uno


nuevo
document.getElementById('showwidget').addEventListener('click', function() {
var originalFrame = $('#theiframe'); // Usa jQuery para seleccionar el
iframe

// Eliminar el iframe original si existe


if (originalFrame.length) {
originalFrame.remove(); // Elimina el iframe del DOM
}

// Crear un nuevo iframe


var newFrame = $('<iframe>', {
id: "theiframe", // Asegúrate de que el ID sea único
width: "100%",
height: "100%",
src: "https://sports.zya.me/widget.html",
frameborder: "0",
allow: "encrypted-media;fullscreen",
scrolling: "1",
});

// Agregar el nuevo iframe al contenedor


$('#content').append(newFrame);
});

//Se usa para aplicar evento activo y para cambiar imagen del background
// Array of valid classes for background images
const validClasses = ['other', 'fútbol', 'fútbol_cup', 'tenis', 'atp', 'beisbol',
'mlb', 'basketball', 'baloncesto', 'hockey', 'nhl', 'wwe', 'wta', 'nfl', 'ufc',
"motor"];

document.addEventListener("click", setText);

function setText(event) {
// Check if the clicked element has the class 'link', para poner como color
activo
if (event.target.classList.contains("link")) {
event.preventDefault(); // Prevent the default anchor click behavior

// Get the parent <li> of the clicked link


var listItem = event.target.parentElement;

// Remove 'active' class from all <li> elements


var listItems = document.querySelectorAll('.list');
listItems.forEach(item => {
item.classList.remove('activo');
});

// Reset the color of all links


var links = document.querySelectorAll('.link');
links.forEach(link => {
link.style.color = ''; // Reset to default color
});

// Add 'active' class to the clicked <li>


listItem.classList.add('activo');

// Set the color of the clicked link


event.target.style.color = '#ff9933';

//esta parte es para cambiar la imagen del fondo de acuerdo al enlace clicado

/*// Reset the background image before setting a new one


document.body.style.backgroundImage = ''; // Reset the background image

// Check for matching classes and set the background image


const classes = listItem.classList;
let foundClass = null;

for (let validClass of validClasses) {


if (classes.contains(validClass)) {
foundClass = validClass;
break; // Stop searching once we find a match
}
}

// If a valid class is found, construct the image URL and set it


if (foundClass) {
const imageUrl = `https://sports.zya.me/img/bg/${foundClass}.jpg`;
document.body.style.backgroundImage = `url('${imageUrl}')`;
//document.body.style.backgroundSize = 'cover'; // Optional: cover the
entire body
//document.body.style.backgroundPosition = 'center'; // Optional:
center the image
} else {
console.log('No valid class found for background image.');
}*/
}
}

//Cargar el widget al hacer click en el evento


let teamNameMappings = {};

// Fetch team name mappings from JSON file


async function loadTeamNameMappings() {
try {
const response = await fetch('js/teamNameMappings.json'); // Update the
path as necessary
teamNameMappings = await response.json();
} catch (error) {
console.error('Error loading team name mappings:', error);
}
}
// Fetch data from the specified URL
async function fetchData() {
try {
const now = new Date();
let date;

// Get the current hours and minutes


const hours = now.getHours();
const minutes = now.getMinutes();

// Determine the date based on the current time


if ((hours === 3 && minutes >= 6) || (hours > 3 && hours < 24)) {
// Time is between 3:06 AM and 11:59 PM
date = now.toLocaleString("es", { day: '2-digit', month: "2-digit",
year: 'numeric' });
} else {
// Time is between 12:00 AM and 3:07 AM
now.setDate(now.getDate() - 1); // Go to the previous day
date = now.toLocaleString("es", { day: '2-digit', month: "2-digit",
year: 'numeric' });
}

const response = await fetch('https://webwidgets.365scores.com/web/games/?


appTypeId=5&langId=29&timezoneName=America/
Cancun&userCountryId=31&sports=&startDate=' + date + '&endDate=' + date);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
return null; // Return null in case of an error
}
}

// Load data and extract teams


async function loadData() {
const data = await fetchData();
if (!data || !data.games) { // Check for the new structure
console.error('Invalid data structure');
return { games: [] };
}

return data.games; // Return the games directly


}

// Normalize team names for comparison


function normalizeTeamName(name) {
let normalized = name;

// Replace using mappings from the JSON file


for (const [key, value] of Object.entries(teamNameMappings)) {
normalized = normalized.replace(new RegExp(key, 'gi'), value); // 'gi' for
case-insensitive replacement
}

return normalized
.replace(/[^\w\s]|_/g, '') // Remove punctuation
.replace(/\s+/g, ' ') // Replace multiple spaces with a single space
.normalize("NFD") // Decompose accented characters
.replace(/[\u0300-\u036f]/g, "") // Remove diacritics
.trim()
.toLowerCase(); // Ensure the name is in lowercase
}

// Get IDs based on input with exact and partial matching


async function getIdsFromInput(input) {
const games = await loadData();

// Split the input into teams


const parts = input.toLowerCase().split(" vs ");
if (parts.length !== 2) {
console.error("Input format is incorrect. Expected format: 'team 1 vs team
2'");
return;
}

const team1 = parts[0].split(":")[1]?.trim() || parts[0].trim();


const team2 = parts[1].trim();

// Get IDs for both teams


const teamIds = await findTeamIdsInGames(team1, team2, games);

// If IDs are found, join them into a string and update the widget
if (teamIds) {
const result = teamIds.join("-");
console.log(result);

// Attempt to update the widget with the original IDs


const loadedSuccessfully = await updateWidgetWithCheck(result, 2000); //
Check for 5 seconds
if (!loadedSuccessfully) {
// If the widget fails to load, invert the IDs
const invertedResult = [teamIds[1], teamIds[0], teamIds[2]].join("-");
console.log("Inverted IDs: ", invertedResult);
await updateWidgetWithCheck(invertedResult, 2000); // Check for 5
seconds
}
} else {
console.error("No matching teams found.");
}
}
// Find a team's ID based on the new matching logic within the context of the same
game
async function findTeamIdsInGames(team1Name, team2Name, games) {
const normalizedTeam1Name = normalizeTeamName(team1Name);
const normalizedTeam2Name = normalizeTeamName(team2Name);

for (const game of games) {


const homeTeamShortName = game.homeCompetitor.shortName ?
normalizeTeamName(game.homeCompetitor.shortName) : null;
const awayTeamShortName = game.awayCompetitor.shortName ?
normalizeTeamName(game.awayCompetitor.shortName) : null;
const homeTeamName = normalizeTeamName(game.homeCompetitor.name);
const awayTeamName = normalizeTeamName(game.awayCompetitor.name);

// Check for perfect match on names


if (homeTeamName === normalizedTeam1Name && awayTeamName ===
normalizedTeam2Name) {
return [game.homeCompetitor.id, game.awayCompetitor.id,
game.competitionId];
}

// Check for perfect match on short names


if (homeTeamShortName === normalizedTeam1Name && awayTeamShortName ===
normalizedTeam2Name) {
return [game.homeCompetitor.id, game.awayCompetitor.id,
game.competitionId];
}

// Check for perfect match on home competitor name with team1


if (homeTeamName === normalizedTeam1Name) {
return [game.homeCompetitor.id, game.awayCompetitor.id,
game.competitionId];
}

// Check for perfect match on away competitor name with team2


if (awayTeamName === normalizedTeam2Name) {
return [game.homeCompetitor.id, game.awayCompetitor.id,
game.competitionId];
}
}

// If no perfect match is found, check for partial matches


for (const game of games) {
const homeTeamName = normalizeTeamName(game.homeCompetitor.name);
const awayTeamName = normalizeTeamName(game.awayCompetitor.name);

//Check if homeCompetitor name includes any word from team1 input


const team1Words = normalizedTeam1Name.split(' ');
const team2Words = normalizedTeam2Name.split(' ');

const homeMatch = team1Words.some(word => homeTeamName.includes(word));


const awayMatch = team2Words.some(word => awayTeamName.includes(word));

if (homeMatch && awayMatch) {


return [game.homeCompetitor.id, game.awayCompetitor.id,
game.competitionId];
}
}

// check for partial match inverted input of team 1 to match name of


awaycompetitor and team 2 to home competitor
for (const game of games) {
const homeTeamName = normalizeTeamName(game.homeCompetitor.name);
const awayTeamName = normalizeTeamName(game.awayCompetitor.name);

// Check if homeCompetitor name includes any word from team1 input


const team1Words = normalizedTeam1Name.split(' ');
const team2Words = normalizedTeam2Name.split(' ');

const awayMatch = team1Words.some(word => awayTeamName.includes(word));


const homeMatch = team2Words.some(word => homeTeamName.includes(word));

if (homeMatch && awayMatch) {


return [game.awayCompetitor.id, game.homeCompetitor.id,
game.competitionId];
}
}

return null; // Return null if no match is found


}

async function updateWidgetWithCheck(result, delay) {


updateWidget(result); // Attempt to update the widget

// Wait for the specified delay


await new Promise(resolve => setTimeout(resolve, delay));

// Check if the widget was successfully added


return !!document.getElementById("widgets-loader_0.vnigd5ihlb7");
}

// Update the widget with the result


function updateWidget(result) {
const existingDiv = document.getElementById("widget");
if (existingDiv) {
existingDiv.remove();
}

// Remove the existing script if it exists


const existingScript = document.getElementById("widget-script");
if (existingScript) {
existingScript.remove(); // Remove the existing script
}

const newDiv = document.createElement("div");


//newDiv.setAttribute("style", "position:absolute;top:96vh;width:62.5%");
newDiv.setAttribute("id", "widget");
newDiv.setAttribute("data-entity-type", "entityGame");
newDiv.setAttribute("data-widget-type", "game");
newDiv.setAttribute("data-entity-id", result);
newDiv.setAttribute("data-lang", "es-419");
newDiv.setAttribute("data-widget-id", "0.vnigd5ihlb7");
newDiv.setAttribute("data-theme", "dark");
newDiv.setAttribute("data-inner-links", "allow");
newDiv.setAttribute("data-allow-premium-data", "true");
newDiv.setAttribute("data-hide-powered-by", "true");
newDiv.setAttribute("data-use-client-user-country-id", "true");
newDiv.setAttribute("data-show-sponsorship", "false");
newDiv.setAttribute("data-show-odds", "false");
newDiv.setAttribute("data-odds-type", "decimal");
newDiv.setAttribute("data-publisher-id", "1");

const content = document.getElementById("content");


content.appendChild(newDiv);

const script = document.createElement("script");


script.src = "https://sports.zya.me/main.js";
script.type = "text/javascript";
//script.async = true;
script.id = "widget-script";

document.head.appendChild(script);
// Check if the widget was successfully added
return !!document.getElementById("widgets-loader_0.vnigd5ihlb7");
}

// Add a single event listener to the document for links with class 'trigger'
document.addEventListener('click', function (event) {
if (event.target.classList.contains('trigger')) {
// Fade out the content
$('#content').fadeOut(100, function() {
// After fading out, wait for 2 seconds (2000 milliseconds)
setTimeout(function() {
// Fade in the content
$('#content').fadeIn(300);
}, 3500); // Change this value to adjust the wait time
});
//remove widget onclick
updateWidget();
event.preventDefault(); // Prevent the default link behavior
const input = event.target.textContent; // Get the text content of the
clicked link
getIdsFromInput(input); // Call the function with the input
}
});

// Call loadTeamNameMappings at the start of your script


loadTeamNameMappings();
</script>

You might also like