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');
}, 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 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","");
}
function updateDayList(searchyear, searchmonth, searchday, allowNull = true) {
var year = isNaN(searchyear) ? document.getElementById(searchyear).value : searchyear;
var month = isNaN(searchmonth) ? document.getElementById(searchmonth).value : searchmonth;
if (year && month) {
var numberofday = new Date(year, month, 0).getDate();
var content = allowNull ? [""] : [];
for (var i = 1; i <= numberofday; i++) {
var day = i.toString().padStart(2, '0');
content.push("");
}
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 setStepperActive(targetSwitch){
if(targetSwitch == 'js-match'){
document.querySelectorAll('.js-match').forEach((step) => {
step.classList.add("active");
});
document.querySelectorAll('.js-import').forEach((step) => {
step.classList.remove("active");
});
}else if(targetSwitch == 'js-import'){
document.querySelectorAll('.js-match').forEach((step) => {
step.classList.add("active");
});
document.querySelectorAll('.js-import').forEach((step) => {
step.classList.add("active");
});
}else{
document.querySelectorAll('.js-match').forEach((step) => {
step.classList.remove("active");
});
document.querySelectorAll('.js-import').forEach((step) => {
step.classList.remove("active");
});
}
}
function copyToClipboard(targetId,tooltipId = ''){
var copyText = document.getElementById(targetId);
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
if(document.getElementById(tooltipId)){
var tooltip = document.getElementById(tooltipId);
tooltip.innerHTML = "Copied";
}else{
showAlert('success&Copied to Clipboard');
}
}
function resetTooltip(tooltipId){
var tooltip = document.getElementById(tooltipId);
tooltip.innerHTML = "Copy to your clipboard";
}
function addClassByValue(element, verifyValue, className){
if(element.value == verifyValue || element.value == ""){
element.classList.add(className);
}
}
function sendWhatsapp(type,id){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "sendWhatsapp",
type: type,
id: id
}),
success: function(responseText, responseStatus) {
window.open(responseText, "_blank");
if (typeof DialogChannel !== 'undefined') {
DialogChannel.postMessage(responseText); // Send the URL to Flutter
}
}
});
}
function exportExcel(type, id = "", id2 = ""){
var filtertype = "date";
if(document.querySelector('.js-btn-togglesearchdiv')){
filtertype = document.querySelector('.js-btn-togglesearchdiv').value;
}
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "exportExcel",
type: type,
id: id,
id2: id2,
filtertype: filtertype,
searchstatus: jQuery('#searchstatus').val(),
searchkeyword: jQuery('#SearchBox').val(),
searchuser: jQuery('#searchuser').val(),
searchyear: jQuery('#searchyear').val(),
searchmonth: jQuery('#searchmonth').val(),
searchday: jQuery('#searchday').val(),
searchsource: jQuery('#searchsource').val(),
searchcat_id: jQuery('#searchcat_id').val(),
searchtype_id: jQuery('#searchtype_id').val(),
searchtrantype: jQuery('#searchtrantype').val(),
searchledgertype: jQuery('#searchledgertype').val(),
searchledger: jQuery('#searchledger').val(),
datefrom: jQuery('#datefrom').val(),
dateto: jQuery('#dateto').val(),
searchdate: jQuery('#searchdate').val()
}),
success: function(responseText, responseStatus) {
hideLoading();
console.log(responseText);
var arr = responseText.split("&&&&");
if(arr[0] == "success"){
arr.shift();
window.open(arr.join('&'),"_self");
}else if(arr[0] == "fail"){
showAlert("fail&" + jslang["failtoexport"]);
}
}
});
}
function printPDF(type, keyid = ""){
var filtertype = "date";
if(document.querySelector('.js-btn-togglesearchdiv')){
filtertype = document.querySelector('.js-btn-togglesearchdiv').value;
}
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "printPDF",
type: type,
keyid: keyid,
filtertype: filtertype,
searchstatus: jQuery('#searchstatus').val(),
searchuser: jQuery('#searchuser').val(),
searchyear: jQuery('#searchyear').val(),
searchmonth: jQuery('#searchmonth').val(),
searchday: jQuery('#searchday').val(),
searchsource: jQuery('#searchsource').val(),
searchcat_id: jQuery('#searchcat_id').val(),
searchtype_id: jQuery('#searchtype_id').val(),
searchtrantype: jQuery('#searchtrantype').val(),
searchledgertype: jQuery('#searchledgertype').val(),
searchledger: jQuery('#searchledger').val(),
searchkeyword: jQuery('#searchkeyword').val(),
datefrom: jQuery('#datefrom').val(),
dateto: jQuery('#dateto').val(),
searchdate: jQuery('#searchdate').val()
}),
success: function(responseText, responseStatus) {
hideLoading();
console.log(responseText);
var arr = responseText.split("&&&&");
if(arr[0] == "success"){
arr.shift();
openDialog(arr.join('&'));
}else if(arr[0] == "fail"){
showAlert("fail&" + jslang["failtoexport"]);
}
}
});
}
function forceShowTips(targetAdd) {
var targetElement = document.getElementById(targetAdd);
targetElement.classList.toggle('hidden');
targetElement.classList.toggle('!block');
targetElement.classList.toggle('!visible');
targetElement.classList.toggle('!opacity-100');
}
function closeShowTip(id, save = true){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "closeShowTip",
id: id,
save: save,
}),
success: function(responseText, responseStatus) {
;
}
});
}
function closeSessionShowTip(id){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "closeSessionShowTip",
id: id
}),
success: function(responseText, responseStatus) {
;
}
});
}
function initToggleAllCheckBox(){
var triggerElement = document.querySelector('.js-checkallbox');
var checkboxList = document.querySelectorAll('.js-checkbox');
checkboxList.forEach((checkbox) => {
checkbox.addEventListener('change', function () {
var isAnyUnchecked = Array.from(checkboxList).some((box) => !box.checked);
if(!isAnyUnchecked){
triggerElement.checked = true;
}else{
triggerElement.checked = false;
}
});
});
}
function toggleAllCheckBox(triggerElement, clear = false){
if(clear){
triggerElement.checked = false;
var checkboxList = document.querySelectorAll('.js-checkbox');
checkboxList.forEach((checkbox) => {
if(checkbox.checked){
checkbox.click();
}
});
}else{
var isChecked = triggerElement.checked;
var checkboxList = document.querySelectorAll('.js-checkbox');
if(isChecked){
checkboxList.forEach((checkbox) => {
if(!checkbox.checked){
checkbox.click();
}
});
}else{
checkboxList.forEach((checkbox) => {
if(checkbox.checked){
checkbox.click();
}
});
}
}
}
function handleDragOver(event) {
event.preventDefault();
}
function handleDrop(event,fileInput) {
event.preventDefault();
const files = event.dataTransfer.files;
moveFilesToInput(files,fileInput);
}
function moveFilesToInput(files,fileInput) {
fileInput.files = files;
const event = new Event('change', { bubbles: true });
fileInput.dispatchEvent(event)
}
function downgradeModal(){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "downgradeModal"
}),
success: function(responseText, responseStatus) {
showConfirmationModal(responseText);
}
});
}
function downgrade(){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "downgrade"
}),
success: function(responseText, responseStatus) {
window.open(responseText,"_self");
}
});
}
function updateDateNow(triggerElement, triggerCondition,targetElement){
if(document.getElementById(triggerElement).value == triggerCondition && (document.getElementById(targetElement).value == "" || document.getElementById(targetElement).value == "0000-00-00")){
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // Month is zero-based
const day = String(today.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
document.getElementById(targetElement).value = formattedDate;
document.getElementById(targetElement).classList.remove('text-transparent');
}
}
function checkJsonString(json){
try {
return jsonObject = JSON.parse(json.replace(/'/g, '"'));
} catch (error) {
return jsonObject = json;
}
}
function handleRedirect(subfunction, subparam, defaultFunc, defaultParam = ""){
if(subfunction != null){
if(subparam != null){
const arrayData = checkJsonString(subparam)
if(typeof(arrayData) == "object"){
switch(arrayData.length){
case 1:
window[subfunction](arrayData[0]);
break;
case 2:
window[subfunction](arrayData[0],arrayData[1]);
break;
case 3:
window[subfunction](arrayData[0],arrayData[1],arrayData[2]);
break;
case 4:
window[subfunction](arrayData[0],arrayData[1],arrayData[2],arrayData[3]);
break;
}
}else{
window[subfunction](subparam);
}
}else{
window[subfunction]();
}
}else{
if(defaultParam != ""){
window[defaultFunc](defaultParam);
}else{
window[defaultFunc]();
}
}
}
// Custom rounding function
function roundToDecimal(num, decimalPlaces) {
const factor = Math.pow(10, decimalPlaces);
return Math.round(num * factor + 0.0000001) / factor;
}
// Function to format unit numbers
function sysUnitNumberFormat(value = "") {
const parsedValue = parseFloat(value);
return isNaN(parsedValue) ? roundToDecimal(0, jsunitdecimal) : roundToDecimal(parsedValue, jsunitdecimal);
}
// Function to format general numbers
function sysNumberFormat(value = "") {
const parsedValue = parseFloat(value);
return isNaN(parsedValue) ? roundToDecimal(0, jspricedecimal) : roundToDecimal(parsedValue, jspricedecimal);
}
// Function to format prices as a string
function sysPriceFormat(value = "") {
const parsedValue = parseFloat(value);
const roundedValue = isNaN(parsedValue) ? roundToDecimal(0, jspricedecimal) : roundToDecimal(parsedValue, jspricedecimal);
return roundedValue.toFixed(jspricedecimal);
}
// Function to format units as a string
function sysUnitFormat(value = "") {
const parsedValue = parseFloat(value);
const roundedValue = isNaN(parsedValue) ? roundToDecimal(0, jsunitdecimal) : roundToDecimal(parsedValue, jsunitdecimal);
return roundedValue.toFixed(jsunitdecimal);
}
function switchDateRangeByYear(targetElement, add){
let datefrom = targetElement.querySelector('#datefrom');
let dateto = targetElement.querySelector('#dateto');
let start = new Date(datefrom.value);
let end = new Date(dateto.value);
if(add){
start.setFullYear(start.getFullYear() + 1);
end.setFullYear(end.getFullYear() + 1);
}else{
start.setFullYear(start.getFullYear() - 1);
end.setFullYear(end.getFullYear() - 1);
}
datefrom.value = formatDate(start);
dateto.value = formatDate(end);
}
function switchDateRangeByMonth(targetElement, add){
let datefrom = targetElement.querySelector('#datefrom');
let dateto = targetElement.querySelector('#dateto');
let dateParts = datefrom.value.split("/");
let year = parseInt(dateParts[0], 10);
let month = parseInt(dateParts[1], 10);
if(add){
if(month == 12){
year += 1;
month = 1;
}else{
month += 1;
}
}else{
if(month == 1){
year -= 1;
month = 12;
}else{
month -= 1;
}
}
let start = new Date(year, month - 1, 1);
let end = new Date(year, month, 0);
datefrom.value = formatDate(start);
dateto.value = formatDate(end);
}
function formatDate(date) {
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
return `${year}/${month}/${day}`;
}
function checkAccess(menuid,functionName,modal = null){
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "checkAccess",
menuid: menuid
}),
success: function(responseText, responseStatus) {
if(responseText != "error"){
const func = new Function(functionName);
func();
if(modal != null){
closeModal('modal');
}
}else{
showAlert("fail&" + jslang["unabletoaccess"]);
hideLoading();
}
}
});
}
function handleFormKeyDown(event) {
// Check if the pressed key is Enter and the active element is not a textarea
if (event.key === 'Enter' && event.target.nodeName !== 'TEXTAREA') {
event.preventDefault(); // Prevent form submission
return false;
}
return true; // Allow default behavior for other keys or when inside textarea
}
function filterPhone(element) {
var phone = element.value;
phone = phone.replace(/[^0-9\-]/g, '');
phone = phone.replace(/[\s\-+]/g, '');
if (phone.startsWith('0') && phone !== '') {
phone = '6' + phone;
}
element.value = phone;
}
function toggleTextfield(show, elementId) {
var element = document.getElementById(elementId);
if (element) {
if (show) {
element.classList.remove('!hidden');
} else {
element.classList.add('!hidden');
}
}
}
function getScrollY() {
var height = window.innerHeight;
var width = window.innerWidth;
if (width > 750) {
if (height < 700) {
return '43vh';
} else {
return '48vh';
}
} else if (height < 600) {
return '23vh';
} else if (height < 700) {
return '27vh';
} else if (height < 800) {
return '33vh';
} else if (height < 900) {
return '38vh';
} else if (height < 1000) {
return '43vh';
} else {
return '48vh';
}
}
function copyLinkModal(type, id, modal = "modal"){
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "copyLinkModal",
id: id,
type: type,
modal: modal,
}),
success: function(responseText, responseStatus) {
if(modal == "modal"){
showModal(responseText);
}else if(modal == "modalConfirmation"){
showConfirmationModal(responseText);
}
}
});
}
function printDocument(type, id){
hideLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "printDocument",
id: id,
type: type
}),
success: function(responseText, responseStatus) {
openDialog(responseText);
}
});
}
function showWSSupportModal(supportphone){
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "showWSSupportModal",
supportphone: supportphone
}),
success: function(responseText, responseStatus) {
showConfirmationModal(responseText);
}
});
}
function WSSupport(supportphone){
showLoading();
jQuery.ajax({
type: "POST", dataType: "html",
url: webpath + "ajax/common/common.php",
data: ({
pageaction: "WSSupport",
supportphone: supportphone
}),
success: function(responseText, responseStatus) {
window.open(responseText);
closeModal('modalConfirmation');
hideLoading();
}
});
}