function initScript(menu,submenu,subfunction = null, subparam = null){
if(unsaved){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "unloadForm",
menu: menu,
submenu: submenu
}),
success: function(responseText, responseStatus) {
showConfirmationModal(responseText);
}
});
}else{
if(subfunction != null){
if(subparam != null){
window[submenu](subfunction,subparam);
}else{
window[submenu](subfunction);
}
}else{
try {
window[submenu]();
}
catch(err) {
setTimeout(function() {
window[submenu]();
}, 200);
}
}
}
}
function pushBackClick(func, param){
var arr = [];
if (sessionStorage.getItem("backclick") !== null) {
arr = JSON.parse(sessionStorage.getItem("backclick"));
}
const lastElement = arr[arr.length - 1];
var newanchor = [func,arrayToCommaSepString(param)]
if(lastElement === undefined || !arraysAreEqual(lastElement,newanchor)){
arr.push(newanchor);
sessionStorage.setItem("backclick", JSON.stringify(arr));
}
history.pushState({ custom: true }, "");
}
function popBackClick(){
if (sessionStorage.getItem("backclick") !== null) {
const arr = JSON.parse(sessionStorage.getItem("backclick"));
arr.pop();
sessionStorage.setItem("backclick", JSON.stringify(arr));
}
}
function clearBackClick(){
const arr = [];
sessionStorage.setItem("backclick", JSON.stringify(arr));
}
function triggerBackClick(){
history.back();
}
function handleBackClick(){
exitFullScreen();
saveFilter();
if (sessionStorage.getItem("backclick") !== null) {
const arr = JSON.parse(sessionStorage.getItem("backclick"));
const previousPage = arr[arr.length - 2];
arr.pop();
arr.pop();
sessionStorage.setItem("backclick", JSON.stringify(arr));
if(previousPage !== undefined){
if(previousPage[1] != ""){
if(previousPage[1].includes(", ")){
const indexOfComma = previousPage[1].indexOf(', ');
const functionName = previousPage[1].slice(0, indexOfComma);
const param = previousPage[1].slice(indexOfComma + 2); // +2 to skip the ", "
window[previousPage[0]](functionName,param);
}else{
window[previousPage[0]](previousPage[1]);
}
}else{
window[previousPage[0]]();
}
}
}
}
function arrayToCommaSepString(param) {
if (Array.isArray(param)) {
const tempArr = param.map((item) => {
if (Array.isArray(item)) {
return "['" + item.join("', '") + "']";
} else {
return `${item}`;
}
});
return tempArr.join(", ");
} else {
if (!param || param === "") {
return "";
} else {
return `${param}`;
}
}
}
function arraysAreEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function showAlert(responseText){
var arr = responseText.split("&");
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "showAlert",
alertType: arr[0],
alertMsg: arr[1]
}),
success: function(responseText, responseStatus) {
var alert = document.createElement('div');
alert.innerHTML = responseText;
if(document.getElementById('tw-alert-section') == null){
var alertSection = document.createElement('div');
alertSection.setAttribute("id","tw-alert-section");
document.body.appendChild(alertSection);
}
document.getElementById('tw-alert-section').appendChild(alert);
setTimeout(function() {
alert.classList.remove('animate-alert-animation-in');
alert.classList.add('animate-alert-animation-out');
setTimeout(function() {
alert.parentNode.removeChild(alert);
}, 490);
}, 5000);
}
});
return arr[0];
}
function closeAlert(event){
event.parentElement.classList.remove('animate-alert-animation-in');
event.parentElement.classList.add('animate-alert-animation-out');
setTimeout(function() {
event.parentElement.remove();
}, 490);
}
function closeTip(event){
event.parentElement.remove();
}
function showModal(responseText){
let modal = document.getElementById("modal");
let modalcontainer = modal.children[0];
modal.classList.remove('hidden');
modal.classList.add('animate-fade-animation-in');
jQuery('#modal').children().html(responseText);
modalcontainer.classList.add('animate-modal-animation-in');
$('body').addClass('tw-modal-open');
initForm();
hideLoading();
}
function showVideoModal(videotype){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "showVideoModal",
videotype: videotype
}),
success: function(responseText, responseStatus) {
showModal(responseText);
if (videotype == "setup-account"){
amplitude.getInstance().logEvent("Watch Setup Now");
} else if (videotype == "sale-invoice"){
amplitude.getInstance().logEvent("Watch Sales Invoice Tutorial");
} else if (videotype == "purchase-invoice"){
amplitude.getInstance().logEvent("Watch Purchase Invoice Tutorial");
} else {
amplitude.getInstance().logEvent("Watch Cash Book Tutorial");
}
}
});
}
function closeVideoModal(){
closeModal('modal');
setTimeout(function(){
document.getElementById('video-modal').querySelector('iframe').remove();
}, 150);
}
function showConfirmationModal(responseText){
let modal = document.getElementById("modalConfirmation");
let modalcontainer = modal.children[0];
modal.classList.remove('hidden');
modal.classList.add('animate-fade-animation-in');
jQuery('#modalConfirmation').children().html(responseText);
modalcontainer.classList.add('animate-modal-animation-in');
$('body').addClass('tw-modal-open');
initForm();
hideLoading();
}
function closeModal(targetModal){
if(targetModal != "modalConfirmation"){
unsaved = false;
}
let modal = document.getElementById(targetModal);
let modalcontainer = modal.children[0];
modal.classList.remove('animate-fade-animation-in');
modalcontainer.classList.remove('animate-modal-animation-in');
modal.classList.add('animate-fade-animation-out');
modalcontainer.classList.add('animate-modal-animation-out');
setTimeout(function(){
modal.classList.add('hidden');
modalcontainer.classList.remove('animate-modal-animation-out');
modal.classList.remove('animate-fade-animation-out');
$('body').removeClass('tw-modal-open');
// Clear modal content only — keep .tw-modal-container so showModal() still has modal.children[0]
if (modalcontainer) {
modalcontainer.innerHTML = "";
}
}, 150);
}
function showMessageBox(message){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "showMessageBox",
message: message
}),
success: function(responseText, responseStatus) {
showConfirmationModal(responseText);
}
});
}
function showReloadRequiredBox(){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "showReloadRequiredBox"
}),
success: function(responseText, responseStatus) {
hideLoading();
showConfirmationModal(responseText);
}
});
}
function setTabActive (target){
const tab = document.querySelector(".tw-tab");
const tabList = tab.querySelectorAll("button");
const targetbtn = tabList[target];
tabList.forEach((item) => {
if (item !== targetbtn) {
item.classList.remove("active");
}else{
item.classList.add("active");
}
});
}
function setSubTabActive (target){
const tab = document.querySelector(".tw-subtab");
const tabList = tab.querySelectorAll("button");
const targetbtn = tabList[target];
tabList.forEach((item) => {
if (item !== targetbtn) {
item.classList.remove("active");
}else{
item.classList.add("active");
}
});
}
function setSecSubTabActive (target){
const tab = document.querySelector(".tw-secsubtab");
const tabList = tab.querySelectorAll("button");
const targetbtn = tabList[target];
tabList.forEach((item) => {
if (item !== targetbtn) {
item.classList.remove("active");
}else{
item.classList.add("active");
}
});
}
function setModalSubTabActive (target){
const tab = document.querySelector(".tw-modaltab");
const tabList = tab.querySelectorAll("button");
const targetbtn = tabList[target];
tabList.forEach((item) => {
if (item !== targetbtn) {
item.classList.remove("active");
}else{
item.classList.add("active");
}
});
}
function saveFilter(){
var filterList = document.querySelectorAll('.js-filter-value');
filterList.forEach((filter) => {
sessionStorage.setItem(filter.id,filter.value);
});
if (document.querySelector('.js-btn-togglesearchdiv') !== null){
sessionStorage.setItem("filtertype",document.querySelector('.js-btn-togglesearchdiv').value);
}
}
function setTablePaginationActive(selectedPageNo){
savePaginationFilter('currentpage', selectedPageNo);
const index = selectedPageNo - 1;
const pageNo = document.querySelector(".tw-pagination");
const pageNoList = pageNo.querySelectorAll("span");
const targetPageNo = pageNoList[index];
pageNoList.forEach((item) => {
if (item !== targetPageNo) {
item.classList.remove("active");
}else{
item.classList.add("active");
}
});
}
function getPaginationFilter(enablePage = true){
if (enablePage) {
return {
pageno: sessionStorage.getItem('currentpage'),
pagelimit: sessionStorage.getItem('pagelimit'),
sortby: sessionStorage.getItem('sortby'),
sortorder: sessionStorage.getItem('sortorder'),
}
}
else {
return {
sortby: sessionStorage.getItem('sortby'),
sortorder: sessionStorage.getItem('sortorder'),
}
}
}
function savePaginationFilter(filter, value){
switch(filter) {
case 'currentpage':
sessionStorage.setItem('currentpage', value);
break;
case 'sortby':
sessionStorage.setItem('currentpage', 1);
let lastSortBy = sessionStorage.getItem('sortby');
// set sortby
sessionStorage.setItem('sortby', value);
// set sortorder (if same column, change sortorder value)
if (lastSortBy == value)
sessionStorage.getItem('sortorder') == 'asc'
? sessionStorage.setItem('sortorder', 'desc')
: sessionStorage.setItem('sortorder', 'asc');
else
sessionStorage.setItem('sortorder', 'asc');
// sessionStorage.setItem('sortorder', 'desc');
break;
}
}
function clearPaginationFilter(defaultsortby, defaultsortorder){
sessionStorage.setItem('currentpage', 1);
sessionStorage.setItem('pagelimit', 100);
sessionStorage.setItem('sortby', defaultsortby ?? '');
sessionStorage.setItem('sortorder', defaultsortorder ?? 'desc');
}
function clearFilter(){
sessionStorage.setItem("searchyear","");
sessionStorage.setItem("searchmonth","");
sessionStorage.setItem("searchday","");
sessionStorage.setItem("searchuser","");
sessionStorage.setItem("searchstatus","");
sessionStorage.setItem("searchledger","");
sessionStorage.setItem("searchcat_id","");
sessionStorage.setItem("searchdate","");
sessionStorage.setItem("filtertype","");
sessionStorage.setItem("datefrom","");
sessionStorage.setItem("dateto","");
sessionStorage.setItem("search","");
sessionStorage.setItem("searchkeyword","");
sessionStorage.setItem("searchtype_id","");
sessionStorage.setItem("searchkeyword2","");
sessionStorage.setItem("searchevent","");
sessionStorage.setItem("searchaction","");
clearPaginationFilter();
}
function updateDayList(searchyear, searchmonth, searchday, allowAll = true) {
var year = isNaN(searchyear) ? document.getElementById(searchyear).value : searchyear;
var month = isNaN(searchmonth) ? document.getElementById(searchmonth).value : searchmonth;
// Store original value before updating
var originalValue = document.getElementById(searchday).value;
if (year && month) {
var numberofday = new Date(year, month, 0).getDate();
var content = allowAll ? [""] : [];
for (var i = 1; i <= numberofday; i++) {
var day = i.toString().padStart(2, '0');
content.push("");
}
document.getElementById(searchday).innerHTML = content.join('');
// Restore original value if it's within the new range
if (originalValue && parseInt(originalValue) <= numberofday) {
document.getElementById(searchday).value = originalValue;
}
}
else if (year && !month) {
var content = [""];
document.getElementById(searchday).innerHTML = content.join('');
}
}
function showInput(toggleField,targetAdd, scroll = true){
var toggleElement = document.getElementById(toggleField);
var targetElement = document.getElementById(targetAdd);
if (targetElement.classList.contains('hidden')) {
toggleElement.classList.add('hidden');
targetElement.classList.remove('hidden');
if(scroll){
targetElement.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
}
} else {
toggleElement.classList.remove('hidden');
targetElement.classList.add('hidden');
}
}
function hideInput(targetId){
document.getElementById(targetId).classList.add('hidden');
}
function isValidDate(date) {
return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
function previewLogoImage(targetElement) {
var validtype = validateFileType(targetElement.files[0].type);
if(validtype == "image"){
var container = targetElement.parentElement.parentElement.previousElementSibling;
var containerUpload = container.nextElementSibling;
var image = container.children[1].children[0];
image.src = URL.createObjectURL(targetElement.files[0]);
container.classList.remove("hidden");
containerUpload.classList.add("hidden");
}else{
showAlert("fail&" + jslang["pleaseuploadimagefile"]);
targetElement.value = "";
}
};
function closePreviewLogoImage(event) {
var container = event.target.parentElement.parentElement;
var containerUpload = container.nextElementSibling;
var image = container.children[1].children[0];
image.src = "";
containerUpload.querySelector('.js-file-upload').value='';
container.classList.add("hidden");
containerUpload.classList.remove("hidden");
if(containerUpload.querySelector('.js-have-logo')){
containerUpload.querySelector('.js-have-logo').value='no';
}
};
function previewImageUpload(targetElement){
if(targetElement.files.length > 0){
var validtype = validateFileType(targetElement.files[0].type);
var src = URL.createObjectURL(targetElement.files[0]);
var preview = document.querySelector(".tw-iframe");
if(validtype == "image"){
preview.innerHTML = "";
let element = document.createElement("img");
element.src = src;
preview.appendChild(element);
}else{
showAlert("fail&" + jslang["pleaseuploadimagefile"]);
targetElement.value = "";
preview.innerHTML = "";
}
}
}
function previewFileUpload(targetElement){
if(targetElement.files.length > 0){
var validtype = validateFileType(targetElement.files[0].type);
var src = URL.createObjectURL(targetElement.files[0]);
var preview = document.querySelector(".tw-iframe");
if(validtype == "pdf"){
preview.innerHTML = "";
let element = document.createElement("iframe");
element.src = src;
preview.appendChild(element);
}else if(validtype == "image"){
preview.innerHTML = "";
let element = document.createElement("img");
element.src = src;
preview.appendChild(element);
}else{
showAlert("fail&" + jslang["pleaseuploadvalidfile"]);
targetElement.value = "";
preview.innerHTML = "";
}
var label = preview.previousElementSibling;
var view = label.querySelector('a');
if (view) {
view.parentNode.removeChild(view);
}
}
}
function clearFileUpload(targetId){
document.getElementById(targetId).value = null;
}
function validateFileType(imagetype){
var type = imagetype.split("/");
var acceptedimagetype = ["png","jpg","jpeg"];
var match = acceptedimagetype.find(element => {return element == type[1]});
if(match != null){
return "image";
}else if(type[1] == "pdf"){
return "pdf";
}else if(type[1] == "csv"){
return "excel";
}else{
return false;
}
}
function openDialog(url){
window.open(url, "_blank", "top=100, left=200,height=500, width=800, titlebar=0, menubar=0, location=0, status=0, toolbar=0, scrollbars=1");
if (typeof DialogChannel !== 'undefined') {
DialogChannel.postMessage(url); // Send the URL to Flutter
}
}
function downloadExcel(responseText){
responseText = responseText.replace(/^\s+|\s+$/g, '');
var arr = responseText.split("&");
if(arr[0] == "success"){
window.open(arr[1],"_self");
}else if(arr[0] == "fail"){
showAlert("fail&" + jslang["failtoexport"]);
}
}
function login(){
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "login",
username: jQuery('#username').val(),
password: jQuery('#password').val()
}),
success: function(responseText, responseStatus) {
if(responseText.trim()=='200'){
window.location = weburl;
}else if(responseText=='userexpire'){
showAlert("fail&" + jslang["userexpiredorsuspend"]);
}else{
showAlert("fail&" + jslang["loginfail"]);
}
hideLoading();
}
});
}
function logout(){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "logout"
}),
success: function(responseText, responseStatus) {
localStorage.clear();
window.location = loginurl;
}
});
}
function verifyLogin(){
var username = "";
if(document.getElementById('jsloginusername')){
username = document.getElementById('jsloginusername').value;
}
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "verifyLogin",
username: username
}),
success: function(responseText, responseStatus) {
let returnJson;
try {
returnJson = JSON.parse(responseText);
if (returnJson.status !== "success") {
alert("Your session is expired\nYour current IP address: " + returnJson.data.currentip + "\nLast Login IP address: " + returnJson.data.lastip);
clearInterval(intervalId1);
clearInterval(intervalId2);
window.location = loginurl;
}
} catch (e) {
alert(jslang["sessionexpired"]);
clearInterval(intervalId1);
clearInterval(intervalId2);
window.location = loginurl;
}
}
});
}
function validateSession(){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "validateSession"
}),
success: function(responseText, responseStatus) {
}
});
}
function sanitizeFormInput(form){
var inputList = form.querySelectorAll('input')
var textareaList = form.querySelectorAll('textarea');
inputList.forEach((input) => {
if(input.type != "file" && !input.classList.contains('hidden') && !input.classList.contains('!hidden')){
input.value = sanitizeString(input.value);
}
});
textareaList.forEach((textarea) => {
textarea.value = sanitizeString(textarea.value);
});
}
function sanitizeString(str){
//str = str.replace(/[^a-z0-9áéíóúñü \'.,_\n-]/gim,"");
//str = str.replace(/[<>*()?']/g, "\\$&");
return str.trim();
}
function initForm(){
//var $select2 = $('.tw-select2').select2();
$('form').submit(false);
}
//Check for unsaved changes
//Parameter Explanation
// 1. mycallback = the whole function with parameter, that you want to proceed after the user want to leave the page
function unloadForm(mycallback){
if(unsaved){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "unloadForm",
mycallback: mycallback
}),
success: function(responseText, responseStatus) {
showConfirmationModal(responseText);
}
});
}else{
executeMultiCallback(mycallback);
}
}
function executeMultiCallback(mycallback){
mycallback = mycallback.split(';');
mycallback.pop();
mycallback.forEach(function(func){
var name = func.substring(0, func.indexOf('('));
var param = func.substring(func.indexOf('('));
var paramtextonly = param.replace(/[()]/g, "");
paramtextonly = paramtextonly.replace(/'/g, "");
if(paramtextonly == "" || param == "''"){
window[name]();
}else{
window[name](paramtextonly);
}
});
}
function showLoading(){
if($('#tw-loader').hasClass('hidden')){
$('#tw-loader .tw-bg-loader').addClass('animate-loader-fade-animation-in');
$('#tw-loader').removeClass('hidden');
}
}
function hideLoading(){
if(!$('#tw-loader').hasClass('hidden')){
$('#tw-loader .tw-bg-loader').removeClass('animate-loader-fade-animation-in');
$('#tw-loader .tw-bg-loader').addClass("animate-loader-fade-animation-out");
setTimeout(function(){
$('#tw-loader').addClass("hidden")
$('#tw-loader .tw-bg-loader').removeClass("animate-loader-fade-animation-out");
}, 150);
}
}
function showBlocker(){
if($('#tw-blocker').hasClass('hidden')){
$('#tw-blocker').removeClass('hidden');
}
}
function hideBlocker(){
if(!$('#tw-blocker').hasClass('hidden')){
$('#tw-blocker').addClass("hidden")
}
}
function addSpinAnimation(targetElement){
targetElement.classList.add('animate-spin');
}
function removeSpinAnimation(targetElement){
targetElement.classList.remove('animate-spin');
}
function setFileName(targetElement, type) {
var validtype = validateFileType(targetElement.files[0].type);
if((type == "attachment" && (validtype == "image" || validtype == "pdf")) || validtype == type){
targetElement.previousElementSibling.value = targetElement.files[0].name;
}
else{
switch(type){
case "image":
showAlert("fail&" + jslang["pleaseuploadimagefile"]);
break;
case "attachment":
showAlert("fail&" + jslang["pleaseuploadvalidfile"]);
break;
case "excel":
showAlert("fail&" + jslang["pleaseuploadcsvfile"]);
break;
}
targetElement.value = "";
}
};
function showFileSelection(targetElement){
targetElement.querySelector('.js-file-upload').click();
}
function deleteAttachment(element, targetElement){
var label = element.parentElement.previousElementSibling;
var view = label.querySelector('a');
if (view) {
view.parentNode.removeChild(view);
}
targetElement.querySelector('.js-file-upload').previousElementSibling.value = "";
targetElement.querySelector('.js-file-upload').value = "";
if(targetElement.querySelector('input[name="previousfile"]')){
targetElement.querySelector('input[name="previousfile"]').value = "";
}
if(targetElement.querySelector('input[name="previousthumbfile"]')){
targetElement.querySelector('input[name="previousthumbfile"]').value = "";
}
element.parentElement.innerHTML = "";
}
function previewFileInIframe(targetElement){
if(targetElement.files.length > 0){
var validtype = validateFileType(targetElement.files[0].type);
if(validtype == "pdf" || validtype == "image"){
// Show all attachments (existing + new)
showAllAttachmentsInIframe();
// Update attachment icons
updateAllAttachmentIcons();
}else{
showAlert("fail&" + jslang["pleaseuploadvalidfile"]);
targetElement.value = "";
var previewContainer = document.getElementById('js-iframe');
if(previewContainer){
previewContainer.innerHTML = "";
}
}
}
}
// Function to show all attachments (existing + newly uploaded)
function showAllAttachmentsInIframe(){
var previewContainer = document.getElementById('js-iframe');
if(!previewContainer) return;
previewContainer.innerHTML = '';
// Set container to allow inline-block children to flow horizontally
previewContainer.classList.add('tw-attachment-container');
var rows = document.querySelectorAll('#multi-ledger-entries-table tbody tr');
var hasAttachments = false;
rows.forEach(function(row, index){
var fileInput = row.querySelector('.js-file-upload');
var previousFileInput = row.querySelector('input[name="previousfile[]"]');
var hasNewFile = fileInput && fileInput.files && fileInput.files.length > 0;
var hasExistingFile = previousFileInput && previousFileInput.value && previousFileInput.value.trim() !== '';
if(hasNewFile || hasExistingFile){
hasAttachments = true;
// Detect file type first
var fileType = null;
var fileUrl = null;
if(hasNewFile){
fileType = validateFileType(fileInput.files[0].type);
} else if(hasExistingFile){
fileUrl = previousFileInput.value;
if(fileUrl.match(/\.(jpg|jpeg|png|gif)$/i)){
fileType = "image";
} else if(fileUrl.match(/\.pdf$/i)){
fileType = "pdf";
}
}
// Create preview container
var rowContainer = document.createElement('div');
rowContainer.className = 'attachment-item';
// Set container style based on file type
if(fileType == "pdf"){
rowContainer.classList.add('pdf');
} else {
rowContainer.classList.add('image');
}
var previewElement = document.createElement('div');
previewElement.className = 'tw-iframe';
// Add close button
var closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.className = 'tw-close absolute right-0 text-gray-400 hover:text-gray-500';
closeButton.onclick = function() {
deleteAttachmentInIframe(this);
};
previewElement.appendChild(closeButton);
// Create preview based on file type
if(hasNewFile){
createPreviewFromFile(fileInput.files[0], previewElement, rowContainer);
} else if(hasExistingFile){
createPreviewFromUrl(previousFileInput.value, previewElement, rowContainer);
}
rowContainer.appendChild(previewElement);
previewContainer.appendChild(rowContainer);
}
});
if(!hasAttachments){
previewContainer.innerHTML = '';
previewContainer.classList.remove('tw-attachment-container');
}
}
// Function to show existing attachments in edit mode
function showExistingAttachmentsInIframe(){
showAllAttachmentsInIframe();
// Update attachment icons
updateAllAttachmentIcons();
}
// Helper function to create preview from file object
function createPreviewFromFile(file, container, rowContainer){
var validtype = validateFileType(file.type);
var src = URL.createObjectURL(file);
if(validtype == "image"){
var img = document.createElement('img');
img.src = src;
// Detect image orientation after load and set container width
img.onload = function(){
var isPortrait = img.naturalHeight > img.naturalWidth;
if(rowContainer){
// Remove existing width classes
rowContainer.classList.remove('portrait', 'landscape');
if(isPortrait){
rowContainer.classList.add('portrait');
} else {
rowContainer.classList.add('landscape');
}
}
};
container.appendChild(img);
} else if(validtype == "pdf"){
container.classList.add('tw-iframe-pdf');
var iframe = document.createElement('iframe');
iframe.src = src;
container.appendChild(iframe);
}
}
// Helper function to create preview from URL
function createPreviewFromUrl(fileUrl, container, rowContainer){
if(fileUrl.match(/\.(jpg|jpeg|png|gif)$/i)){
var img = document.createElement('img');
img.src = fileUrl;
// Detect image orientation after load and set container width
img.onload = function(){
var isPortrait = img.naturalHeight > img.naturalWidth;
if(rowContainer){
// Remove existing width classes
rowContainer.classList.remove('portrait', 'landscape');
if(isPortrait){
rowContainer.classList.add('portrait');
} else {
rowContainer.classList.add('landscape');
}
}
};
container.appendChild(img);
} else if(fileUrl.match(/\.pdf$/i)){
container.classList.add('tw-iframe-pdf');
var iframe = document.createElement('iframe');
iframe.src = fileUrl;
container.appendChild(iframe);
}
}
function deleteAttachmentInIframe(element){
var previewElement = element.closest('.tw-iframe');
if(!previewElement) {
showAlert("warning&No preview element found");
return;
}
var rowContainer = previewElement.parentElement;
if(!rowContainer) {
showAlert("warning&No row container found");
return;
}
var previewContainer = document.getElementById('js-iframe');
var attachmentContainers = previewContainer.querySelectorAll('.attachment-item');
var containerIndex = Array.from(attachmentContainers).indexOf(rowContainer);
if(containerIndex === -1) {
showAlert("warning&Could not find attachment index");
return;
}
var rows = document.querySelectorAll('#multi-ledger-entries-table tbody tr');
var attachmentRows = [];
rows.forEach(function(row){
var fileInput = row.querySelector('.js-file-upload');
var previousFileInput = row.querySelector('input[name="previousfile[]"]');
var hasNewFile = fileInput && fileInput.files && fileInput.files.length > 0;
var hasExistingFile = previousFileInput && previousFileInput.value && previousFileInput.value.trim() !== '';
if(hasNewFile || hasExistingFile){
attachmentRows.push(row);
}
});
var targetRow = attachmentRows[containerIndex];
if(!targetRow) {
showAlert("warning&Could not find target row");
return;
}
var fileInput = targetRow.querySelector('.js-file-upload');
var previousFileInput = targetRow.querySelector('input[name="previousfile[]"]');
if(fileInput){
fileInput.value = "";
if(fileInput.previousElementSibling){
fileInput.previousElementSibling.value = "";
}
}
if(previousFileInput){
previousFileInput.value = "";
}
showAllAttachmentsInIframe();
updateAllAttachmentIcons();
}
function previewAttachmentInWindow(element){
var attachmentData = getAttachmentData(element);
if(attachmentData.hasAttachment){
var fileType = getFileType(attachmentData);
openAttachmentPreview(attachmentData.attachmentUrl, fileType);
} else {
showAlert("info&No attachment found");
}
}
// Helper function to get attachment data from a table row
function getAttachmentData(element){
var row = element.closest('tr');
var fileInput = row ? row.querySelector('.js-file-upload') : null;
var previousFileInput = row ? row.querySelector('input[name="previousfile[]"]') : null;
var hasNewFile = fileInput && fileInput.files && fileInput.files.length > 0;
var hasExistingFile = previousFileInput && previousFileInput.value && previousFileInput.value.trim() !== '';
return {
fileInput: fileInput,
previousFileInput: previousFileInput,
hasAttachment: hasNewFile || hasExistingFile,
attachmentUrl: hasNewFile ? URL.createObjectURL(fileInput.files[0]) : (hasExistingFile ? previousFileInput.value : "")
};
}
// Helper function to determine file type
function getFileType(attachmentData){
if(attachmentData.fileInput && attachmentData.fileInput.files && attachmentData.fileInput.files.length > 0){
// For new uploads, use MIME type
var mimeType = attachmentData.fileInput.files[0].type;
if(mimeType.startsWith('image/')) return "image";
if(mimeType === 'application/pdf') return "pdf";
return "other";
} else {
// For existing files, use URL-based detection
return validateFileTypeFromUrl(attachmentData.attachmentUrl);
}
}
// Helper function to open attachment preview in new window
function openAttachmentPreview(url, fileType){
if(fileType === "image"){
openImagePreview(url);
} else if(fileType === "pdf"){
window.open(url, '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
} else {
openDownloadPreview(url);
}
}
// Helper function to open image preview
function openImagePreview(url){
var newWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
newWindow.document.write(`
Image Preview
`);
newWindow.document.close();
}
// Helper function to open download preview
function openDownloadPreview(url){
var newWindow = window.open('', '_blank', 'width=400,height=200,scrollbars=yes,resizable=yes');
newWindow.document.write(`
File Preview