function onChangeCommonTextLang(e, lang, targetTextEn, targetTextAr) {
   
    var sourceLangName;
    var targetLangName;
    var targetText;
    var id = e.currentTarget.id;

    if (lang === 1) {
        sourceLangName = 'Arabic';
        targetLangName = 'English';

        targetText = $("#tb" + targetTextEn);
        if (!targetText.length) {
            targetText = $("#" + targetTextEn);
        }

    } else {
        sourceLangName = 'English';
        targetLangName = 'Arabic';

        targetText = $("#tb" + targetTextAr);
        if (!targetText.length) {
            targetText = $("#" + targetTextAr);
        }
    }

    var sourceText = $("#" + id).val();

    if (sourceText !== "" && targetText.val() === "") {
        $.ajax({
            async: false,
            url: "../../Translator/GetTranslator",
            type: "POST",
            dataType: "json",
            data: { sourceText: sourceText, sourceLanguage: sourceLangName, targetLanguage: targetLangName },
            success: function (result) {
                targetText.val(result);
            },
            error: function () {
                $.ajax({
                    async: false,
                    url: "../Translator/GetTranslator",
                    type: "POST",
                    dataType: "json",
                    data: { sourceText: sourceText, sourceLanguage: sourceLangName, targetLanguage: targetLangName },
                    success: function (result) {
                        targetText.val(result);
                    },
                    error: function () {
                        targetText.val();
                    }
                });
            }
        });


    }
}

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    if (xhr.status == 401) {
        // unauthorized
        //window.location.href = 'login?returnurl=/';
        window.location.href = 'Protection/index';
    }
});

$(document).ajaxSuccess(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    //set current to the "en-GB" culture script
    kendo.culture("en-GB");
    //alert(kendo.culture().calendar.patterns.d);
    //alert(kendo.toString(new Date(2000, 10, 18), "d"));
});

function SubmitForm(FormName, ControllerName, ActionName, CommandName, GetDataObjectMethodName, OnSuccessMethodName, httpMethod, ValidateForm, UpdateFormAction, ShowWaitingDialog, DestroyKendo, ExtWaitDialogTitle, ExtWaitDialogMessage) {
    ValidateForm = ValidateForm == null || ValidateForm == undefined ? true : ValidateForm;
    httpMethod = httpMethod == null || httpMethod == undefined ? "get" : httpMethod;
    UpdateFormAction = UpdateFormAction == null || UpdateFormAction == undefined ? false : UpdateFormAction;
    ShowWaitingDialog = ShowWaitingDialog == null || ShowWaitingDialog == undefined ? true : ShowWaitingDialog;
    DestroyKendo = DestroyKendo == null || DestroyKendo == undefined ? true : DestroyKendo;
    if (!ValidateForm || ($('#' + FormName + '')[0] && $('#' + FormName + '').valid())) {
        if (UpdateFormAction)
            $("#" + FormName).attr("action", ControllerName + "/" + ActionName);

        jQuery.ajaxSettings.traditional = true;
        $.ajaxSetup({
            cache: false
        });

        if (ShowWaitingDialog)
            $.when(kendo.ui.ExtWaitDialog.show({ title: ExtWaitDialogTitle, message: ExtWaitDialogMessage }));

        if (httpMethod == "post")
            $.post("/" + ControllerName + "/" + ActionName, GetDataObjectMethodName != null ? GetDataObjectMethodName(CommandName) : null, function (data) {
                if (ShowWaitingDialog)
                    kendo.ui.ExtWaitDialog.hide();

                if (DestroyKendo)
                    $(".k-window").each(function () {
                        $(this).remove();
                    });

                OnSuccessMethodName(data);
            }, "json").fail(function (d) {
                if (ShowWaitingDialog)
                    kendo.ui.ExtWaitDialog.hide();
                $.when(kendo.ui.ExtAlertDialog.show({
                    title: "Error",
                    message: "Load Failed",
                    icon: "k-ext-error"
                }));
            });
        else
            $.get("/" + ControllerName + "/" + ActionName, GetDataObjectMethodName != null ? GetDataObjectMethodName(CommandName) : null, function (data) {
                if (ShowWaitingDialog)
                    kendo.ui.ExtWaitDialog.hide();

                if (DestroyKendo)
                    $(".k-window").each(function () {
                        $(this).remove();
                    });

                OnSuccessMethodName(data);
            }, "json").fail(function (d) {
                if (ShowWaitingDialog)
                    kendo.ui.ExtWaitDialog.hide();
                $.when(kendo.ui.ExtAlertDialog.show({
                    title: "Error",
                    message: "Load Failed",
                    icon: "k-ext-error"
                }));
            });
    }
}

function IsValidEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

var KendoCustom = {
    OpenWindow: function (options) {
        options = $.extend({
            WinId: "",
            WinTitle: null,
            CenterWin: true,
            BindContent: false,
            Content: null
        }, options);

        var window = $("#" + options.WinId).data("kendoWindow");

        if (window != undefined && window != null) {
            if (options.WinTitle != null)
                window.title(options.WinTitle);

            if (options.BindContent)
                window.content(options.Content);

            if (options.CenterWin)
                window.center();

            window.open();
        }
    },

    CloseWindowById: function (winId) {
        $("#" + winId).data("kendoWindow").close();
    },

    CloseWindowUsingInternalElement: function (element) {
        $(element).closest('div.k-window-content').data("kendoWindow").close();
    },

    RunkendoValidator: function (frmId) {
        $('#' + frmId).kendoValidator();
    },

    //ValidatekendoValidator: function (frmId) {
    //
    //    var validator = $("#" + frmId).kendoValidator().data("kendoValidator");
    //    return validator.validate();
    //},

    ReadGrid: function (gridId) {
        var grid = $("#" + gridId).data("kendoGrid");
        if (grid != undefined && grid != null)
            grid.dataSource.read();
    },

    ReadPageGrid: function (gridId, index) {
        var grid = $("#" + gridId).data("kendoGrid");
        if (grid != undefined && grid != null)
            grid.dataSource.page(index);
    },

    ReadListView: function (viewId) {
        var listView = $("#" + viewId).data("kendoListView");
        if (listView != undefined && listView != null)
            listView.dataSource.read();
    },

    ReadPageListView: function (viewId, index) {
        var listView = $("#" + viewId).data("kendoListView");
        if (listView != undefined && listView != null)
            listView.dataSource.page(index);
    },

    GetKendObject: function (kendoType, kendoElementId) {
        return $("#" + kendoElementId).data(kendoType);
    },

    TreeViewInputSearch: function (inputId, treeViewId) {
        var itemsCount = 0;
        var currentIndex = -1;

        var ScrollToHighlighted = function (index) {
            var div = $('#' + treeViewId);
            var item = div.find('.highlight').eq(index);

            //alert(div.scrollTop() + item.offset().top - div.offset().top);

            div.animate({
                scrollTop: div.scrollTop() + item.offset().top - div.offset().top
            }, 0);
        }

        $('#' + inputId).on('keyup', function () {
            var tv = $('#' + treeViewId).data('kendoTreeView');
            $('#' + inputId + '_Down').addClass('k-state-disabled').attr("disabled", "disabled");
            $('#' + inputId + '_Top').addClass('k-state-disabled').attr("disabled", "disabled");
            itemsCount = 0;
            currentIndex = -1;

            $('span.k-in > span.highlight').each(function () {
                $(this).parent().text($(this).parent().text());
            });

            // ignore if no search term
            if ($.trim($(this).val()) == '') {
                $('#' + inputId + '_Count').hide();
                return;
            }

            var term = this.value.toUpperCase();
            var tlen = term.length;

            $('#' + treeViewId + ' span.k-in').each(function (index) {
                var text = $(this).text();
                var html = '';
                var q = 0;
                while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
                    html += text.substring(q, p) + '<span class="highlight">' + text.substr(p, tlen) + '</span>';
                    q = p + tlen;
                }

                if (q > 0) {
                    itemsCount++;

                    html += text.substring(q);
                    $(this).html(html);

                    $(this).parentsUntil('.k-treeview').filter('.k-item').each(
                        function (index, element) {
                            tv.expand($(this));
                            $(this).data(inputId, term);
                        }
                    );

                    if (itemsCount == 1) {
                        ScrollToHighlighted(0);
                    }
                }
            });

            //$('#' + treeViewId + ' .k-item').each(function () {
            //    if ($(this).data(inputId) != term) {
            //        tv.collapse($(this));
            //    }
            //});

            if (itemsCount > 0) {
                $('#' + inputId + '_Count').text('1 - ' + itemsCount).show();
                currentIndex = 0;

                if (itemsCount > 1) {
                    $('#' + inputId + '_Down').removeClass('k-state-disabled').removeAttr("disabled");
                }
            } else {
                $('#' + inputId + '_Count').hide();
            }
        });

        $('#' + inputId + '_Top').on('click', function () {
            if (currentIndex == itemsCount - 1)
                $('#' + inputId + '_Down').removeClass('k-state-disabled').removeAttr("disabled");

            currentIndex--;

            $('#' + inputId + '_Count').text((currentIndex + 1) + ' - ' + itemsCount).show();
            ScrollToHighlighted(currentIndex);

            if (currentIndex == 0)
                $('#' + inputId + '_Top').addClass('k-state-disabled').attr("disabled", "disabled");
        });

        $('#' + inputId + '_Down').on('click', function () {
            if (currentIndex == 0)
                $('#' + inputId + '_Top').removeClass('k-state-disabled').removeAttr("disabled");

            currentIndex++;

            $('#' + inputId + '_Count').text((currentIndex + 1) + ' - ' + itemsCount).show();
            ScrollToHighlighted(currentIndex);

            if (currentIndex == itemsCount - 1)
                $('#' + inputId + '_Down').addClass('k-state-disabled').attr("disabled", "disabled");
        });
    }
};

var commonValidation = {
    IsValidEmail: function () {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    },

    Integer: function (e) {
        var k = e.which;

        return !(k > 31 && (k < 48 || k > 57));
    },

    PreventSpecialCharacters: function (e) {
        var k = e.which;

        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 /*|| k == 32*/ || (k >= 48 && k <= 57));
    }
}

$(document).ajaxSuccess(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    //set current to the "en-GB" culture script
    kendo.culture("en-GB");
});

var Common = {
    LoadPageContent: function (data) {
        $("#pageContent").html(data);
        //$("#pageContent").children('div.RibbonContent').eq(0).attr("class", "RibbonContent Hide");
    },

    LoadViewContent: function (data, title) {
        $("#content").html(data);

        if (title != undefined && title != null)
            $("span.RibbonTitle").html(title);
    },

    AjaxCall: function (options) {
        options = $.extend({
            ControllerName: null,
            ActionName: null,
            RouteData: null,
            OnSuccess: null,
            OnFail: null,
            HttpMethod: "get",
            ShowWaitingDialog: false,
            WaitingDialogTitle: "Please Wait",
            WaitingDialogMsg: "Waiting for loading...",
            ShowFailedDialog: true,
            LoadFailedTitle: "Error",
            LoadFailedMsg: "Load Failed",
            DestroyKendoWindow: false,
            RTL: false
        }, options);

        if (options.ControllerName != null && options.ActionName != null) {
            jQuery.ajaxSettings.traditional = true;

            $.ajaxSetup({
                cache: false
            });

            if (options.ShowWaitingDialog)
                $.when(kendo.ui.ExtWaitDialog.show({ title: options.WaitingDialogTitle, message: options.WaitingDialogMsg }));

            if (options.HttpMethod == "post")
                $.post(options.ControllerName + "/" + options.ActionName, options.RouteData, function (data) {
                    if (options.ShowWaitingDialog)
                        kendo.ui.ExtWaitDialog.hide();

                    if (options.DestroyKendoWindow)
                        $(".k-window").each(function () {
                            $(this).remove();
                        });

                    if (options.OnSuccess != null)
                        options.OnSuccess(data);
                }).fail(function (d) {
                    if (options.ShowWaitingDialog)
                        kendo.ui.ExtWaitDialog.hide();

                    if (options.OnFail != null)
                        options.OnFail(d);

                    if (options.ShowFailedDialog)
                        $.when(kendo.ui.ExtAlertDialog.show({
                            title: options.LoadFailedTitle,
                            message: options.LoadFailedMsg,
                            icon: "k-ext-error",
                            RTL: options.RTL
                        }));
                });
            else
                // $("#urlRoot").val() +
                $.get(options.ControllerName + "/" + options.ActionName, options.RouteData, function (data) {
                    if (options.ShowWaitingDialog)
                        kendo.ui.ExtWaitDialog.hide();

                    if (options.DestroyKendoWindow)
                        $(".k-window").each(function () {
                            $(this).remove();
                        });

                    if (options.OnSuccess != null)
                        options.OnSuccess(data);
                }).fail(function (d) {
                    if (options.ShowWaitingDialog)
                        kendo.ui.ExtWaitDialog.hide();

                    if (options.OnFail != null)
                        options.OnFail(d);

                    if (options.ShowFailedDialog)
                        $.when(kendo.ui.ExtAlertDialog.show({
                            title: options.LoadFailedTitle,
                            message: options.LoadFailedMsg,
                            icon: "k-ext-error",
                            RTL: options.RTL
                        }));
                });
        }
    }
}

//$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
//    if (xhr.status == 401) {
//        window.location.href = 'Protection/index';
//    }
//});

var DateManager = {
    MonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

    QuinDate: function (dtime) {
        var d = new Date(parseInt(dtime.toString().slice(6, -2)));

        return d.getDate() + ' ' + this.MonthNames[(d.getMonth())] + ' ' + d.getFullYear();
    },

    GetDateTime: function (dtime) {
        var d = new Date(parseInt(dtime.toString().slice(6, -2)));
        return d.getHours() + ":" + d.getMinutes();
    },

    GetTime: function (date) {
        var h = date.getHours();
        var m = date.getMinutes();
        var t;
        if (m < 10) {
            m = "0" + m;
        }

        if (h > 11) {
            h = h - 12;
            t = " PM";
        } else {
            t = " AM";
        }

        return h + ":" + m + " " + t;
    }
}

var commonValidation = {
    IsValidEmail: function () {
        var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regex.test(email);
    },

    Integer: function (e) {
        var k = e.which;

        return !(k > 31 && (k < 48 || k > 57));
    },

    PreventSpecialCharacters: function (e) {
        var k = e.which;

        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 /*|| k == 32*/ || (k >= 48 && k <= 57));
    }
}
function CheckLanguage(e, dir, langId) {
    debugger;

    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) {


                // الإنجليزي
                if ((langId == 2 || langId == 1 || langId == 4 /*gric*/) && e.currentTarget.id == "tbName") {
                    if (((unicode < 48 || unicode > 57) && (unicode < 0x0600 || unicode > 0x06FF)) || (e.charCode >= 48 && e.charCode <= 57)) {
                        return true;
                    } else {
                        if (langId == 1) {
                            Swal.fire("من فضلك قم بتغيير اللغة الى الإنجليزية");
                        } else {
                            Swal.fire("Please Change Language To English");
                        }
                        return false;
                    }
                }
                // اليوناني
                else if (langId == 4 && e.currentTarget.id != "tbName") {
                    if ((unicode >= 0x0370 && unicode <= 0x03FF) || (unicode >= 48 && unicode <= 57)) {
                        return true;
                    } else {
                        if (langId == 1) {
                            Swal.fire("من فضلك قم بتغيير اللغة الى اليونانية");
                        } else {
                            Swal.fire("Παρακαλώ αλλάξτε τη γλώσσα σε Ελληνικά");
                        }
                        return false;
                    }
                }

              
            }
        }
    }
}
//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;
//                }
//            }
//        }
//    }
//}
function CheckDescriptionLanguage(e, lang) {
    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 (lang == 1) {
                if ((unicode < 48 || unicode > 57) && (unicode < 0x0600 || unicode > 0x06FF)
                ) //if not a number or arabic
                {
                    if (unicode == 45 || unicode == 47 || unicode == 92) {
                        return true;
                    }
                    alert("من فضلك قم بتغيير اللغة الى  العربية");
                    return false; //disable key press
                }
            }
            if (lang == 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 {
                    alert("Please Change Language To English");

                    return false;
                }
            }
        }
    }
}

document.addEventListener("DOMContentLoaded", function () {
    // Select all labels with the custom attribute data-isdisplayasterisk
    var labels = document.querySelectorAll("label[data-isdisplayasterisk]");

    labels.forEach(function (label) {
        var isDisplayAsterisk = label.getAttribute("data-isdisplayasterisk");

        if (isDisplayAsterisk === "true") {
            var span = document.createElement("span");
            span.textContent = "*";  // Asterisk to be added
            span.style.color = "red"; // Set the text color to red
            label.appendChild(span);
        }
    });
});
