987 lines
36 KiB
HTML
987 lines
36 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<title data-i18n="scoring.results_calculator">Kalkulator</title>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<link rel="stylesheet" href="/static/css/base.css">
|
|
<link rel="stylesheet" href="/static/css/navbar.css">
|
|
<link rel="stylesheet" href="/static/css/buttons.css">
|
|
<link rel="stylesheet" href="/static/css/components.css">
|
|
<link rel="stylesheet" href="/static/css/responsive.css">
|
|
<link rel="stylesheet" href="/static/css/pages/results_calculator.css">
|
|
<script src="/static/js/i18n.js"></script>
|
|
</head>
|
|
<body>
|
|
<div class="navbar">
|
|
<div class="navbar-title">🎯 <span data-i18n="scoring.results_calculator">Kalkulator</span></div>
|
|
<div class="navbar-controls">
|
|
<a href="/tournament" class="nav-btn">🏆 <span data-i18n="navigation.tournament">Tournament</span></a>
|
|
<a href="/tournament/draft" class="nav-btn">📋 Razpored</a>
|
|
<a href="/results/calculator" class="nav-btn active">🎯 <span data-i18n="navigation.calculator">Kalkulator</span></a>
|
|
<a href="/" class="nav-btn">✕</a>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="content-wrapper">
|
|
<div class="container">
|
|
|
|
<!-- LEFT: Players card -->
|
|
<div class="calc-card" style="width:240px;flex-shrink:0;align-self:stretch;">
|
|
<div class="players-search-bar">
|
|
<div class="players-search-wrap">
|
|
<input class="players-search-input" id="playerSearch" type="text" placeholder="🔍 Iskanje..." oninput="filterPlayers(this.value)">
|
|
<button class="players-search-clear" onclick="clearPlayerSearch()" title="Clear">✕</button>
|
|
</div>
|
|
</div>
|
|
<div class="participants-list" id="participantsList">
|
|
{% for player_id, participant in results.participants.items() %}
|
|
<div class="participant-list-item {{ 'completed' if participant.completed else '' }}" onclick="selectParticipant({{ player_id }})" id="list-item-{{ player_id }}" data-player-id="{{ player_id }}">
|
|
<div class="participant-list-item-content">
|
|
<span class="participant-list-item-name">{{ participant.name }}</span>
|
|
<span class="participant-list-item-score" id="list-score-{{ player_id }}">{{ participant.total_score }}</span>
|
|
<span class="participant-list-item-tens" id="list-tens-{{ player_id }}">0</span>
|
|
</div>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
|
|
<!-- MIDDLE: Scoring card + Finish card -->
|
|
<div style="flex:1;display:flex;flex-direction:column;gap:12px;min-height:0;overflow:hidden;">
|
|
|
|
<!-- Scoring card -->
|
|
<div class="calc-card" style="flex:1;min-height:0;">
|
|
<div class="main-card-panel" id="mainCardPanel">
|
|
<div class="main-card-panel-empty" id="emptyPanel">
|
|
👈 <span data-i18n="general.select">Select a participant</span>
|
|
</div>
|
|
{% for player_id, participant in results.participants.items() %}
|
|
<div class="participant-card {{ 'completed' if participant.completed else 'in-progress' }}" id="card-{{ player_id }}" data-player-id="{{ player_id }}">
|
|
<!-- Card Header on Top -->
|
|
<div class="card-header-top">
|
|
<div class="header-info">
|
|
<div class="player-name">{{ participant.name }}</div>
|
|
<div class="player-stats">
|
|
<div style="display: flex; flex-direction: column; align-items: center;">
|
|
<span class="total-score" id="total-{{ player_id }}">{{ participant.total_score }}</span>
|
|
<span class="score-label" data-i18n="scoring.points">pts</span>
|
|
</div>
|
|
<div style="display: flex; flex-direction: column; align-items: center;">
|
|
<span class="tens-count" id="tens-{{ player_id }}">0</span>
|
|
<span class="tens-label">10s</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="header-actions" onclick="event.stopPropagation();">
|
|
<button class="header-btn clear-btn" onclick="clearParticipant({{ player_id }})" data-i18n-title="scoring.clear_all_scores">
|
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
<line x1="10" y1="11" x2="10" y2="17"></line>
|
|
<line x1="14" y1="11" x2="14" y2="17"></line>
|
|
</svg>
|
|
</button>
|
|
<button class="header-btn zero-fill-btn" onclick="fillEmptyWithZeros({{ player_id }})" data-i18n-title="scoring.fill_empty_with_zero">
|
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
<circle cx="12" cy="12" r="10"></circle>
|
|
<line x1="12" y1="6" x2="12" y2="18"></line>
|
|
<line x1="6" y1="12" x2="18" y2="12"></line>
|
|
</svg>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<!-- All Targets (scrollable) -->
|
|
<div class="participant-targets-wrapper">
|
|
<div class="targets-row" id="targets-{{ player_id }}">
|
|
<!-- Targets will be populated by JavaScript -->
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Finish card -->
|
|
<div class="calc-card finish-section">
|
|
<button class="fill-all-btn" onclick="fillAllPlayersRandom()">
|
|
🎲 <span data-i18n="scoring.fill_all_players_random">Fill All Random</span>
|
|
</button>
|
|
<button class="finish-btn" id="finishBtn" onclick="finishTournament()" data-i18n="scoring.finish_tournament_button">🏁 Finish Tournament
|
|
</button>
|
|
</div>
|
|
|
|
</div><!-- end middle column -->
|
|
|
|
<!-- RIGHT: Draft card -->
|
|
{% if tournament and tournament.rounds %}
|
|
<div class="calc-card draft-panel">
|
|
<div class="draft-panel-header">
|
|
<button class="draft-round-nav" id="draftPrevBtn" onclick="draftChangeRound(-1)">←</button>
|
|
<span class="draft-round-label" id="draftRoundLabel">{{ tournament.current_round }} / {{ tournament.total_rounds }}</span>
|
|
<button class="draft-round-nav" id="draftNextBtn" onclick="draftChangeRound(1)">→</button>
|
|
</div>
|
|
<div class="draft-positions" id="draftPositions">
|
|
<!-- populated by JS -->
|
|
</div>
|
|
<div class="draft-panel-footer">
|
|
<button class="nav-btn" id="btnTvDraft" onclick="toggleTvDraft()">📺 Pokaži Razpored</button>
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
|
|
</div><!-- end container -->
|
|
</div><!-- end content-wrapper -->
|
|
|
|
<script>
|
|
let results = {{ results|tojson }};
|
|
let saveTimeout = {};
|
|
|
|
// Tournament configuration
|
|
const tournamentType = results.tournament_type || '20_targets';
|
|
let numTargets, shotsPerTarget;
|
|
|
|
// Set tournament parameters
|
|
if (tournamentType === '40_targets') {
|
|
numTargets = 40;
|
|
shotsPerTarget = 2;
|
|
} else if (tournamentType === '4_targets') {
|
|
numTargets = 4;
|
|
shotsPerTarget = 5;
|
|
} else {
|
|
numTargets = 20;
|
|
shotsPerTarget = 2;
|
|
}
|
|
|
|
// Calculate 10s count for a player
|
|
function calculateTensCount(playerId) {
|
|
const playerIdStr = playerId.toString();
|
|
const targets = results.participants[playerIdStr].targets;
|
|
let tensCount = 0;
|
|
|
|
for (let target in targets) {
|
|
const targetData = targets[target];
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
const shotValue = targetData[`shot${i}`];
|
|
if (shotValue === 10) {
|
|
tensCount++;
|
|
}
|
|
}
|
|
}
|
|
|
|
return tensCount;
|
|
}
|
|
|
|
// Update participant's 10s display
|
|
function updateParticipantTens(playerId) {
|
|
const tensCount = calculateTensCount(playerId);
|
|
|
|
// Update main card display
|
|
const tensElement = document.getElementById(`tens-${playerId}`);
|
|
if (tensElement) {
|
|
tensElement.textContent = tensCount;
|
|
|
|
// Add visual feedback
|
|
tensElement.style.color = '#ffc107';
|
|
setTimeout(() => {
|
|
tensElement.style.color = '';
|
|
}, 300);
|
|
}
|
|
|
|
// Update sidebar 10s count
|
|
const sidebarTensElement = document.getElementById(`list-tens-${playerId}`);
|
|
if (sidebarTensElement) {
|
|
sidebarTensElement.textContent = tensCount;
|
|
}
|
|
}
|
|
|
|
// Update overall 10s count
|
|
function updateOverallTens() {
|
|
let totalTens = 0;
|
|
|
|
for (let playerId in results.participants) {
|
|
totalTens += calculateTensCount(parseInt(playerId));
|
|
}
|
|
|
|
const ttEl = document.getElementById('totalTens'); if (ttEl) ttEl.textContent = totalTens;
|
|
}
|
|
|
|
// Debounce function for auto-saving
|
|
function debounce(func, wait, immediate) {
|
|
var timeout;
|
|
return function() {
|
|
var context = this, args = arguments;
|
|
var later = function() {
|
|
timeout = null;
|
|
if (!immediate) func.apply(context, args);
|
|
};
|
|
var callNow = immediate && !timeout;
|
|
clearTimeout(timeout);
|
|
timeout = setTimeout(later, wait);
|
|
if (callNow) func.apply(context, args);
|
|
};
|
|
}
|
|
|
|
function generateTargetsHTML(playerId) {
|
|
const participant = results.participants[playerId.toString()];
|
|
let html = '';
|
|
|
|
for (let i = 1; i <= numTargets; i++) {
|
|
const targetData = participant.targets[i.toString()] || {};
|
|
|
|
html += `
|
|
<div class="target-group" id="target-group-${playerId}-${i}">
|
|
<div class="target-number">${i}</div>
|
|
<div class="shots-container shots-${shotsPerTarget}">
|
|
`;
|
|
|
|
for (let shot = 1; shot <= shotsPerTarget; shot++) {
|
|
const shotKey = `shot${shot}`;
|
|
const value = targetData[shotKey];
|
|
const displayValue = value !== null && value !== undefined ? value : '';
|
|
|
|
html += `
|
|
<input type="number"
|
|
class="shot-input ${value === 10 ? 'ten' : ''}"
|
|
id="shot${shot}-${playerId}-${i}"
|
|
data-player="${playerId}"
|
|
data-target="${i}"
|
|
data-shot="${shot}"
|
|
min="0"
|
|
max="10"
|
|
value="${displayValue}"
|
|
placeholder="Strel ${shot}"
|
|
oninput="updateScore(${playerId}, ${i}, ${shot}, this.value)">
|
|
`;
|
|
}
|
|
|
|
html += `
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
return html;
|
|
}
|
|
|
|
function initializeTargetsForPlayer(playerId) {
|
|
const targetsContainer = document.getElementById(`targets-${playerId}`);
|
|
if (targetsContainer) {
|
|
targetsContainer.className = `targets-row targets-${numTargets}`;
|
|
targetsContainer.innerHTML = generateTargetsHTML(playerId);
|
|
}
|
|
}
|
|
|
|
function toggleParticipant(playerId) {
|
|
const card = document.getElementById(`card-${playerId}`);
|
|
card.classList.toggle('collapsed');
|
|
}
|
|
|
|
function selectParticipant(playerId) {
|
|
// Remove active class from all list items and cards
|
|
document.querySelectorAll('.participant-list-item').forEach(item => {
|
|
item.classList.remove('active');
|
|
});
|
|
document.querySelectorAll('.participant-card').forEach(card => {
|
|
card.classList.remove('active');
|
|
});
|
|
|
|
// Add active class to selected item and card
|
|
const listItem = document.getElementById(`list-item-${playerId}`);
|
|
const card = document.getElementById(`card-${playerId}`);
|
|
|
|
if (listItem) listItem.classList.add('active');
|
|
if (card) card.classList.add('active');
|
|
|
|
// Hide empty panel if shown
|
|
const emptyPanel = document.getElementById('emptyPanel');
|
|
if (emptyPanel) emptyPanel.style.display = 'none';
|
|
}
|
|
|
|
function updateScore(playerId, targetNum, shotNum, value) {
|
|
const playerIdStr = playerId.toString();
|
|
const targetStr = targetNum.toString();
|
|
|
|
// Parse input - allow empty string, treat as null/undefined for completion check
|
|
let numValue = null;
|
|
if (value !== '' && value !== null && value !== undefined) {
|
|
numValue = parseInt(value);
|
|
if (isNaN(numValue)) numValue = null;
|
|
else numValue = Math.max(0, Math.min(10, numValue)); // Clamp between 0-10
|
|
}
|
|
|
|
// Update the input field with clamped value
|
|
const input = document.getElementById(`shot${shotNum}-${playerId}-${targetNum}`);
|
|
if (input && numValue !== null && input.value !== numValue.toString()) {
|
|
input.value = numValue;
|
|
}
|
|
|
|
// Update local data
|
|
if (!results.participants[playerIdStr]) {
|
|
console.error('Player not found:', playerIdStr);
|
|
return;
|
|
}
|
|
if (!results.participants[playerIdStr].targets[targetStr]) {
|
|
// Initialize target with all shots as null
|
|
const target = {};
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
target[`shot${i}`] = null;
|
|
}
|
|
results.participants[playerIdStr].targets[targetStr] = target;
|
|
}
|
|
|
|
results.participants[playerIdStr].targets[targetStr][`shot${shotNum}`] = numValue;
|
|
|
|
// Update target group styling
|
|
updateTargetGroupStyling(playerId, targetNum);
|
|
|
|
// Recalculate totals
|
|
updateParticipantTotal(playerId);
|
|
updateParticipantTens(playerId);
|
|
updateParticipantStatus(playerId);
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
|
|
// Visual feedback for input - highlight 10s
|
|
if (input) {
|
|
input.classList.remove('valid', 'ten');
|
|
if (numValue !== null) {
|
|
if (numValue === 10) {
|
|
input.classList.add('ten');
|
|
} else {
|
|
input.classList.add('valid');
|
|
}
|
|
}
|
|
}
|
|
|
|
// Auto-save with debounce
|
|
clearTimeout(saveTimeout[playerId]);
|
|
saveTimeout[playerId] = setTimeout(() => {
|
|
saveParticipant(playerId, true);
|
|
}, 1000);
|
|
}
|
|
|
|
function updateTargetGroupStyling(playerId, targetNum) {
|
|
const playerIdStr = playerId.toString();
|
|
const targetStr = targetNum.toString();
|
|
const targetGroup = document.getElementById(`target-group-${playerId}-${targetNum}`);
|
|
|
|
if (targetGroup && results.participants[playerIdStr].targets[targetStr]) {
|
|
const targetData = results.participants[playerIdStr].targets[targetStr];
|
|
|
|
// Check if all shots are completed
|
|
let allCompleted = true;
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
const shotValue = targetData[`shot${i}`];
|
|
if (shotValue === null || shotValue === undefined) {
|
|
allCompleted = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (allCompleted) {
|
|
targetGroup.classList.add('completed');
|
|
} else {
|
|
targetGroup.classList.remove('completed');
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateParticipantTotal(playerId) {
|
|
const playerIdStr = playerId.toString();
|
|
const targets = results.participants[playerIdStr].targets;
|
|
let total = 0;
|
|
|
|
for (let target in targets) {
|
|
const targetData = targets[target];
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
const shotValue = targetData[`shot${i}`];
|
|
total += (shotValue !== null && shotValue !== undefined ? shotValue : 0);
|
|
}
|
|
}
|
|
|
|
results.participants[playerIdStr].total_score = total;
|
|
|
|
// Update main card display
|
|
const totalElement = document.getElementById(`total-${playerId}`);
|
|
if (totalElement) {
|
|
totalElement.textContent = total;
|
|
|
|
// Add visual feedback
|
|
totalElement.style.color = '#28a745';
|
|
setTimeout(() => {
|
|
totalElement.style.color = '';
|
|
}, 300);
|
|
}
|
|
|
|
// Update sidebar score
|
|
const sidebarScoreElement = document.getElementById(`list-score-${playerId}`);
|
|
if (sidebarScoreElement) {
|
|
sidebarScoreElement.textContent = total;
|
|
}
|
|
}
|
|
|
|
function updateParticipantStatus(playerId) {
|
|
const playerIdStr = playerId.toString();
|
|
const targets = results.participants[playerIdStr].targets;
|
|
const card = document.getElementById(`card-${playerId}`);
|
|
|
|
let completedTargets = 0;
|
|
let totalShots = 0;
|
|
|
|
for (let target in targets) {
|
|
const targetData = targets[target];
|
|
let targetCompleted = true;
|
|
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
const shotValue = targetData[`shot${i}`];
|
|
|
|
// Count shots that have been entered (including 0)
|
|
if (shotValue !== null && shotValue !== undefined) {
|
|
totalShots++;
|
|
} else {
|
|
targetCompleted = false;
|
|
}
|
|
}
|
|
|
|
if (targetCompleted) {
|
|
completedTargets++;
|
|
}
|
|
}
|
|
|
|
const isCompleted = completedTargets === numTargets;
|
|
const isInProgress = totalShots > 0 && !isCompleted;
|
|
|
|
results.participants[playerIdStr].completed = isCompleted;
|
|
|
|
// Update card styling based on status
|
|
if (card) {
|
|
card.classList.remove('completed', 'in-progress');
|
|
if (isCompleted) {
|
|
card.classList.add('completed');
|
|
} else if (isInProgress) {
|
|
card.classList.add('in-progress');
|
|
}
|
|
}
|
|
|
|
// Update sidebar styling based on status
|
|
const listItem = document.getElementById(`list-item-${playerId}`);
|
|
if (listItem) {
|
|
listItem.classList.remove('completed', 'in-progress');
|
|
if (isCompleted) {
|
|
listItem.classList.add('completed');
|
|
} else if (isInProgress) {
|
|
listItem.classList.add('in-progress');
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateOverallProgress() {
|
|
let completedCount = 0;
|
|
let totalShots = 0;
|
|
|
|
for (let playerId in results.participants) {
|
|
const participant = results.participants[playerId];
|
|
if (participant.completed) {
|
|
completedCount++;
|
|
}
|
|
|
|
for (let target in participant.targets) {
|
|
const targetData = participant.targets[target];
|
|
for (let i = 1; i <= shotsPerTarget; i++) {
|
|
const shotValue = targetData[`shot${i}`];
|
|
if (shotValue !== null && shotValue !== undefined) totalShots++;
|
|
}
|
|
}
|
|
}
|
|
|
|
const ccEl = document.getElementById('completedCount'); if (ccEl) ccEl.textContent = completedCount;
|
|
const tsEl = document.getElementById('totalShots'); if (tsEl) tsEl.textContent = totalShots;
|
|
|
|
// Update finish button state
|
|
const finishBtn = document.getElementById('finishBtn');
|
|
const allCompleted = completedCount === Object.keys(results.participants).length;
|
|
|
|
if (finishBtn) {
|
|
finishBtn.disabled = !allCompleted;
|
|
}
|
|
}
|
|
|
|
async function saveParticipant(playerId, silent = false) {
|
|
try {
|
|
const playerIdStr = playerId.toString();
|
|
const participantData = results.participants[playerIdStr];
|
|
|
|
const response = await fetch(`/api/results/participant/${playerId}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
targets: participantData.targets
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to save');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error saving participant:', error);
|
|
if (!silent) {
|
|
alert('Failed to save participant data. Please try again.');
|
|
}
|
|
}
|
|
}
|
|
|
|
async function saveAllPlayers() {
|
|
try {
|
|
const playerIds = Object.keys(results.participants);
|
|
for (const playerId of playerIds) {
|
|
await saveParticipant(parseInt(playerId), true);
|
|
}
|
|
} catch (error) {
|
|
console.error('Error saving all players:', error);
|
|
alert('Failed to save all player data. Please try again.');
|
|
}
|
|
}
|
|
|
|
function clearParticipant(playerId) {
|
|
if (!confirm('Are you sure you want to clear all scores for this participant?')) {
|
|
return;
|
|
}
|
|
|
|
const playerIdStr = playerId.toString();
|
|
|
|
// Clear all inputs
|
|
for (let i = 1; i <= numTargets; i++) {
|
|
for (let shot = 1; shot <= shotsPerTarget; shot++) {
|
|
const shotInput = document.getElementById(`shot${shot}-${playerId}-${i}`);
|
|
if (shotInput) {
|
|
shotInput.value = '';
|
|
shotInput.classList.remove('valid', 'ten');
|
|
}
|
|
}
|
|
|
|
// Update data
|
|
const target = {};
|
|
for (let shot = 1; shot <= shotsPerTarget; shot++) {
|
|
target[`shot${shot}`] = null;
|
|
}
|
|
results.participants[playerIdStr].targets[i.toString()] = target;
|
|
|
|
// Update target group styling
|
|
updateTargetGroupStyling(playerId, i);
|
|
}
|
|
|
|
updateParticipantTotal(playerId);
|
|
updateParticipantTens(playerId);
|
|
updateParticipantStatus(playerId);
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
|
|
// Save changes
|
|
saveParticipant(playerId);
|
|
}
|
|
|
|
function fillEmptyWithZeros(playerId) {
|
|
const playerIdStr = playerId.toString();
|
|
let changedCount = 0;
|
|
|
|
// Fill all empty entries with 0
|
|
for (let i = 1; i <= numTargets; i++) {
|
|
const target = results.participants[playerIdStr].targets[i.toString()] || {};
|
|
|
|
for (let shot = 1; shot <= shotsPerTarget; shot++) {
|
|
const shotInput = document.getElementById(`shot${shot}-${playerId}-${i}`);
|
|
|
|
// Only fill if empty
|
|
if ((target[`shot${shot}`] === null || target[`shot${shot}`] === undefined) && shotInput && shotInput.value === '') {
|
|
shotInput.value = 0;
|
|
shotInput.classList.remove('ten');
|
|
shotInput.classList.add('valid');
|
|
changedCount++;
|
|
|
|
// Update data
|
|
if (!results.participants[playerIdStr].targets[i.toString()]) {
|
|
results.participants[playerIdStr].targets[i.toString()] = {};
|
|
}
|
|
results.participants[playerIdStr].targets[i.toString()][`shot${shot}`] = 0;
|
|
}
|
|
}
|
|
|
|
// Update target group styling
|
|
updateTargetGroupStyling(playerId, i);
|
|
}
|
|
|
|
if (changedCount > 0) {
|
|
updateParticipantTotal(playerId);
|
|
updateParticipantTens(playerId);
|
|
updateParticipantStatus(playerId);
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
saveParticipant(playerId, true);
|
|
}
|
|
}
|
|
|
|
function autoFillDemo(playerId) {
|
|
if (!confirm('Fill with random demo scores? This will overwrite existing data.')) {
|
|
return;
|
|
}
|
|
|
|
fillPlayerRandom(playerId);
|
|
saveParticipant(playerId);
|
|
}
|
|
|
|
function fillPlayerRandom(playerId) {
|
|
const playerIdStr = playerId.toString();
|
|
let fillCount = 0;
|
|
|
|
// Fill with random scores (0-10) - all fields will be filled
|
|
for (let i = 1; i <= numTargets; i++) {
|
|
const target = {};
|
|
|
|
for (let shot = 1; shot <= shotsPerTarget; shot++) {
|
|
const randomScore = Math.floor(Math.random() * 11);
|
|
const inputId = `shot${shot}-${playerId}-${i}`;
|
|
const shotInput = document.getElementById(inputId);
|
|
|
|
if (shotInput) {
|
|
shotInput.value = randomScore;
|
|
shotInput.classList.remove('valid', 'ten');
|
|
if (randomScore === 10) {
|
|
shotInput.classList.add('ten');
|
|
} else {
|
|
shotInput.classList.add('valid');
|
|
}
|
|
fillCount++;
|
|
}
|
|
target[`shot${shot}`] = randomScore;
|
|
}
|
|
|
|
// Update data
|
|
results.participants[playerIdStr].targets[i.toString()] = target;
|
|
|
|
// Update target group styling
|
|
updateTargetGroupStyling(playerId, i);
|
|
}
|
|
|
|
console.log(`Player ${playerId}: filled ${fillCount} inputs`);
|
|
updateParticipantTotal(playerId);
|
|
updateParticipantTens(playerId);
|
|
updateParticipantStatus(playerId);
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
}
|
|
|
|
async function fillAllPlayersRandom() {
|
|
if (!confirm('Fill ALL players with random demo scores? This will overwrite all existing data and enable tournament finish.')) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Fill all players with random data
|
|
const playerIds = Object.keys(results.participants);
|
|
for (const playerId of playerIds) {
|
|
fillPlayerRandom(parseInt(playerId));
|
|
}
|
|
|
|
// Save all players
|
|
for (const playerId of playerIds) {
|
|
await saveParticipant(parseInt(playerId), true);
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Error filling all players:', error);
|
|
alert('Failed to fill all players: ' + error.message);
|
|
}
|
|
}
|
|
|
|
async function finishTournament() {
|
|
const allCompleted = Object.values(results.participants).every(p => p.completed);
|
|
|
|
if (!allCompleted) {
|
|
alert('Please complete scoring for all participants before finishing the tournament.');
|
|
return;
|
|
}
|
|
|
|
if (!confirm('Are you sure you want to finish the tournament? This will finalize all results and make them viewable.')) {
|
|
return;
|
|
}
|
|
|
|
const finishBtn = document.getElementById('finishBtn');
|
|
finishBtn.disabled = true;
|
|
const originalText = finishBtn.innerHTML;
|
|
const originalI18n = finishBtn.getAttribute('data-i18n');
|
|
finishBtn.removeAttribute('data-i18n');
|
|
finishBtn.innerHTML = '🔄 Finishing Tournament...';
|
|
|
|
try {
|
|
const response = await fetch('/api/results/finish', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
});
|
|
|
|
if (response.ok) {
|
|
const responseData = await response.json();
|
|
|
|
// Determine where to redirect based on tournament type and archive
|
|
let redirectUrl = '/results';
|
|
|
|
// Priority 1: If league finished, redirect to league archive
|
|
if (responseData.league_archived && responseData.league_archive_filename) {
|
|
redirectUrl = `/archive/league/${responseData.league_archive_filename}`;
|
|
}
|
|
// Priority 2: If standalone tournament, redirect to tournament archive
|
|
else if (responseData.archived && responseData.archive_filename) {
|
|
redirectUrl = `/archive/tournament/${responseData.archive_filename}`;
|
|
}
|
|
// Priority 3: If league tournament (not final), show league standings
|
|
else if (responseData.league && !responseData.league_finished) {
|
|
redirectUrl = '/results'; // This will show league standings with current tournament
|
|
}
|
|
|
|
// Always show results after tournament finishes
|
|
alert('Tournament finished successfully! Showing results...');
|
|
setTimeout(() => {
|
|
window.location.href = redirectUrl;
|
|
}, 1000);
|
|
} else {
|
|
const error = await response.json();
|
|
throw new Error(error.message || 'Failed to finish tournament');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error finishing tournament:', error);
|
|
alert('Failed to finish tournament: ' + error.message);
|
|
finishBtn.disabled = false;
|
|
finishBtn.innerHTML = originalText;
|
|
if (originalI18n) {
|
|
finishBtn.setAttribute('data-i18n', originalI18n);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle joker checkbox change
|
|
function handleJokerChange(playerId) {
|
|
const checkbox = document.getElementById(`joker-calc-${playerId}`);
|
|
const isChecked = checkbox.checked;
|
|
|
|
// If checked, warn user that all scores will be set to zero
|
|
if (isChecked) {
|
|
if (confirm('Marking this player as using their Joker will set all their scores to zero. Continue?')) {
|
|
// Set all scores to zero
|
|
const participant = results.participants[playerId];
|
|
if (participant && participant.targets) {
|
|
Object.keys(participant.targets).forEach(targetId => {
|
|
const target = participant.targets[targetId];
|
|
Object.keys(target).forEach(shotKey => {
|
|
if (shotKey.startsWith('shot')) {
|
|
target[shotKey] = 0;
|
|
}
|
|
});
|
|
});
|
|
}
|
|
participant.total_score = 0;
|
|
participant.completed = true; // Mark as completed since joker is used
|
|
participant.joker_selected = true; // Mark joker as selected in results
|
|
|
|
// Update UI
|
|
updateParticipantTotal(playerId);
|
|
updateParticipantStatus(playerId);
|
|
updateParticipantTens(playerId);
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
|
|
// Disable the checkbox so it can't be unchecked
|
|
checkbox.disabled = true;
|
|
|
|
// Save the change
|
|
savePlayerData(playerId);
|
|
} else {
|
|
// User cancelled, uncheck the box
|
|
checkbox.checked = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── PLAYER SEARCH ────────────────────────────────────────────────────────
|
|
function filterPlayers(query) {
|
|
const q = query.trim().toLowerCase();
|
|
const clearBtn = document.querySelector('.players-search-clear');
|
|
if (clearBtn) clearBtn.classList.toggle('visible', q.length > 0);
|
|
document.querySelectorAll('.participant-list-item').forEach(item => {
|
|
const name = item.querySelector('.participant-list-item-name').textContent.toLowerCase();
|
|
item.style.display = (!q || name.includes(q)) ? '' : 'none';
|
|
});
|
|
}
|
|
|
|
function clearPlayerSearch() {
|
|
const input = document.getElementById('playerSearch');
|
|
input.value = '';
|
|
filterPlayers('');
|
|
input.focus();
|
|
}
|
|
|
|
// ── DRAFT PANEL ──────────────────────────────────────────────────────────
|
|
{% if tournament and tournament.rounds %}
|
|
const draftRounds = {{ tournament.rounds | tojson }};
|
|
let draftCurrentRound = {{ tournament.current_round }};
|
|
const draftTotalRounds = {{ tournament.total_rounds }};
|
|
|
|
function renderDraftPanel() {
|
|
const round = draftRounds.find(r => r.round_number === draftCurrentRound);
|
|
const positions = document.getElementById('draftPositions');
|
|
const label = document.getElementById('draftRoundLabel');
|
|
const prevBtn = document.getElementById('draftPrevBtn');
|
|
const nextBtn = document.getElementById('draftNextBtn');
|
|
|
|
if (!positions || !label) return;
|
|
|
|
label.textContent = `${draftCurrentRound} / ${draftTotalRounds}`;
|
|
if (prevBtn) prevBtn.disabled = draftCurrentRound <= 1;
|
|
if (nextBtn) nextBtn.disabled = draftCurrentRound >= draftTotalRounds;
|
|
|
|
const players = round ? round.players : [];
|
|
let html = '';
|
|
for (let pos = 1; pos <= 6; pos++) {
|
|
const player = players[pos - 1];
|
|
if (player) {
|
|
html += `<div class="draft-position-row" onclick="selectParticipant(${player.id})">
|
|
<div class="draft-position-num">${pos}</div>
|
|
<div class="draft-position-name">${player.name}</div>
|
|
</div>`;
|
|
} else {
|
|
html += `<div class="draft-position-row empty">
|
|
<div class="draft-position-num">${pos}</div>
|
|
<div class="draft-position-name">—</div>
|
|
</div>`;
|
|
}
|
|
}
|
|
positions.innerHTML = html;
|
|
}
|
|
|
|
async function draftChangeRound(direction) {
|
|
const newRound = draftCurrentRound + direction;
|
|
if (newRound < 1 || newRound > draftTotalRounds) return;
|
|
|
|
const prevBtn = document.getElementById('draftPrevBtn');
|
|
const nextBtn = document.getElementById('draftNextBtn');
|
|
if (prevBtn) prevBtn.disabled = true;
|
|
if (nextBtn) nextBtn.disabled = true;
|
|
|
|
try {
|
|
const response = await fetch(`/api/tournament/round/${newRound}`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
if (response.ok) {
|
|
draftCurrentRound = newRound;
|
|
}
|
|
} catch (e) {
|
|
console.error('Round change failed:', e);
|
|
}
|
|
renderDraftPanel();
|
|
}
|
|
// TV draft toggle
|
|
let currentTvView = 'cameras';
|
|
|
|
function updateTvDraftBtn(view) {
|
|
currentTvView = view;
|
|
const btn = document.getElementById('btnTvDraft');
|
|
if (!btn) return;
|
|
btn.style.background = (view === 'draft') ? '#28a745' : '';
|
|
btn.style.color = (view === 'draft') ? 'white' : '';
|
|
btn.style.borderColor = (view === 'draft') ? '#1e7e34' : '';
|
|
btn.textContent = (view === 'draft') ? '📺 Skrij Razpored' : '📺 Pokaži Razpored';
|
|
}
|
|
|
|
async function toggleTvDraft() {
|
|
const newView = currentTvView === 'draft' ? 'cameras' : 'draft';
|
|
try {
|
|
await fetch('/api/tv/view', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ view: newView })
|
|
});
|
|
updateTvDraftBtn(newView);
|
|
} catch (e) { console.error(e); }
|
|
}
|
|
|
|
fetch('/api/dashboard/state').then(r => r.json()).then(d => updateTvDraftBtn(d.tv_view || 'cameras')).catch(() => {});
|
|
{% endif %}
|
|
|
|
// Keyboard shortcuts
|
|
document.addEventListener('keydown', function(event) {
|
|
if (event.ctrlKey && event.key === 's') {
|
|
event.preventDefault();
|
|
saveAllPlayers();
|
|
}
|
|
});
|
|
|
|
// Initialize
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
|
|
// Initialize targets for all players
|
|
Object.keys(results.participants).forEach(playerId => {
|
|
initializeTargetsForPlayer(parseInt(playerId));
|
|
|
|
// Update initial states
|
|
for (let i = 1; i <= numTargets; i++) {
|
|
updateTargetGroupStyling(parseInt(playerId), i);
|
|
}
|
|
updateParticipantStatus(parseInt(playerId));
|
|
updateParticipantTens(parseInt(playerId));
|
|
});
|
|
|
|
// Initialize joker checkboxes for league tournaments
|
|
{% if league_state %}
|
|
const leagueState = {{ league_state | tojson | safe }};
|
|
Object.keys(results.participants).forEach(playerId => {
|
|
const checkbox = document.getElementById(`joker-calc-${playerId}`);
|
|
if (checkbox && leagueState.participants && leagueState.participants[playerId]) {
|
|
const participant = leagueState.participants[playerId];
|
|
if (participant.joker_used) {
|
|
checkbox.checked = true;
|
|
checkbox.disabled = true;
|
|
}
|
|
}
|
|
});
|
|
{% endif %}
|
|
|
|
updateOverallProgress();
|
|
updateOverallTens();
|
|
|
|
// Initialize draft panel
|
|
{% if tournament and tournament.rounds %}
|
|
renderDraftPanel();
|
|
{% endif %}
|
|
|
|
// Add input validation and navigation
|
|
document.addEventListener('input', function(e) {
|
|
if (e.target.classList.contains('shot-input')) {
|
|
if (e.target.value !== '') {
|
|
const value = parseInt(e.target.value);
|
|
const clampedValue = Math.max(0, Math.min(10, isNaN(value) ? 0 : value));
|
|
if (e.target.value !== clampedValue.toString()) {
|
|
e.target.value = clampedValue;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
document.addEventListener('keydown', function(e) {
|
|
if (e.target.classList.contains('shot-input') && e.key === 'Enter') {
|
|
const inputs = Array.from(document.querySelectorAll('.shot-input'));
|
|
const currentIndex = inputs.indexOf(e.target);
|
|
const nextInput = inputs[currentIndex + 1];
|
|
if (nextInput) {
|
|
nextInput.focus();
|
|
nextInput.select();
|
|
}
|
|
}
|
|
});
|
|
});
|
|
</script>
|
|
</body>
|
|
</html> |