jQuery(document).ready(function($) {
function analyzeMatchResults() {
$(document).on('change', '[id^="field_nqfb-m"][id$="-hpts-p13"], [id^="field_nqfb-m"][id$="-apts-p22"]', function () {
var homeWins = 0;
var homeDraws = 0;
var homeLosses = 0;
var awayWins = 0;
var awayDraws = 0;
var awayLosses = 0;
// Check existence of elements before processing
$('[id^="field_nqfb-m"][id$="-hpts-p13"]').each(function () {
var value = parseFloat($(this).val());
if (value === 1) {
homeWins++;
} else if (value === 0.5) {
homeDraws++;
} else if (!isNaN(value) && value !== 1 && value !== 0.5) {
homeLosses++;
}
});
$('[id^="field_nqfb-m"][id$="-apts-p22"]').each(function () {
var value = parseFloat($(this).val());
if (value === 1) {
awayWins++;
} else if (value === 0.5) {
awayDraws++;
} else if (!isNaN(value) && value !== 1 && value !== 0.5) {
awayLosses++;
}
});
$('#field_home-games-won').val(homeWins).trigger('change');
$('#field_home-games-drawn').val(homeDraws).trigger('change');
$('#field_home-games-lost').val(homeLosses).trigger('change');
$('#field_away-games-won').val(awayWins).trigger('change');
$('#field_away-games-drawn').val(awayDraws).trigger('change');
$('#field_away-games-lost').val(awayLosses).trigger('change');
});
}
function calculateMatchResults() {
$(document).on('change', '#field_homepts, #field_awaypts', function () {
var homePts = parseInt($('#field_homepts').val());
var awayPts = parseInt($('#field_awaypts').val());
var homeTeamID = $('#field_home-team-id-lookup').val();
var awayTeamID = $('#field_away-team-id-lookup').val();
var matchWinner = '';
var matchLoser = '';
var matchHomePts = homePts;
var matchAwayPts = awayPts;
var matchDraw = 0;
if (homePts > awayPts) {
matchWinner = homeTeamID;
matchLoser = awayTeamID;
} else if (homePts < awayPts) {
matchWinner = awayTeamID;
matchLoser = homeTeamID;
} else {
matchDraw = 1;
}
$('#field_match-winner').val(matchWinner);
$('#field_match-loser').val(matchLoser);
$('#field_match-home-pts').val(matchHomePts);
$('#field_match-away-pts').val(matchAwayPts);
if (matchDraw) {
$('#field_match-homedraw').val(homeTeamID);
$('#field_match-awaydraw').val(awayTeamID);
} else {
$('#field_match-homedraw').val('');
$('#field_match-awaydraw').val('');
}
});
}
calculateMatchResults();
analyzeMatchResults();
});