$(document).ready(function () {
// Global Variables
window.select_subject = 4359
window.babysitter_textArea = 10524
document.title = "מילואים 360 - קרן הסיוע";
//---------------------------SHAHAR LIBA V4 CODE START------------------------
function checkSend() {
// First completely remove all click handlers to prevent multiple bindings
$(".sendBTN").off("click");
// Then add a single new click handler
$(".sendBTN").on("click", function () {
var canNext = true;
var passedChecksForDrop = true;
var passedChecksForDate = true;
var passedChecksForRadio = true;
var passedChecksForTextBox = true;
var passedChecksForUpload = true;
var canContinueUpload = true;
$(`#page${currentPage}`).find('[fieldid]').each(function () {
var currentFieldStyle = $(this).attr("style");
if (currentFieldStyle != undefined) {
if ($(this).attr("style").includes("block") != false) {
// Check dropdown fields
if ($(this).find(".textSelect").length > 0) {
var currentFieldDrop = $(this).find(".textSelect select");
if (currentFieldDrop.val().length <= 0) {
passedChecksForDrop = false;
$(this).find(".validError").text("זהו שדה חובה");
}
}
// Check upload fields
if ($(this).find(".mu_wrap_upload").length > 0) {
var textTitle = $(this).find(".textTitle");
passedChecksForUpload = false;
$(this).find(".mu_wrap_upload input").each(function () {
var totalSize = 0;
var currentSize = 0;
for (var i = 0; i < this.files.length; i++) {
currentSize = this.files[i].size;
currentSize /= 1024 * 1024;
totalSize = currentSize;
}
if (totalSize > 0) {
passedChecksForUpload = true;
}
if (passedChecksForUpload == false) {
canContinueUpload = false;
$(this).parent().parent().find(".validError").text("זהו שדה חובה");
}
});
}
// Removed duplicate dropdown check
// Check date fields
if ($(this).find(".textDate").length > 0) {
var currentFieldDate = $(this).find(".textDate input");
if (currentFieldDate.val().length <= 0) {
passedChecksForDate = false;
$(this).find(".validError").text("זהו שדה חובה");
}
}
// Check radio fields
if ($(this).find(".textRadio").length > 0) {
var currentFieldRadio = $(this).find(".textRadio input");
passedChecksForRadio = false;
currentFieldRadio.each(function (index) {
if (currentFieldRadio[index].checked) {
passedChecksForRadio = true;
}
});
if (!passedChecksForRadio) {
$(this).find(".validError").text("זהו שדה חובה");
}
}
// Check text fields
if ($(this).find(".textBox").length > 0) {
var currentFieldText = $(this).find(".textBox input").val();
if (currentFieldText.length <= 0 && !$(this).hasClass("hidden") && !$(this).attr("fieldid") == "fld_TheEmailaddres") {
passedChecksForTextBox = false;
$(this).find(".validError").text("זהו שדה חובה");
}
}
}
}
});
// Only call validator once if all checks pass
if (passedChecksForDrop && passedChecksForRadio && passedChecksForTextBox && canContinueUpload && passedChecksForDate) {
canSend = true;
} else {
canSend = false;
}
if (canSend) {
if (Wiz("interestedMoneyInMyAcc").getValue().length > 0 && Wiz("list").getValue() == 'keren15') {
Wiz("ManagedList_Shlasha").setValue("keren21");
}
else if (Wiz("interestedMoneyInMyAcc").getValue().length > 0 && Wiz("list").getValue() == 'keren16') {
Wiz("ManagedList_Shlasha").setValue("keren22");
}
else {
Wiz("ManagedList_Shlasha").setValue(Wiz("list").getValue());
}
fixTextAreas();
} else {
alert("יש למלא את כל השדות בטופס על מנת שתוכל/י לשלוח את הטופס");
}
});
}
//---------------------------SHAHAR LIBA V4 CODE END------------------------
var totalSize = 0
$(document).ready(function () {
changeAllUploadsOnChangeFunc()
//---------------------------SHAHAR LIBA V4 CODE START------------------------
wizForms.addStarToMandatoryFields();
checkSend();
$('[fieldid="fld_list"]').on('change', function () {
Wiz('ManagedList_Shlasha').setValue(Wiz('list').getValue());
});
Wiz("partnerOfMil0603").hide()
Wiz("interestedMoneyInMyAcc").hide()
$("[fieldid = 'list']").on("change", function () {
$("[fieldid = 'partnerOfMil0603'] .textRadio input").prop("checked", false);
$("[fieldid = '71'] .textRadio input").prop("checked", false);
$("[fieldid = 'partnerOfMil0603'] .textRadio input ").trigger("change");
var selectedVal = Wiz("list").getValue();
if (selectedVal == 'keren15' || selectedVal == 'keren16') {
Wiz("71").hide()
Wiz("partnerOfMil0603").show();
}
else {
Wiz("partnerOfMil0603").hide()
Wiz("71").show();
$("[fieldid = 'interestedMoneyInMyAcc'] input ").prop("checked", false)
$("[fieldid = 'interestedMoneyInMyAcc'] input ").trigger("change");
}
});
$("[fieldid = 'partnerOfMil0603'] .textRadio input ").on("change", function () {
var selectedVal = Wiz("partnerOfMil0603").getValue();
if (selectedVal == 'כן') {
Wiz("interestedMoneyInMyAcc").show();
}
else {
Wiz("interestedMoneyInMyAcc").hide()
$("[fieldid = 'interestedMoneyInMyAcc'] input ").prop("checked", false)
$("[fieldid = 'interestedMoneyInMyAcc'] input ").trigger("change");
}
});
$("[fieldid = 'interestedMoneyInMyAcc'] input ").on("change", function () {
var selectedVal = Wiz("interestedMoneyInMyAcc").getValue();
if (selectedVal.length <= 0) {
Wiz("bankNumAndName").hide()
Wiz("bankSnifNum").hide()
Wiz("bankAccNum").hide()
Wiz("bankAccName").hide()
$("[fieldid = 'uploadConfirmAccFrmBank'] ").hide()
$("[fieldid = 'uploadCourtDocument'] ").hide()
$("[fieldid = 'confirmDepositCheck'] ").hide()
Wiz("consent").show()
}
else {
Wiz("consent").hide()
}
});
//---------------------------SHAHAR LIBA V4 CODE END------------------------
$("[fieldid = list] .textSelect select").change(function () {
if ($("[fieldid = list] .textSelect select").val() == "keren13") {
hideElems("TheID", "7", "71", "5", "TheEmailAddres", "reqsum", "8", "uploadFiles", "consent")
$("div").each(function () {
// Check if the div has the class "noFieldId"
if ($(this).hasClass("noFieldId")) {
$(this).addClass("hidden");
}
});
$(".btnAtz").removeClass("hidden")
}
else {
$(".btnAtz").addClass("hidden")
showElems("TheID", "7", "71", "5", "TheEmailAddres", "reqsum", "8", "uploadFiles", "consent")
$("div").each(function () {
// Check if the div has the class "noFieldId"
if ($(this).hasClass("noFieldId")) {
$(this).removeClass("hidden");
}
});
}
});
//fix later for popup
createPopUp();
//----------------------------------- shahar up
// Hide 'שליחה' button when keren13 is chosen in 'נושא פנייה'
var dropdownField = $('[fieldid="list"]')
// 'נושא פנייה' on change function
dropdownField.on('change', function () {
var selectedValue = $('[fieldid="list"] > .textSelect > select').val()
if (selectedValue == 'keren13') {
$('#finishForm').hide()
$('[fieldid="uploadFiles"]').hide();
$('#elemID4369').hide();
//fix later for popup
//showPopUp();
} else {
$('#finishForm').show()
$('[fieldid="uploadFiles"]').show();
$('#elemID4369').show();
}
})
// Made By Shon - Changed By Tomer Ivan in 18/02/2025
// Default Situation - Make 0 Files if none were uploaded
// Get The Amount Of files
// Change The Text Field to hold the correct amount (Which is 0 at the begining)
var uploadfilesFieldids = []
var uploadfilesFields = $('.mu_wrap_upload').parent().each(function () {
uploadfilesFieldids.push($(this).attr('fieldid'))
})
window.uploadfilesFieldids = uploadfilesFieldids;
var hiddenInput = $(".filesCopy .textBox input");
window.cureent_file_sizes = 0
window.current_file_amount = 0
hiddenInput.val(window.current_file_amount);
for (var i = 0; i < uploadfilesFieldids.length; i++) {
$(`[fieldid=${uploadfilesFieldids[i]}] > .textTitle`).append(`
סך הכל צורפו 0 קבצים במשקל כולל של 0MB`)
}
// Start an Event - to get the changes in the form.
$('.mu_upload').on('change', function () {
window.current_file_amount += 1;
window.current_file_sizes = 0
// Start WIZ actions
var element = this;
console.log(element);
checkFileType(element);
// change it in the field
hiddenInput.val(window.current_file_amount);
// show the user the uploaded amount
for (var i = 0; i < window.uploadfilesFieldids.length; i++) {
var current_fieldid = window.uploadfilesFieldids[i]
var fileInfo = GetFileSizes(current_fieldid)
var file_count = fileInfo[0];
var file_size = fileInfo[1];
$(`[fieldid=${window.uploadfilesFieldids[i]}]`).find('.textTitle .filesAmount').text(`סך הכל צורפו ${file_count} קבצים במשקל ${file_size}MB`)
window.current_file_sizes += parseFloat(file_size);
console.log(window.current_file_sizes);
}
if (window.current_file_amount >= 10 || window.current_file_sizes > 10) {
alert("שימו לב, קיימת מגבלה כוללת של 10 קבצים במשקל כולל של 10MB ");
$('#finishForm').hide()
}
else {
$('#finishForm').show()
}
});
$(document).on('click', `.mu_attachedfile input[type='button']`, function () {
window.current_file_amount -= 1;
window.current_file_sizes = 0
hiddenInput.val(window.current_file_amount);
for (var i = 0; i < window.uploadfilesFieldids.length; i++) {
var current_fieldid = window.uploadfilesFieldids[i]
var fileInfo = GetFileSizes(current_fieldid)
var file_count = fileInfo[0];
var file_size = fileInfo[1];
$(`[fieldid=${window.uploadfilesFieldids[i]}]`).find('.textTitle .filesAmount').text(`סך הכל צורפו ${file_count} קבצים במשקל ${file_size}MB`)
window.current_file_sizes += parseFloat(file_size);
console.log(window.current_file_sizes);
}
if (window.current_file_amount >= 10 || window.current_file_sizes > 10) {
alert("שימו לב, קיימת מגבלה כוללת של 10 קבצים במשקל כולל של 10MB ");
$('#finishForm').hide()
}
else {
$('#finishForm').show()
}
})
//--------------------------------------------------------------
displayFooterLogo();
$('#blanket_text').text('מעלה קבצים...')
const dropDownField = $("[fieldid='list'] > .textSelect > select")
const hiddenField = $("[fieldid='hiddenField'] > .textBox > input")
dropDownField.on('change', function () {
const value = $("[fieldid='list'] > .textSelect > select").find("option:selected").text()
hiddenField.val(value)
})
});
function displayFooterLogo() {
var footerHtml = ``;
$(".upperView").append(footerHtml);
}
function headerLogos() {
$('#formLogo').children().remove()
const html_to_append = `
`;
$('#formLogo').append(html_to_append)
}
headerLogos()
function closePopUp() {
$(".overlay").hide();
$(".popup").hide();
$("[fieldid='list'] .textSelect > select").val("").change();
}
function showPopUp() {
$(".overlay").show();
$(".popup").show();
}
function createPopUp() {
var HTMLtoAdd = `
באפשרותכם להגיש בקשה מפורטת לאוכלוסיית העצמאיים באמצעות בקשה יעודית.
`
var container = $("#page1")
container.after(HTMLtoAdd)
$(".popup").hide();
}
function changeAllUploadsOnChangeFunc() {
var uploadFields = $("[fieldid*='upload']");
$(uploadFields).each(function () {
$(this).find("input").attr("onChange", "")
});
}
function checkFileType(elem) {
var file = $(elem)[0].files;
var fileName = file[0].name;
var fileExtension = fileName.split(".").pop().toLowerCase();
if (fileExtension == "jpeg" || fileExtension == "jpg" || fileExtension == "pdf" || fileExtension == "doc" || fileExtension == "docx" || fileExtension == "png" || fileExtension == "tiff") {
addMultiFile(elem);
validFileType = true;
} else {
alert("ניתן לצרף רק קבצים בפורמטים הבאים: .jpg .jpeg .pdf .doc .docx .png .tiff .bmp");
$(elem).val("")
validFileType = false
}
}
function GetFileSizes(fieldarg) {
var filesArray = $(`[fieldid=${fieldarg}] > .mu_wrap_upload`).children().filter('.mu_upload[active=true]');
var total_size = 0
var total_count = 0
filesArray.each(function () {
if (this.files.length > 0) {
total_size += this.files[0].size;
total_count++;
}
})
total_size /= 1024 * 1024 // convert to MB
return [total_count, total_size.toFixed(3)];
}
function GetFileSizes2() {
$(".mu_wrap_upload > input").each(function () {
$(this).on("change", function () {
var currentSize = $(this)[0].files[0].size;
currentSize /= 1024 * 1024;
$(this).attr("currentSize", currentSize);
totalSize = currentSize;
if (totalSize > 10) {
$('#finishForm').hide()
alert("שים לב! גודל הקבצים המצורפים עולה על 10MB לכן לא ניתן לשלוח את הטופס");
}
$(".fileSize").hide();
$("#elemID4368 .textTitle").append(`
גודל קבצים מצורפים: MB ${totalSize.toFixed(3)}
`);
setTimeout(function () {
$("[name^=fileToUpload] > input").attr("onclick", '');
$("[name^=fileToUpload] > input").on("click", function () {
var name = $(this).parent().attr("name");
totalSize -= parseFloat($(`#${name}`).attr("currentSize"));
if (totalSize < 10) {
$('#finishForm').show()
}
$(`#${name}`).attr("currentSize", 0);
removeFile(this);
$(".fileSize").hide();
$("#elemID4368 .textTitle").append(`
גודל קבצים מצורפים: MB ${totalSize.toFixed(3)}
`);
})
}, 500)
});
});
}
function hideElems(...fieldids) {
for (const fieldid of fieldids) {
elem(fieldid).parent().hide()
elem(fieldid).hide()
}
}
function showElems(...fieldids) {
for (const fieldid of fieldids) {
elem(fieldid).parent().show()
elem(fieldid).show()
}
}
function elem(fieldid) {
if (fieldid.includes('modal'))
return ($("[fieldid^='" + fieldid + "']"))
else
return ($("[fieldid='" + fieldid + "']"))
}
});
// Babysitter logics - 11/02/2025
// Define the target value as a variable for easy modification
$(document).ready(function () {
const SHOW_TABLE_FOR_VALUE = 'KerenBabysitter';
// Remove entry function
function removeEntry(index) {
entries.splice(index, 1);
updateEntriesList();
// Update textarea after removing entry
const table = document.querySelector('table');
const rows = table.querySelectorAll('tbody tr');
var paragraph = '\n-----\n';
// Loop through each row and convert it to text
rows.forEach(row => {
const cells = row.querySelectorAll('td');
const year = cells[0].textContent.trim();
const month = cells[1].textContent.trim();
const amount = cells[2].textContent.trim();
paragraph += `${month} ${year}: ${amount} \n`;
});
paragraph +='------'
// Output the paragraph
$('textArea[fieldid=fld_babysitter_sum]').val(paragraph);
// Hide summary row if table is empty
if (entries.length === 0) {
$('.summary-row').hide();
}
}
// Function to toggle form visibility
// Modified toggle form visibility function
function toggleFormVisibility() {
const selectedValue = $('select[fieldid=fld_list]').val();
const shouldShow = selectedValue === SHOW_TABLE_FOR_VALUE;
// Elements to toggle
const formElements = [
'.entry-form',
'.entries-list',
'#tableErrorMsg',
'.summary-row' // Add summary row to elements to toggle
];
// Toggle visibility of all elements
formElements.forEach(selector => {
$(selector)[shouldShow ? 'show' : 'hide']();
});
// If hiding the form, clear the entries
if (!shouldShow) {
entries = [];
updateEntriesList();
$('textArea[fieldid=fld_babysitter_sum]').val('');
}
// Return the selected value for potential use
return selectedValue;
}
// Store entries
let entries = [];
$(document).ready(function () {
const button = document.getElementsByClassName('add-btn');
button.onclick = null; // Clears any inline `onclick` event
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth() + 1;
// Create and append the form
const formHtml = `
שנה
חודש
סכום
התחרטת?
`;
$('div[fieldid=Babysitter_records]').parent().after(formHtml);
// Generate year options from 2023 to current year
function generateYearOptions() {
let options = '';
for (let year = 2023; year <= currentYear; year++) {
options += ``;
}
return options;
}
// Generate month options
function generateMonthOptions() {
const months = [
'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני',
'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
];
let options = '';
months.forEach((month, index) => {
options += ``;
});
return options;
}
$('#yearSelect').val(currentYear).trigger('change');
$('#monthSelect').val(currentMonth).trigger('change');
// Update month options based on selected year
$('#yearSelect').change(function () {
const selectedYear = parseInt($(this).val());
const monthSelect = $('#monthSelect');
$('#monthSelect').children().each(function () {
$(this).prop('disabled', false); // Enables each option
});
if (selectedYear === currentYear) {
if (parseInt(monthSelect.val()) > currentMonth) {
monthSelect.val(currentMonth);
}
monthSelect.find('option').each(function () {
const monthVal = parseInt($(this).val());
$(this).prop('disabled', monthVal > currentMonth);
});
} else {
monthSelect.val(1).trigger('change')
monthSelect.find('option').prop('disabled', false);
}
if (selectedYear === 2023) {
monthSelect.find('option').each(function () {
const monthVal = parseInt($(this).val());
$(this).prop('disabled', monthVal != 10 && monthVal != 11 && monthVal != 12)
});
$('#monthSelect').val(10).trigger('change');
};
});
// Add change event listener to the select
$('select[fieldid=fld_list]').on('change', function () {
toggleFormVisibility();
// Execute the original onchange events after our custom logic
const originalOnchange = this[0].getAttribute('onchange');
if (originalOnchange) {
// Execute each function in the original onchange
originalOnchange.split(';').forEach(func => {
if (func.trim()) {
try {
new Function(func)();
} catch (e) {
console.error('Error executing original onchange:', e);
}
}
});
}
});
// Initialize month restrictions and form visibility
$('#yearSelect').trigger('change');
toggleFormVisibility();
});
// Add entry function
// Function to add entry with fixed validation
function addEntry() {
const year = parseInt($('#yearSelect').val());
const month = parseInt($('#monthSelect').val());
const rawValue = $('#numberInput').val().trim();
const number = parseFloat(rawValue);
const errorMsg = $('#errorMsg');
// Clear any existing error message first
errorMsg.hide().text('');
// Validation checks
if (rawValue === '') {
errorMsg.text('יש להכניס מספר').show();
return false;
}
if (isNaN(number) || number < 0) {
errorMsg.text('יש להכניס מספר גדול מ ₪0').show();
return false;
}
// Check for duplicate month and year combination
const isDuplicate = entries.some(entry =>
entry.year === year && entry.month === month
);
if (isDuplicate) {
errorMsg.text('רשומה עבור חודש ושנה זו כבר קיימת').show();
// Hide the error message after 5 seconds
/*setTimeout(() => {
errorMsg.fadeOut(() => errorMsg.text(''));
}, 5000);*/
return false;
}
// Add new entry
entries.push({ year, month, number });
// Sort entries
entries.sort((a, b) => {
if (a.year !== b.year) return a.year - b.year;
return a.month - b.month;
});
updateEntriesList();
$('#numberInput').val('');
return true;
}
// Modified click handler for add button
$(document).on('click', '.add-btn', function (event) {
event.preventDefault();
addEntry();
});
// Modified click handler for add button
$(document).on('click', '.remove-btn', function (event) {
event.preventDefault();
});
// Modified select change event handler
$('select[fieldid=fld_list]').on('change', function (event) {
// First run our visibility toggle
toggleFormVisibility();
// Don't try to execute original handlers directly
// Instead, let them run through event bubbling
// Safely check and call required functions
try {
if (typeof toggleField === 'function') {
toggleField(this, window.select_subject);
}
} catch (e) {
console.warn('Error in toggleField:', e);
}
try {
if (typeof setMandatory === 'function' && this.value) {
setMandatory(this, 1);
}
} catch (e) {
console.warn('Error in setMandatory:', e);
}
try {
if (typeof saveChanges === 'function') {
saveChanges(this);
}
} catch (e) {
console.warn('Error in saveChanges:', e);
}
try {
if (typeof AlertMandatoryField === 'function' && this.id) {
AlertMandatoryField(this.id, $(this));
}
} catch (e) {
console.warn('Error in AlertMandatoryField:', e);
}
});
// Modified toggle form visibility function
function toggleFormVisibility() {
const selectedValue = $(`#sel${window.select_subject}`).val();
const shouldShow = selectedValue === SHOW_TABLE_FOR_VALUE;
// Elements to toggle
const formElements = [
'.entry-form',
'.entries-list',
'#tableErrorMsg'
];
// Toggle visibility of all elements
formElements.forEach(selector => {
$(selector)[shouldShow ? 'show' : 'hide']();
});
// If hiding the form, clear the entries
if (!shouldShow) {
entries = [];
updateEntriesList();
$('textArea[fieldid=fld_babysitter_sum]').val('');
}
// Return the selected value for potential use
return selectedValue;
}
// Update entries list
// Update entries list with summary
function updateEntriesList() {
const months = [
'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני',
'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
];
// Create number formatter
const numberFormatter = new Intl.NumberFormat('he-IL', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
const entriesHtml = entries.map((entry, index) => `
${entry.year}
${months[entry.month - 1]}
₪${numberFormatter.format(entry.number)}
`).join('');
// Calculate total sum
const totalSum = entries.reduce((sum, entry) => sum + entry.number, 0);
// Format the sum using the same formatter
const formattedSum = numberFormatter.format(totalSum);
// Create summary row HTML
const summaryHtml = `
סה"כ: ₪${formattedSum}
`;
// Update table and append summary
$('#entriesList').html(entriesHtml);
// Remove existing summary if it exists
$('.summary-row').remove();
// Add new summary after the table
$('.entries-list').after(summaryHtml);
}
// Update textarea when adding entry
$(document).on('click', '.add-btn', function () {
const table = document.querySelector('table'); // Select the table
const rows = table.querySelectorAll('tbody tr'); // Get all rows in tbody
var paragraph = '\n-----\n';
// Loop through each row and convert it to text
rows.forEach(row => {
const cells = row.querySelectorAll('td'); // Get cells in the row
const year = cells[0].textContent.trim();
const month = cells[1].textContent.trim();
const amount = cells[2].textContent.trim();
paragraph += `${month} ${year}: ${amount} \n`;
});
paragraph += '------'
// Output the paragraph
$('textArea[fieldid=fld_babysitter_sum]').val(paragraph);
});
// Remove entry from the table
$(document).on('click', '.remove-btn', function () {
index = $(this).attr('id').split("_")[1]
removeEntry(index)
});
// Create a function to check table entries that returns a promise
function validateTableEntries() {
return new Promise((resolve) => {
// Remove any existing error message first
$('#tableErrorMsg').remove();
// Check if there are any entries
if (entries.length === 0 && $('[fieldid=fld_list]').val() == 'KerenBabysitter') {
// Create error message element
const errorHtml = `
יש להזין לפחות רשומה אחת לפני שליחה
`;
// Add error message below the table
$('.entries-list').after(errorHtml);
$('#tableErrorMsg').show();
// Scroll to error message with smooth animation
const errorElement = document.getElementById('tableErrorMsg');
// Hide the error message after 5 seconds
/*setTimeout(() => {
$('#tableErrorMsg').fadeOut(() => {
if (document.getElementById('tableErrorMsg')) {
document.getElementById('tableErrorMsg').textContent = '';
}
});
}, 5000);*/
resolve(false);
} else {
resolve(true);
}
});
}
// Create a wrapper for the original validator that returns a promise
function originalValidatorWrapper(param1, param2) {
return new Promise((resolve) => {
const result = window.validator(param1, param2);
resolve(result);
});
};
// Add change event listener to the select
$('select[fieldid=fld_list]').on('change', function (event) {
// First run our visibility toggle
toggleFormVisibility();
// Let the original onchange events proceed naturally
// Instead of trying to execute them manually
event.stopPropagation(); // Prevent double execution
// If you still need to ensure specific functions run, check if they exist first
if (typeof toggleField === 'function') {
toggleField(this, window.select_subject);
}
if (typeof setMandatory === 'function') {
setMandatory(this, 1);
}
if (typeof saveChanges === 'function') {
saveChanges(this);
}
if (typeof AlertMandatoryField === 'function') {
AlertMandatoryField(this.id, $(this));
}
});
// Push total Babysitter amount to the Total Required Field, and lock the field.
window.selectedSubject = "";
$(document).on('change', function () {
var selectedSubject = $(`select[fieldid=fld_list]`).val()
var fldSum = $(`input[fieldid=fld_reqsum]`)
if ((selectedSubject === "KerenBabysitter" && (window.selectedSubject != "KerenBabysitter"))) {
$('#paymentErrorMsg').show()
$('[fieldid=Babysitter_afternoon]').parent().show()
fldSum.attr('disabled', true);
fldSum.val('');
window.selectedSubject = "KerenBabysitter";
$('#finishForm').attr('onclick','fixTextAreas()');
}
else if ((selectedSubject != "KerenBabysitter") && (window.selectedSubject == "KerenBabysitter")) {
$('#paymentErrorMsg').hide()
fldSum.attr('disabled', false)
$('[fieldid=Babysitter_afternoon]').parent().hide()
fldSum.val('');
window.selectedSubject = selectedSubject;
$('#finishForm').attr('onclick',`fixTextAreas();validator('1','')`);
}
});
$(document).on('click', '.add-btn', function () {
var BabysitterSum = parseFloat($('.summary-row > strong').text().split(" ")[1].split('₪')[1].replace(/,/g, ""))
var fldSum = $(`input[fieldid=fld_reqsum]`)
if (BabysitterSum > 0) {
fldSum.val(BabysitterSum)
}
else {
fldSum.val('')
}
})
// Wrapper Bugfixes - 16/02/2025
function pushBabySitterCheckboxes() {
var htmltopush = `
`;
var titleParent = $('div[fieldid=Payment_method]').parent();
$(titleParent).after(htmltopush);
$('.wrapper').hide()
}
function validatePaymentMethod() {
return new Promise((resolve) => {
// Remove any existing error message first
$('#paymentErrorMsg').remove();
var SelectedSubject = $('[fieldid=fld_list]').val() == "KerenBabysitter"
// Check if at least one checkbox is selected
const isChecked = $('#option-1').is(':checked') || $('#option-2').is(':checked');
if (SelectedSubject && !isChecked) {
// Create error message element
const errorHtml = `
אנא בחר שיטת תשלום לפני ההגשה
`;
// Add error message below the wrapper
$('.wrapper').after(errorHtml);
$('#paymentErrorMsg').show();
// Scroll to error message with smooth animation
const errorElement = document.getElementById('paymentErrorMsg');
// Hide the error message after 5 seconds
/*setTimeout(() => {
$('#paymentErrorMsg').fadeOut(() => {
if (document.getElementById('paymentErrorMsg')) {
document.getElementById('paymentErrorMsg').textContent = '';
}
});
}, 5000);*/
resolve(false);
} else {
resolve(true);
}
});
};
function PaymentMethodLogics() {
// Attach the change event to the checkboxes
$('input[type="checkbox"]').on('change', function () {
var Paybox = $('#option-1').prop('checked');
var Physical = $('#option-2').prop('checked');
// Get the parent elements for Paybox and Physical multi-upload
var PayboxMultUpload = $('input[fieldid=fld_uploadFiles2]').parent().parent().parent();
var PhysicalMultUpload = $('input[fieldid=fld_uploadFiles3]').parent().parent().parent();
$(PayboxMultUpload).hide()
$(PhysicalMultUpload).hide()
// Show/hide based on the checkbox state
if (Physical) {
$(PhysicalMultUpload).show();
} else {
$(PhysicalMultUpload).hide();
}
if (Paybox) {
$(PayboxMultUpload).show();
} else {
$(PayboxMultUpload).hide();
}
});
}
$(document).ready(function () {
$('input[fieldid=fld_uploadFiles2]').parent().parent().parent().hide()
$('input[fieldid=fld_uploadFiles3]').parent().parent().parent().hide()
pushBabySitterCheckboxes(); // Create the checkboxes
PaymentMethodLogics(); // Bind event handlers to the checkboxes
$("select[fieldid=fld_list]").on('change', function () {
if ($("select[fieldid=fld_list]").val() === "KerenBabysitter") {
$('.wrapper').show()
}
else {
$('.wrapper').hide();
$('input[fieldid=fld_uploadFiles2]').parent().parent().parent().hide()
$('input[fieldid=fld_uploadFiles3]').parent().parent().parent().hide()
}
})
});
// Check Upload for Payment Method Documents
function createErrorPlaceHolders() {
var physicalmessageExists = $('#paymentErrorMsg2').length == 0;
const physicalerrorHtml = `
`;
// Add error message below the wrapper
if (physicalmessageExists) {
$(`[fieldid=uploadFiles3]`).after(physicalerrorHtml);
}
var bitmessageExists = $('#paymentErrorMsg1').length == 0;
const biterrorHtml = `
`;
// Add error message below the wrapper
if (bitmessageExists) {
$(`[fieldid=uploadFiles2]`).after(biterrorHtml);
}
}
createErrorPlaceHolders();
function validateBitDocumentsMethod() {
return new Promise((resolve) => {
// Remove any existing error message first
$('#paymentErrorMsg1').text('');
// Check what option should be shown (bit/physical)
var SelectedSubject = $('[fieldid=fld_list]').val() == "KerenBabysitter"
var BitPayment = $('#option-1').is(':checked')
var PhysicalPayment = $('#option-2').is(':checked');
var mult_upload_bit = $(`[fieldid=uploadFiles2] .mu_attachedfile`).length
var mult_upload_physical = $(`[fieldid=uploadFiles3] .mu_attachedfile`).length
if (SelectedSubject && BitPayment && mult_upload_bit == 0) {
$('#paymentErrorMsg1').text('יש לצרף אסמכתא בגין ביצוע תשלום באמצעות העברה בנקאית או אפליקציית תשלום')
$('#paymentErrorMsg1').show();
// Scroll to error message with smooth animation
const errorElement = document.getElementById('paymentErrorMsg1');
/* Hide the error message after 5 seconds
setTimeout(() => {
$('#paymentErrorMsg1').fadeOut(() => {
if (document.getElementById('paymentErrorMsg1')) {
document.getElementById('paymentErrorMsg1').textContent = '';
}
});
}, 5000);*/
resolve(false);
}
else {
resolve(true);
}
});
}
function validatePhysicalDocumentsMethod() {
return new Promise((resolve) => {
// Remove any existing error message first
$('#paymentErrorMsg2').text('')
// Check what option should be shown (bit/physical)
var SelectedSubject = $('[fieldid=fld_list]').val() == "KerenBabysitter"
var BitPayment = $('#option-1').is(':checked')
var PhysicalPayment = $('#option-2').is(':checked');
var mult_upload_bit = $(`[fieldid=uploadFiles2] .mu_attachedfile`).length
var mult_upload_physical = $(`[fieldid=uploadFiles3] .mu_attachedfile`).length
if (SelectedSubject && PhysicalPayment && mult_upload_physical == 0) {
// Create error message element
$('#paymentErrorMsg2').text('יש לצרף אסמכתא לתשלום במזומן')
// Scroll to error message with smooth animation
const errorElement = document.getElementById('paymentErrorMsg2');
// Hide the error message after 5 seconds
/*setTimeout(() => {
$('#paymentErrorMsg2').fadeOut(() => {
if (document.getElementById('paymentErrorMsg2')) {
document.getElementById('paymentErrorMsg2').textContent = '';
}
});
}, 5000);*/
resolve(false);
}
else {
resolve(true);
}
});
}
// bug fix Atzmaim - 16/02/2025
window.field_id_list_SingleParent = ['KnownAsSadir', 'GotInjured', 'SubmitNotice', 'UserAgreement', 'FilesAreChecked', 'EverythingIsCorrect', 'Signature']
window.field_id_list_DoubleParent = ['fld_reservistEmail']
$('[fieldid="fld_list"]').on('change', function () {
if ($('[fieldid="fld_list"]').val() == 'keren13') {
for (var i = 0; i < window.field_id_list_SingleParent.length; i++) {
$(`[fieldid=${window.field_id_list_SingleParent[i]}]`).parent().hide()
}
for (var i = 0; i < field_id_list_DoubleParent.length; i++) {
$(`[fieldid=${window.field_id_list_DoubleParent[i]}]`).parent().parent().hide()
}
}
else {
for (var i = 0; i < window.field_id_list_SingleParent.length; i++) {
$(`[fieldid=${window.field_id_list_SingleParent[i]}]`).parent().show()
}
for (var i = 0; i < field_id_list_DoubleParent.length; i++) {
$(`[fieldid=${window.field_id_list_DoubleParent[i]}]`).parent().parent().show()
}
}
})
/*// Bug fix - remove the original on click event as validator on the finishform button
function removeOnClick() {
$('#finishForm').attr('onclick','fixTextAreas()')
}
removeOnClick();*/
// Bug fix - scroll up when error message occures
const originalAnimate = $.fn.animate;
$.fn.animate = function (properties) {
this.stop(true, false)
if (properties && 'scrollTop' in properties) {
// Find the first Error message that has content
const firstError = $('.validError').filter(function () {
return $(this).text().trim().length > 0;
}).first();
// If we found an error with content
if (firstError.length > 0) {
const errorPosition = firstError.offset().top;
const scrollPosition = errorPosition - 300;
properties.scrollTop = scrollPosition;
}
}
return originalAnimate.apply(this, arguments);
};
// Bug fix - correct checkbox positioning in the code
var problematic_checkboxes = ['UserAgreement', 'FilesAreChecked', 'EverythingIsCorrect','Babysitter_afternoon']
for (var i = 0; i < problematic_checkboxes.length; i++) {
$(`[fieldid=${problematic_checkboxes[i]}]`).css({ 'display': 'flex', 'gap': '5px', 'align-items': 'center' });
$(`[fieldid=${problematic_checkboxes[i]}]`).after($(`[fieldid=${problematic_checkboxes[i]}] > .validError`))
var parent = $(`[fieldid=${problematic_checkboxes[i]}]`).parent();
var corrected_valid_error = $(parent).children().filter('.validError');
$(parent).css({ 'display': 'flex', 'flex-direction': 'column', 'align-items': 'flex-start' });
$(corrected_valid_error).css({ 'margin-right': '21px', 'margin-bottom': '20px' });
if (problematic_checkboxes[i] == "Babysitter_afternoon"){
$(parent).hide()
}
};
// Reset onClick Event for custom logics:
$('#finishForm').attr('onclick','fixTextAreas()')
$(document).on('click', '.sendBTN', async function (event) {
event.preventDefault();
try {
// Run all validations in parallel
const [tableValid, paymentValid, bitValid, physicalValid] = await Promise.all([
validateTableEntries(),
validatePaymentMethod(),
validateBitDocumentsMethod(),
validatePhysicalDocumentsMethod()
]);
// If all validations pass, call validator ONCE
if (tableValid && paymentValid && bitValid && physicalValid) {
if (typeof fixTextAreas === 'function') {
fixTextAreas();
validator('1', '');
}
// Execute any additional onclick logic if needed
const originalOnclick = this.getAttribute('onclick');
if (originalOnclick) {
new Function(originalOnclick.replace(/validator\('1',''\)/g, 'true'))();
}
}
else{
$('html, body').animate({
scrollTop: $('.validError').filter(function() {
return $(this).text().trim().length > 0;
}).first().offset().top
}, 1000);
fixTextAreas();
}
} catch (error) {
console.error('Validation error:', error);
}
});
/* Favicon for Light/Dark Mode*/
/* Initialization */
var userMode = window.matchMedia('(prefers-color-scheme: dark)')
if (userMode.matches){
$('link[rel="shortcut icon"]').attr('href','https://mushlam-frontend.wiz.digital.idf.il/getFile.aspx?profile=10054&fname=mil360Dark.png')
}
else{
$('link[rel="shortcut icon"]').attr('href','https://mushlam-frontend.wiz.digital.idf.il/getFile.aspx?profile=10054&fname=mil360Light.png')
}
/* The user changes between modes */
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change',event => {
/* User is on Dark Mode */
if (event.matches){
$('link[rel="shortcut icon"]').attr('href','https://mushlam-frontend.wiz.digital.idf.il/getFile.aspx?profile=10054&fname=mil360Dark.png')
}
/* User Is On Light Mode */
else {
$('link[rel="shortcut icon"]').attr('href','https://mushlam-frontend.wiz.digital.idf.il/getFile.aspx?profile=10054&fname=mil360Light.png')
}
})
/* Appeal Subject Handling - Written By Tomer 11/03/2025 */
/* Remove the option to appeal on appeal*/
$(`[fieldid="fld_AppealSubject"]`).children().filter('[value="kerenTemp"]').remove();
$(document).on('change',function(){
var current_selection_val = $(`[fieldid="fld_AppealSubject"]`).val()
var current_selection_text = $(`[fieldid="fld_AppealSubject"] option[value="${current_selection_val}"]`).text()
$(`[fieldid="fld_AppealSubjectText"]`).val(`${current_selection_text}`)
});
});