
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();

    $.each(a, function () {
        if (o[this.name] !== undefined) {
            //if (!o[this.name].push) {
            //    o[this.name] = [o[this.name]];
            //}

            //o[this.name].push(this.value || "");
        } else {
            o[this.name] = this.value || "";
        }
    });

    return o;
};

function onlyIntegers(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }

    return true;
}

function pastOnlyIntegers(e, target) {

    var text = e.originalEvent.clipboardData.getData("Text");

    if ($.isNumeric(text)) {
        if ((text.substring(text.indexOf(".")).length > 0) && (text.indexOf(".") > -1)) {
            e.preventDefault();
            $(target).dxTextBox("instance").option("value", text.substring(0, text.indexOf(".")));
        }
    }
    else {
        e.preventDefault();
    }
}

function onlyDecimals(evt) {
    var element = $(evt.target);
    var text = $(element).val();

    if ((evt.which !== 46 || text.indexOf(".") !== -1) && //if the keypress is not a . or there is already a decimal point
        ((evt.which < 48 || evt.which > 57) && //and you try to enter something that isn't a number
            //(evt.which !== 45 || (element[0].selectionStart !== 0 || text.indexOf("-") !== -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
            (evt.which !== 0 && evt.which !== 8))) { //and the keypress is not a backspace or arrow key (in FF)
        return false; //cancel the keypress
    }

    if ((evt.which === 46) && (text.indexOf(".") === -1)) {
        //if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. so you have to cut the extra digits
        setTimeout(function () {
            if (element.val().substring(element.val().indexOf(".")).length > 3) {
                element.val(element.val().substring(0, element.val().indexOf(".") + 3));
            }
        }, 1);
    }

    if ((text.indexOf(".") !== -1) && (text.substring(text.indexOf(".")).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
        ((element[0].selectionStart - element[0].selectionEnd) === 0) && //and no part of the input is selected
        (element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
        //(evt.which !== 45 || (element[0].selectionStart !== 0 || text.indexOf("-") !== -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
        (evt.which !== 0 && evt.which !== 8)) { //and the keypress is not a backspace or arrow key (in FF)
        return false; //cancel the keypress
    }

    return true;
}

function pastOnlyDecimals(e, target) {
    var text = e.originalEvent.clipboardData.getData("Text");

    if ($.isNumeric(text)) {
        if ((text.substring(text.indexOf(".")).length > 3) && (text.indexOf(".") > -1)) {
            e.preventDefault();
            $(target).dxTextBox("instance").option("value", text.substring(0, text.indexOf(".") + 3));
        }
    }
    else {
        e.preventDefault();
    }
}

function convertGregorainToHijriDate(date, successCallBack) {
    if (date) {
        date = date.toISOString();
    }

    $.ajax({
        url: commonControlUrl + "/ConvertGregorainToHijriDate",
        type: "GET",
        data: { 'date': date },
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: successCallBack
    });
}

function convertHijriToGregorainDate(date, successCallBack) {
    $.ajax({
        url: commonControlUrl + "/ConvertHijriToGregorainDate",
        type: "GET",
        data: { 'date': date },
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: successCallBack
    });
}

var myRemoteFlag;




// Show loader when any AJAX request starts
$(document).ajaxStart(function () {
    document.getElementById("modalAjax").style.display = "flex";
    document.getElementById("fadeAjax").style.display = "flex";

    // Optional failsafe timeout (hide after 30s max)
    clearTimeout(window.loaderTimeout);
    window.loaderTimeout = setTimeout(function () {
        document.getElementById("modalAjax").style.display = "none";
        document.getElementById("fadeAjax").style.display = "none";
    }, 30000);
});

// Hide loader when all AJAX requests finish
$(document).ajaxStop(function () {
    document.getElementById("modalAjax").style.display = "none";
    document.getElementById("fadeAjax").style.display = "none";
});

// Hide loader on AJAX error
$(document).ajaxError(function () {
    document.getElementById("modalAjax").style.display = "none";
    document.getElementById("fadeAjax").style.display = "none";
});

// Reusable function for .load() calls
function safeLoad(target, url) {
    // Show loader explicitly
    document.getElementById("modalAjax").style.display = "flex";
    document.getElementById("fadeAjax").style.display = "flex";

    // Load content and hide loader when done or error
    $(target).load(url, function (response, status) {
        document.getElementById("modalAjax").style.display = "none";
        document.getElementById("fadeAjax").style.display = "none";

        if (status === "error") {
            console.error("Failed to load:", url);
        }
    });
}

function SSTPrintDetails(title, selector) {
    var direction = $("body").hasClass("rtl") ? "rtl" : "";

    //var dispSetting = "toolbar=yes,location=no,";
    //dispSetting += "directories=yes,menubar=yes,";
    //dispSetting += "scrollbars=yes,width=700, height=700, left=100, top=25";

    //var docprint = window.open("", "", dispSetting);
    //docprint.document.open();
    //docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');
    //docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
    //docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
    //docprint.document.write("<head>");
    //docprint.document.write('<link rel="stylesheet" href="../../assets/css/bootstrap.min.css" />');
    //docprint.document.write('<link rel="stylesheet" href="../../assets/css/ace-rtl.min.css" />');
    //docprint.document.write('<link rel="stylesheet" href="../../assets/font-awesome/4.5.0/css/font-awesome.min.css" />');
    //docprint.document.write("<title>" + title + "</title>");
    //docprint.document.write('<style type="text/css"></style>');
    //docprint.document.write("</head>");
    //docprint.document.write("<body onLoad='self.print()' class='" + direction + "'>");
    //docprint.document.write(selector);
    //docprint.document.write("</body></html>");
    //docprint.document.close();
    //docprint.focus();

    $(selector).printThis({
        debug: false, // show the iframe for debugging
        importCSS: true, // import parent page css
        importStyle: true, // import style tags
        printContainer: true, // grab outer container as well as the contents of the selector
        loadCSS: "", // path to additional css file - use an array [] for multiple
        pageTitle: title, // add title to print page
        removeInline: false, // remove all inline styles from print elements
        removeInlineSelector: "body *", // custom selectors to filter inline styles. removeInline must be true
        printDelay: 333, // variable print delay
        header: null, // prefix to html
        footer: null, // postfix to html
        base: false, // preserve the BASE tag, or accept a string for the URL
        formValues: true, // preserve input/form values
        canvas: false, // copy canvas elements
        //doctypeString: "", // enter a different doctype for older markup
        removeScripts: false, // remove script tags from print content
        copyTagClasses: false, // copy classes from the html & body tag
        beforePrintEvent: null, // callback function for printEvent in iframe
        beforePrint: null, // function called before iframe is filled
        afterPrint: null, // function called before iframe is removed
        bodyDirection: direction // direction of body tag
    });
}

function getToastrPosition() {
    return $("body").hasClass("rtl") ? "toast-bottom-left" : "toast-bottom-right";;
}

function getToastrOption(timeOut, showDuration) {
    return {
        "showDuration": showDuration,
        "timeOut": timeOut,
        "positionClass": getToastrPosition()
    };
}

function showSuccessMessage(message, title) {
    toastr.success(message, title, getToastrOption("5000", "5000"));
}

function showErrorMessage(message, title) {
    toastr.error(message, title, getToastrOption("15000", "15000"));
}

function showInfoMessage(message, title) {
    toastr.info(message, title, getToastrOption("5000", "5000"));
}

function showWarningMessage(message, title) {
    toastr.warning(message, title, getToastrOption("5000", "5000"));
}

function showWarningMessageSwal(title) {
    //const confirmButtonText = localStorage.getItem("template-Rtl") === "true" ? "نعم" : "OK";
    Swal.fire({
        title: title,
        icon: "warning",
        timer: 10000,
        confirmButtonText: CommonJsKeyRes.OKLabel,
        timerProgressBar: true,
    });
}

function showSuccessMessageSwal(title) {
    //const confirmButtonText = localStorage.getItem("template-Rtl") === "true" ? "نعم" : "OK";
    Swal.fire({
        title: title,
        icon: "success",
        timer: 3000,
        confirmButtonText: CommonJsKeyRes.OKLabel,
        timerProgressBar: true,
    });
}

function showErrorMessageSwal(message) {
  //  const confirmButtonText = localStorage.getItem("template-Rtl") === "true" ? "نعم" : "OK";
    Swal.fire({
        title: message,
        icon: "error",
        timer: 10000,
        confirmButtonText: CommonJsKeyRes.OKLabel,
        timerProgressBar: true,
    });
    toggleSaveButton(false);
}

function disableButtonSave() {
    $('#btnSaveDraft').attr('disabled', 'disabled');
    $('#btnSave').attr('disabled', 'disabled');
}

function enableButtonSave() {
    $('#btnSaveDraft').removeAttr('disabled');
    $('#btnSave').removeAttr('disabled');
}

function showFile(url) {
    window.open(url, "_blank");
}
function OpenRedirectWindowCommon(code, url) {
    window.open(url + '?id=' + code, '_blank');
}

function OpenSaveWindowCommon(code, titleText, url, windowId) {
    
    $.get(url, { 'id': code }, function (data) {
        var window = $("#" + windowId).data("kendoWindow");
        window.title(titleText) ;
        window.content(data);
        window.center();
        window.open();
        var titleBar = $("#" + windowId).closest(".k-window").find(".k-window-title");
        titleBar.html(" <i class='fa fa-window-restore px-1'></i>" + titleText );
    });
}




function OpenSaveWindowCommonWithParams(openData, titleText, url, windowId) {


    $.get(url, openData, function (data) {
        var window = $("#" + windowId).data("kendoWindow");
        window.title(titleText);
        window.content(data);
        window.center();
        window.open();
        var titleBar = $("#" + windowId).closest(".k-window").find(".k-window-title");
        titleBar.html(" <i class='fa fa-window-restore px-1'></i>" + titleText);
    });
}

function CloseSaveWindowCommon(windowId) {
    var window = $("#" + windowId).data("kendoWindow");
    window.close();
}

function SaveWindowCommon(saveFormId, windowId, gridId, isExtraValidationValid = true, fileNamePropertyName = "FileName") {
    debugger
    var form = $("form#" + saveFormId).get(0);
    var validator = $(form).kendoValidator().data("kendoValidator");
    var isValid = validator.validate();
    if (isValid && isExtraValidationValid) {
                var formModel = $(form).serializeObject(); formModel.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
        var filesUpload = $("#files").data("kendoUpload");

        
        if (filesUpload) {
            var files = filesUpload.getFiles();
            if (files.length > 0) {
                formModel[fileNamePropertyName] = files[0].name;
            }
        }
       
        var sPostData = JSON.stringify(formModel);
        $.ajax({
            url: form.action,
            type: "POST",
            data: sPostData,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) { OnSaveActionDone(data, windowId, gridId); }
        });
    }
}

function OnSaveActionDone(data, windowId, gridId) {
    if (data.Success) {
        CloseSaveWindowCommon(windowId);
        var grid = $("#" + gridId).data("kendoGrid");
        grid.dataSource.read();
        showSuccessMessageSwal(data.Message);
    } else {
        showErrorMessageSwal(data.Message);
    }
}


function DeleteCommonVuexy(id, windowTitle, windowsMessage, isRTL, url, gridId) {
    var sPostData = { id: id };
    ConfirmActionMultiParamsSwal(sPostData, windowTitle, windowsMessage, isRTL, url, gridId);
}

function OpenReportCrystalWindowCommon(parameters, reportName = "JournalEntry", reportArea = "GenerlLedger") {
    var selectionFormula = "?ReportName=" + reportName + ".rpt&SelectionFormula=" + parameters;
    selectionFormula = selectionFormula + "&ReportArea=" + reportArea;
    var src = crystalReportViewerUrl + selectionFormula;
    window.open(src, "_blank", "left=200,top=235,width=1000,height=700,scrollbars=auto");
}

function OpenCommonEncryptUrl(id, areaName, controllerName, actionName) {
    var dictParam = {
        id: id,
    };

    $.ajax({
        url: commonControlUrl + "/EncryptUrl",
        type: "POST",
        data: {
            dictParam: dictParam,
            controllerName: controllerName,
            area: areaName,
            actionName: actionName
        },
        "success": function (data) {
            window.location.href = data.Url;
        }
    });
}


function OpenRedirectWindowCommonMultiParams(params, url, newTabblank) { 
    if (typeof params === 'object' && params !== null) {
        const queryString = Object.entries(params)
            .map(entry => `${encodeURIComponent(entry[0])}=${encodeURIComponent(entry[1])}`)
            .join('&');

        const fullUrl = url + '?' + queryString;

        if (newTabblank === "True") {
            window.open(fullUrl, '_blank');
        } else {
            window.location.href = fullUrl;
        }
    }
}

function OpenCommonEncryptUrlMultiParams(params, areaName, controllerName, actionName, newTabblank) {
    
    // Check if params is an object and not null
    if (typeof params === 'object' && params !== null) {
        // Convert the params object to a query string
        const queryString = Object.entries(params)
            .map(function (entry) {
                return `${encodeURIComponent(entry[0])}=${encodeURIComponent(entry[1])}`;
            })
            .join('&');

        $.ajax({
            url: commonControlUrl + "/EncryptUrl",
            type: "POST",
            data: {
                dictParam: params, 
                controllerName: controllerName,
                area: areaName,
                actionName: actionName
            },
            success: function (data) {
                if (newTabblank === "True") {
                    window.open(data.Url, '_blank');
                } else {
                    window.location.href = data.Url;
                }
            },
            error: function (xhr, status, error) {
                
                showErrorMessageSwal("Error with the AJAX request:", error);

            }
        });
    } else {
        showErrorMessageSwal("Invalid parameters passed to OpenCommonEncryptUrlMultiParams.");
    }
   
}

function ConfirmActionSwal(id, windowTitle, windowsMessage, isRTL, url, gridId) {
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-danger",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    const confirmButtonText = CommonJsKeyRes.DeleteLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, { id: id }, function (data) {
                if (data.Success) {
                    var grid = $("#" + gridId).data("kendoGrid");
                    grid.dataSource.read();
                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: CommonJsKeyRes.MsgError,
                        text: data.Message,
                        icon: "error",
                        confirmButtonText: okButtonText, 
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-danger',
                        },
                    });
                }
            });
        }
    });
}

function ConfirmSaveChangesActionSwal(windowTitle, windowsMessage, isRTL, confirmFunction, refuseFunction) {
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-danger",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });
    
    const confirmButtonText = CommonJsKeyRes.DeleteLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            confirmFunction();
        } else {
            refuseFunction();
        }
    });
}

function ConfirmActionMultiParamsSwal(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    // Set button text based on the isRTL flag
    const confirmButtonText = CommonJsKeyRes.YesLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    
    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    // دعم قائمة أو قيمة مفردة لـ gridId
                    if (Array.isArray(gridId)) {
                        gridId.forEach(function (id) {
                            const grid = $("#" + id).data("kendoGrid");
                            if (grid) {
                                grid.dataSource.read();
                            }
                        });
                    } else {
                        const grid = $("#" + gridId).data("kendoGrid");
                        if (grid) {
                            grid.dataSource.read();
                        }
                    }

                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Error!",
                        text: data.Message,
                        icon: "error"
                    });
                }
            });
        }
    });
}
function ConfirmActionMultiParamsSwalListView(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    // Set button text based on the isRTL flag
    const confirmButtonText = CommonJsKeyRes.YesLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    // دعم قائمة أو قيمة مفردة لـ gridId
                    if (Array.isArray(gridId)) {
                        gridId.forEach(function (id) {
                            const grid = $("#" + id).data("kendoListView");
                            if (grid) {
                                grid.dataSource.read();
                            }
                        });
                    } else {
                        const grid = $("#" + gridId).data("kendoListView");
                        if (grid) {
                            grid.dataSource.read();
                        }
                    }

                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Error!",
                        text: data.Message,
                        icon: "error"
                    });
                }
            });
        }
    });
}

function DeleteCommonWithParamsGet(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    $.when(kendo.ui.ExtOkCancelDialog.show({
        title: windowTitle,
        message: windowsMessage,
        icon: "k-ext-question",
        width: "400px",
        RTL: (isRTL === "True")
    })).done(function (response) {
        if (response.button === "OK") {
            $.get(url, sPostData, function (data) {
                if (data.Success) {
                    var grid = $("#" + gridId).data("kendoGrid");
                    grid.dataSource.read();
                    showSuccessMessageSwal(data.Message);
                } else {
                    showErrorMessageSwal(data.Message);
                }
            });
        }
    });
}

function DeleteCommonWithParams(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    $.when(kendo.ui.ExtOkCancelDialog.show({
        title: windowTitle,
        message: windowsMessage,
        icon: "k-ext-question",
        width: "400px",
        RTL: (isRTL === "True")
    })).done(function (response) {
        if (response.button === "OK") {
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    var grid = $("#" + gridId).data("kendoGrid");
                    grid.dataSource.read();
                    showSuccessMessageSwal(data.Message);
                } else {
                    showErrorMessageSwal(data.Message);
                }
            });
        }
    });
}

function DynamicallyFillKendoLists(kendoListId, kendoListType, textField, valueField, fillURL, verb, routData, optionalFirstElement = "") {
    var kendoList = $("#" + kendoListId).data(kendoListType);
    $.ajax({
        url: fillURL,
        type: verb,
        data: routData,
        success: function (data) {
            if (optionalFirstElement != "") {
                data.unshift(optionalFirstElement);
            }
            kendoList.setDataSource({
                data: data,
                dataTextField: textField,
                dataValueField: valueField
            });
        }
    });
}

var invalidFiles = new Array();

function getUploadedFilesNamesList(uploadFileControlId) {
    var lstFilesModel = new Array();
    var files = $("#" + uploadFileControlId).data("kendoUpload").getFiles();

    for (var i = 0; i < files.length; i++) {
        var fileIndex = $.inArray(files[i].uid, invalidFiles);
        if (fileIndex >= 0) {
        } else {
            var fileName = files[i].name.split("/");
            var fileName = files[i].name;
            lstFilesModel.push({
                FileName: fileName,
                FileType: 1,
            });
        }
    }
    return lstFilesModel;
}

function getUploadedFrontFilesNamesList(uploadFileControlId) {
    var lstFilesModel = new Array();
    var files = $("#" + uploadFileControlId).data("kendoUpload").getFiles();

    for (var i = 0; i < files.length; i++) {
        var fileIndex = $.inArray(files[i].uid, invalidFiles);
        if (fileIndex >= 0) {
        } else {
            var fileName = files[i].name.split("/");
            var fileName = files[i].name;
            lstFilesModel.push({
                FrontFileName: fileName,
                FileType: 1,
            });
        }
    }
    return lstFilesModel;
}

function onUploadSelect(e) {
    var validationFilesResult = onUploadSelectMultipleFilesCommon(e);
    invalidFiles = validationFilesResult.invalidFiles;

    if (validationFilesResult.invalidFileTypeCount > 0) {
        return showErrorMessageSwal(validationFilesResult.invalidFileTypeCount + " " + validationMessages.invalidFileType);
    }

    if (validationFilesResult.invalidFileSizeCount > 0) {
        return showErrorMessageSwal(validationFilesResult.invalidFileSizeCount + " " + validationMessages.invalidFileSize);
    }

    if (validationFilesResult.duplicateFileCount > 0) {
        return showErrorMessageSwal(validationFilesResult.duplicateFileCount + " " + validationMessages.duplicateFileName);
    }

    if (validationFilesResult.fileContainSymboleCount > 0) {
        return showErrorMessageSwal(validationFilesResult.fileContainSymboleCount + " " + validationMessages.fileContainSymbol);
    }
}

function onUploadSelectMultipleFilesCommon(e) {
    toggleSaveButton(true);
    var filesInList = $("ul.k-upload-files span.k-file-name");
    var invalidFileTypeCount = 0;
    var invalidFileSizeCount = 0;
    var duplicateFileCount = 0;
    var fileContainSymboleCount = 0;
    invalidFiles = new Array();
    const allCharSymbole = ["&", "%", "+", '?', '@'];

    $.each(e.files, function (index, value) {
        if (value.validationErrors && value.validationErrors.length > 0) {
            if (value.validationErrors[0] === "invalidFileExtension") {
                invalidFileTypeCount++;
                e.preventDefault();
            } else if (value.validationErrors[0] === "invalidMaxFileSize") {
                invalidFileSizeCount++;
                e.preventDefault();
            }
            invalidFiles.push(e.files[index].uid);
        }

        for (let i = 0; i < allCharSymbole.length; i++) {
            if (value.name.includes(allCharSymbole[i]) == true) {
                fileContainSymboleCount++;
                e.preventDefault();
                invalidFiles.push(e.files[index].uid);
                continue;
            }
        }

        filesInList.each(function () {
            if ($(this).text() === value.name) {
                duplicateFileCount++;
                e.preventDefault();
                invalidFiles.push(e.files[index].uid);
            }
        });
    });

    if (invalidFiles.length != 0) {
        toggleSaveButton(false);
    }

    return {
        invalidFileTypeCount: invalidFileTypeCount,
        invalidFileSizeCount: invalidFileSizeCount,
        duplicateFileCount: duplicateFileCount,
        fileContainSymboleCount: fileContainSymboleCount,
        invalidFiles: invalidFiles,
    };
}

function onUploadComplete(e) {
    toggleSaveButton(false);
}

function toggleSaveButton(disabled) {
  
    const saveButton = document.querySelector('.btn.btn-sm.btn-post');
    if (!saveButton) return;
    saveButton.disabled = disabled;

    if (disabled) {
        saveButton.classList.add('disabled');
    } else {
        saveButton.classList.remove('disabled');
    }
}

function toast(message, type = 'success', timer = '2500', position = 'bottom-end') {
    const Toast = Swal.mixin({
        toast: true,
        position: position,
        showConfirmButton: false,
        timer: timer,
        timerProgressBar: true,
    })

    Toast.fire({
        type: type,
        title: message
    });
}

function DeleteAlertCustem(e, windowTitle, windowsMessage, isRTL, gridId) {
    e.preventDefault();
    var grid = $("#" + gridId).data("kendoGrid");
    var dataItem = grid.dataItem($(e.currentTarget).closest("tr"));
    ConfirmActionAlertSwal(
        windowTitle,
        windowsMessage,
        isRTL,
        gridId,
        dataItem
    );
}

function ConfirmActionAlertSwal(windowTitle, windowsMessage, isRTL, gridId, rowData) {
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });
  
    const confirmButtonText = CommonJsKeyRes.DeleteLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;
    const titleText = CommonJsKeyRes.MsgSuccessfully;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Find the Kendo Grid instance
            var grid = $("#" + gridId).data("kendoGrid");

            if (grid && rowData) {
                // Remove the row data from the data source
                grid.dataSource.remove(rowData);
                grid.dataSource.sync(); // Sync the grid to reflect changes

                // Success message
                swalWithBootstrapButtons.fire({
                    title: titleText,
                    confirmButtonText: okButtonText,
                    timer: 1500,
                    timerProgressBar: true,
                    icon: "success",
                    customClass: {
                        actions: 'my-actions',
                        cancelButton: 'd-none',
                        confirmButton: 'swal2-confirm btn btn-success'
                    },
                });
            } else {
                // Error handling
                swalWithBootstrapButtons.fire({
                    title: "Error",
                    text: "Unable to delete row. Grid or row data not found.",
                    icon: "error"
                });
            }
        }
    });
}


function confirmDelete(element, gridId, isRTL) {

    const confirmButtonText = CommonJsKeyRes.DeleteLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;
    const titleText = CommonJsKeyRes.MsgDeletedSuccessfully;
    const titlefire = CommonJsKeyRes.MsgDeletedConfirm;
    const textfire = CommonJsKeyRes.MsgWillTemporarilyDeleted;



    Swal.fire({
        title: titlefire,
        text: textfire,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
    }).then((result) => {
        if (result.isConfirmed) {
            var grid = $("#" + gridId).data("kendoGrid");
            var row = $(element).closest("tr");
            var dataItem = grid.dataItem(row);
            grid.dataSource.remove(dataItem);
            grid.dataSource.sync();
            Swal.fire({
                text: titleText,
                icon: "success",
                timer: 1500,
                confirmButtonText: okButtonText,
                timerProgressBar: true,
            });
        }
     
    });
}





function createSvg(percentage, labelText = "") {
    const absPercentage = Math.abs(percentage);
    const classes =
        percentage < 0
            ? "danger-stroke circle-chart__circle--negative"
            : percentage <= 30
                ? "warning-stroke"
                : "success-stroke";

    return `
      <svg class="circle-chart" viewBox="0 0 33.83 33.83" xmlns="http://www.w3.org/2000/svg">
          <circle class="circle-chart__background" cx="16.9" cy="16.9" r="15.9"></circle>
          <circle class="circle-chart__circle ${classes}" stroke-dasharray="${absPercentage},100" cx="16.9" cy="16.9" r="15.9"></circle>
          <g class="circle-chart__info">
              <text class="circle-chart__percent" x="16.9" y="15.5">${percentage}%</text>
              ${labelText ? `<text class="circle-chart__subline" x="16.9" y="22">${labelText}</text>` : ""}
          </g>
      </svg>
  `;
}

(function ($) {
    $.fn.circlechart = function () {
        this.each(function () {
            const percentage = $(this).data("percentage");
            const labelText = $(this).text();
            $(this).html(createSvg(percentage, labelText));
        });
        return this;
    };
})(jQuery);


function ConfirmActionNotGridSwal(sPostData, windowTitle, windowsMessage, isRTL, url) {
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-warning",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    const confirmButtonText = CommonJsKeyRes.YesLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Error!",
                        text: data.Message,
                        icon: "error"
                    });
                }
            });
        }
    });
}

function CancelConfirmActionMultiParamsSwal(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    debugger
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    // Set button text based on the isRTL flag
    const confirmButtonText = CommonJsKeyRes.YesLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;

    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    var grid = $("#" + gridId).data("kendoGrid");
                    grid.dataSource.read();
                    startNotificationTimer("WorkFlowNotification");
                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Error!",
                        text: data.Message,
                        icon: "error"
                    });
                }
            });
        }
    });
}







function allowOnlyDigits(e) {
    var key = e.key;
    // Allow digits 0–9 and essential keys like backspace, delete, arrows
    if (/^[0-9]$/.test(key) ||
        ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(key)) {
        return true;
    }
    e.preventDefault();
    return false;
}


function updateListBoxToolbarDirection(isRTL) {
    const listBox = document.querySelector('.k-listbox');

    if (!listBox) return;

    listBox.classList.remove('k-listbox-toolbar-left', 'k-listbox-toolbar-right');

    if (isRTL) {
        listBox.classList.add('k-listbox-toolbar-right');
    } else {
        listBox.classList.add('k-listbox-toolbar-left');
    }
}

// Example usage
const isRTL = document.documentElement.dir === 'rtl'; // Or your own language check


function removeFirstButtonInGrid(id) {
    var gridContainer = $("#" + id);
    if (gridContainer.length > 0) {
        var firstButton = gridContainer.find("a.k-button").first();
        if (firstButton.length > 0) {
            firstButton.remove();
        }
    }
}



// Wait for the document to fully load before applying styles
document.addEventListener('DOMContentLoaded', function () {
    //// Select all elements with the 'readonly' attribute (and any other attributes you need)
    //var elementsWithAttributes = document.querySelectorAll('[readonly], [disabled]');

    //// Loop through each element and add the 'readOnly-box' class
    //elementsWithAttributes.forEach(function (element) {
    //    element.classList.add('readOnly-box');
    //});
});








$(document).ready(function () {
    setTimeout(function () {
        var generalRequestGrid = $("#gridContainerWfSignature").data("kendoGrid");

        if (generalRequestGrid) {
            generalRequestGrid.bind("dataBound", function () {
                // Row checkboxes
                $("[id^='Accept_']").addClass("custom-checkbox approve shadow");
                $("[id^='Refuse_']").addClass("custom-checkbox refuse-checkbox shadow");

                // Header checkboxes
                $("#checkAll").addClass("custom-checkbox approve shadow");
                $("#checkAllRefuse").addClass("custom-checkbox refuse-checkbox shadow");

                // Center all TDs that contain checkbox inputs
                $("#gridContainerWfSignature td").has("input[type='checkbox']").addClass("text-center");

            });
        }
    }, 100);


});



function ConfirmActionTreeviewMultiParamsSwal(sPostData, windowTitle, windowsMessage, isRTL, url, gridId) {
    debugger
    const swalWithBootstrapButtons = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success",
            cancelButton: "btn btn-secondary"
        },
        buttonsStyling: false
    });

    // Set button text based on the isRTL flag
    const confirmButtonText = CommonJsKeyRes.YesLabel;
    const cancelButtonText = CommonJsKeyRes.CancelLabel;
    const okButtonText = CommonJsKeyRes.CloseLabel;



    swalWithBootstrapButtons.fire({
        title: windowTitle,
        text: windowsMessage,
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        reverseButtons: true,
        rtl: (isRTL === "True") // RTL support
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform the delete operation
            $.post(url, sPostData, function (data) {
                if (data.Success) {
                    // دعم قائمة أو قيمة مفردة لـ gridId
                    if (Array.isArray(gridId)) {
                        gridId.forEach(function (id) {
                            const grid = $("#" + id).data("kendoTreeView");
                            if (grid) {
                                grid.dataSource.read();
                            }
                        });
                    } else {
                        const grid = $("#" + gridId).data("kendoTreeView");
                        if (grid) {
                            grid.dataSource.read();
                        }
                    }

                    swalWithBootstrapButtons.fire({
                        title: data.Message,
                        confirmButtonText: okButtonText,
                        timer: 1500,
                        timerProgressBar: true,
                        icon: "success",
                        customClass: {
                            actions: 'my-actions',
                            cancelButton: 'd-none',
                            confirmButton: 'swal2-confirm btn btn-success',
                        },
                    });
                } else {
                    swalWithBootstrapButtons.fire({
                        title: "Error!",
                        text: data.Message,
                        icon: "error"
                    });
                }
            });
        }
    });
}


$("<style>")
    .prop("type", "text/css")
    .html(`
        .k-loading-mask,
        .k-loading-image,
        .k-loading-color {
            display: none !important;
        }
    `)
    .appendTo("head");

$(document).ready(function () {
    $(".k-grid").each(function () {
        var grid = $(this).data("kendoGrid");
        if (grid) {
            grid.bind("dataBinding", function () {
                this.wrapper.find(".k-loading-mask").hide();
            });
            
        }
    });
});


function CheckLanguage(e, dir, langId) {
    var unicode = e.charCode;
    if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
        if (unicode == 32 || unicode == 0)
            return true;
        else {
            if (dir == 1) {
                if ((unicode < 48 || unicode > 57) && (unicode < 0x0600 || unicode > 0x06FF)
                ) //if not a number or arabic
                {
                    if (langId == 1) {
                        Swal.fire("من فضلك قم بتغيير اللغة الى  العربية");
                    } else {
                        Swal.fire("Please Change Language To Arabic");

                    }

                    return false; //disable key press
                }
            }
            if (dir == 2) {
                //English or number
                if ((unicode < 48 || unicode > 57) && (unicode < 0x0600 || unicode > 0x06FF)
                )
                    return true;
                else if ((e.charCode >= 48 && e.charCode <= 57)) {
                    return true;
                } else {
                    if (langId == 1) {

                        Swal.fire("من فضلك قم بتغيير اللغة الى  الإنجليزية");
                    } else {

                        Swal.fire("Please Change Language To English");
                    }
                    return false;
                }
            }
        }
    }
}