//#region Form General

//#region Other From Behavior

function ChangeRequirements(elementsID, IsRequirement) {
    $.each(elementsID.split(","), function (index, elementID) {
        ChangeRequirement($('#' + elementID), IsRequirement);
    });
}
function ChangeRequirement(input, IsRequirement) {


    if (IsRequirement) {
        $(input).attr('required', 'required');
        //$(input).removeAttr('nonRequired');
        if ($(input).parent().parent().is('.k-datepicker')) {
            {
                if (firstReloadFlag != 1)
                    $(input).parent().css("border", "1px solid red");
            }
        }
        else if ($(input).is('input.tzTimePicker')) {
            if (firstReloadFlag != 1)
                $(input).css("border", "1px solid red");
        }

        else if ($(input).parent().is('.k-dropdown')) {
            if (firstReloadFlag != 1)
                $(input).parent().css("border", "1px solid red");
        }

        else if ($(input).hasClass('tzFileUpload')) {
            if ($(input).attr('fileID') == "-1")
                $(input).children('.input-group-btn').children("span.btn.btn-default.btn-file").children().attr('required', 'required');

            if (firstReloadFlag != 1)
                $(input).css("border", "1px solid red");
        }

        else if ($(input).hasClass('tzLookup')) {
            if (firstReloadFlag != 1)
                $(input).css("border", "1px solid red");
            $(input).children('input').attr('required', 'required');
            $(input).children('input').removeAttr('disabled');
            $(input).children('input').keydown(function (e) {
                e.preventDefault();
            });

        }

        else if ($(input).hasClass('k-textbox')) {
            if (firstReloadFlag != 1)
                $(input).addClass("k-invalid")
        }
        else if ($(input).hasClass('k-content')) {
            if (firstReloadFlag != 1) {
                $(input).attr('required', 'required');
                $(input).addClass("k-invalid")
                $(input).css("border", "1px solid red");
                // $('iframe').css('border', '1px solid red');
                $(input).prev('.k-content').css('border', '1px solid red');
            }

        }

        return true;
    }
    else {


        $(input).removeAttr('required');
        $(input).attr('aria-invalid', false);

        if ($(input).parent().parent().is('.k-datepicker')) {
            $(input).parent().css("border", "");
        }
        else if ($(input).is('input.tzTimePicker')) {
            $(input).css("border", "");
        }
        else if ($(input).parent().is('.k-dropdown')) {
            $(input).parent().css("border", "");
            $(input).parent().removeClass("k-invalid")
        }
        else if ($(input).hasClass('tzFileUpload')) {
            $(input).children('.input-group-btn').children("span.btn.btn-default.btn-file").children().removeAttr('required');
            $(input).css("border", "");
        }
        else if ($(input).hasClass('tzLookup')) {

            $(input).css("border", "");
            $(input).children('input').removeAttr('required');
            $(input).children('input').attr('disabled', 'disabled');
        }
        else if ($(input).hasClass('k-content')) {
            $(input).removeAttr('required');
            $(input).css("border", "");
            $(input).prev('.k-content').css('border', '');
            // $('iframe').css('border', '');
        }
        //if (true) {
        //    $(input).has
        //}
        //$(input).removeAttr('required');
        //$(input).attr('nonRequired',"");
        //return false;
    }
}

var ComponentsDiplayStatus = [];
function EnableComponents(elementsID, enable, raiser) {
    //if (firstReloadFlag == 1) {
    //firstReloadFlag => waiting for components initilizing
    ComponentsDiplayStatus.push({
        key: elementsID,
        value: enable,
        raiser: raiser
    });
    //} else {
    $.each(elementsID.split(","), function (index, elementID) {
        EnableComponent($('#' + elementID), enable, raiser);
    });
    //}
}

function EnableComponent(input, enable, raiser) {

    var EqualChildParentFlag = GetElementID(raiser) == GetElementID(input);
    if (!EqualChildParentFlag)
        ElementActivityLogger(raiser, input, enable);


    if ($(input).is('input.k-textbox,a,textarea.k-textbox,input.tzTimePicker')) {
        if (enable) {
            // $(input).removeAttr('disabled');
            $(input).removeAttr('readonly');
            $(input).removeClass('k-state-disabled');
        }
        else {
            //$(input).attr('disabled', 'disabled');
            $(input).attr('readonly', 'readonly');
            $(input).addClass('k-state-disabled');
        }
    }
    else if ($(input).is('button.tbsButton,button.tzButton')) {
        if (enable) {
            // $(input).removeAttr('disabled');
            $(input).removeAttr('disabled');
            $(input).removeClass('k-state-disabled');
        }
        else {
            //$(input).attr('disabled', 'disabled');
            $(input).attr('disabled', 'disabled');
            $(input).addClass('k-state-disabled');
        }
    }
    else if ($(input).is('div.tzFileUpload')) {
        if (enable) {
            $(input).find('.glyphicon-remove').removeAttr("disabled");
            $(input).find('input[type=file]').removeAttr('disabled');
            $(input).removeClass('tzDisabled');
            $(input).find('div.input-group-btn > span.btn-file').css('background-color', '#fff');
            $(input).find('div.input-group-btn > span.btn-file').css('cursor', 'pointer');
        }
        else {

            // $('.btn.btn-default.k-state-disabled.glyphicon.glyphicon-remove').trigger('click');

            $(input).find('input[type=file]').attr('disabled', 'disabled');
            $(input).find('.glyphicon-remove').attr("disabled", "disabled");
            $(input).find('div.input-group-btn > span.btn-file').css('background-color', 'silver');
            $(input).find('div.input-group-btn > span.btn-file').css('cursor', 'default');
        }

    }
    else if ($(input).is("input[type='checkbox'],input[type='radio']")) {
        if (enable) {
            $(input).parent().css('color', 'black');
            $(input).removeAttr('disabled');
            $(input).removeClass('k-state-disabled');
        }
        else {
            $(input).parent().css('color', '#7a7777');
            $(input).attr('disabled', 'disabled');
            $(input).addClass('k-state-disabled');
        }
    }
    else if ($(input).is("ul.tzCheckListBox")) {
        if (enable) {
            $(input).children('li').css('color', 'black');
            $(input).children('li').children('label').children('input.tzCheckListCheckBox').removeAttr('disabled');
            $(input).children('li').children('label').children('input.tzCheckListCheckBox').removeClass('k-state-disabled');
        }
        else {
            $(input).children('li').css('color', 'silver');
            $(input).children('li').children('label').children('input.tzCheckListCheckBox').attr('disabled', 'disabled');
            $(input).children('li').children('label').children('input.tzCheckListCheckBox').addClass('k-state-disabled');
        }
    }
    else if ($(input).parent().parent().is('.k-datepicker')) {
        //if ($(input).data('kendoDatePicker') == undefined)
        //    setTimeout(function () { EnableComponent(input, enable); }, 200);
        //else
        //$(input).data('kendoDatePicker').enable(enable);
        var ComponentItem;
        if ($(input).hasClass('tzGregorianMode')) {
            ComponentItem = $(input).data('kendoDatePickerEn');
        } else {
            ComponentItem = $(input).data('kendoDatePicker');
        }


        if (ComponentItem != undefined) {
            ComponentItem.enable(enable);
        }
    }
    else if ($(input).is('div.tzLookup')) {
        if (enable) {
            //$(input).children('button').removeClass('k-state-disabled');
            $(input).children('button').prop('disabled', false);
            $(input).removeClass('k-state-disabled');
        }
        else {
            //$(input).children('button').addClass('k-state-disabled');
            $(input).children('button').prop('disabled', true);
            $(input).addClass('k-state-disabled');
        }
        EnableComponent($(input).children('button'), enable, input);
    }
    else if ($(input).hasClass('tzGridView')) {
        if (enable) {
            $(input).removeAttr('disabled');
            $(input).removeClass('k-state-disabled');

            //$(input).children('.k-grid-content').children('table').addClass('k-selectable');
            //$(input).children('.k-grid-toolbar').children('button').removeAttr('disabled');
        }
        else {
            $(input).attr('disabled', 'disabled');
            $(input).addClass('k-state-disabled');

            //$(input).children('.k-grid-content').children('table').removeClass('k-selectable');
            //$(input).children('.k-grid-toolbar').children('button').prop('disabled', true);
        }
    }
    else if ($(input).is('fieldset')) {
        if (enable) {
            //$(input).css('border-color', 'black');
            if ($(input)[0].style.borderColor == "") {
                $(input).removeClass('disable-color');
                $(input).addClass('default-color');
            }
            $(input).children('legend').css('color', 'black');
        }
        else {
            //$(input).css('border-color', 'silver');
            if ($(input)[0].style.borderColor == "") {
                $(input).removeClass('default-color');
                $(input).addClass('disable-color');
            }
            $(input).children('legend').css('color', 'silver');
        }
        $(input).children().each(function (index, child) {
            if ($(child).is('.k-dropdown')) {
                EnableComponent($(child).children('select'), enable, input);
            }
            else if ($(child).is('.k-datepicker,.k-timepicker')) {
                EnableComponent($(child).children('.k-picker-wrap').children('input'), enable, input);
            }
            else if ($(child).is('div[for]')) {
                EnableComponent($(child).children("#" + $(child).attr('for')), enable, input);
            }
            else {
                EnableComponent(child, enable, input);
            }
        });
    }
    else if ($(input).is('div')) {
        if (enable) {
            $(input).css('border-color', 'black');
            $(input).children('legend').css('color', 'black');
        }
        else {
            $(input).css('border-color', 'silver');
            $(input).children('legend').css('color', 'silver');
        }
        $(input).children().each(function (index, child) {
            if ($(child).is('.k-dropdown')) {
                EnableComponent($(child).children('select'), enable, input);
            }
            else if ($(child).is('.k-datepicker,.k-timepicker')) {
                EnableComponent($(child).children('.k-picker-wrap').children('input'), enable, input);
            }
            else if ($(child).is('div[for]')) {
                EnableComponent($(child).children("#" + $(child).attr('for')), enable, input);
            }
            else {
                EnableComponent(child, enable, input);
            }
        });
    }
    else if ($(input).is('select')) {
        //$(input).data('kendoDropDownList').enable(enable);
        var ComponentItem = $(input).data('kendoDropDownList')
        if (ComponentItem != undefined) {
            ComponentItem.enable(enable);
        }
        if (enable) {
            $(input).parent('span').removeClass('k-state-disabled');
        }
        else {
            $(input).parent('span').addClass('k-state-disabled');
        }

    }
    if ($(input).is('.tbsDataGridBtn-Del')) {
        if (enable) {
            $(input).removeClass('k-state-disabled');
        }
        else {
            $(input).addClass('k-state-disabled');
        }
    }
    if (!EqualChildParentFlag)
        GroupEndLogger("");
}


function getParameterByName(name, url) {

    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


var elementsAndState = [];
function ShowComponents(elementsID, show, raiser) {

    $.each(elementsID.split(","), function (index, elementID) {
        ShowComponent($('#' + elementID), show, raiser);
    });
    //elementsAndState.push({ elements: elementsID, states: show, raiser:raiser });
    //window.setTimeout(setPriorityOfShowHide, 10, elementsAndState);
}
function setPriorityOfShowHide(elementsWithState) {
    elementsWithState.sort(function (a, b) {
        var a1 = a.states, b1 = b.states;
        if (a1 == b1) return 0;
        return a1 > b1 ? 1 : -1;
    });
    $.each(elementsWithState, function (key, value) {
        $.each(value.elements.split(","), function (index, elementID) {
            ShowComponent($('#' + elementID), value.states, value.raiser);
        });
    });
    elementsAndState.splice(0, elementsWithState.length);
}
ComponentVisibiltyRepository = [];
function ShowComponent(input, show, raiser) {

    //if (firstReloadFlag == 1) {
    //firstReloadFlag => waiting for components initilizing
    ComponentVisibiltyRepository.push({
        key: input,
        value: show,
        raiser: raiser
    });
    //} else {

    ShowElementLogger(raiser, input, show);
    if (show)
        $(input).removeClass('tzInVisible');

    if ($(input).is('input.tzTimePicker,input.k-textbox,textarea.k-textbox,div.display-label,button,fieldset,div.tzLookup,a,img,ul.tzCheckListBox,audio.tzPlayer,input.tzFileUpload,.tzFileUpload.input-group')) {
        if (show)
            $(input).show();
        else
            $(input).hide();
    }
    else if ($(input).is("input[type='checkbox'],input[type='radio']")) {
        if (show) {
            $(input).parent().show();
        }
        else {
            $(input).parent().hide();
        }
    }
    else if ($(input).hasClass('tzGridView')) {
        if (show)
            $(input).show();
        else
            $(input).hide();
    }
    else if ($(input).parent().is('.k-picker-wrap')) {
        if (show)
            $(input).parent().parent().show();
        else
            $(input).parent().parent().hide();
    }
    else if ($(input).hasClass('tzTabStrip')) {
        if (show)
            $(input).show();
        else
            $(input).hide();
    }
    else if ($(input).is('select')) {
        var ComponentItem = $(input).getKendoDropDownList();
        //if (ComponentItem == undefined) {
        //    ComponentItem = $(input).kendoDropDownList();
        //}
        if (ComponentItem != undefined) {
            if (show)
                ComponentItem.wrapper.show();
            else
                ComponentItem.wrapper.hide();
        }

    }
    else if ($(input).is(".input-group")) {
        if (show)
            $(input).first().css('display', 'table');
        else
            $(input).first().css('display', 'none');
    }
    //}    
    if (!show) {
        let isParentEffect = true;
        $(input).parents('div.row').first().find('*:not(div)').each((index, item) => {
            if ($(item).css('display') != 'none') {
                isParentEffect = false;
                return false;
            }
        });

        if (isParentEffect) {
            $(input).parents('div.row').first().css('display', 'none');
        }
    }
    else {
        $(input).parents('div.row').first().css('display', 'block');
    }
}

function getImageBase64Source(element, source, isExternalLink) {
    if (source == "" || source == undefined)
        return;

    $.ajax({
        type: "POST",
        url: tbsRootURL + "Form/GetFileDataExternalLink",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        contentType: "application/json",
        dataType: "json",
        async: true,
        data: JSON.stringify({
            source: source
            , isExternalLink: isExternalLink
        }),
        success: function (result) {
            $(element)[0].src = source;
            $($(element).parent().children()[0]).css('z-index', "0");
            ImageViewer($(element));

        }
    });

}



function ClearComponents(elementsID, clear) {
    $.each(elementsID.split(","), function (index, elementID) {
        ClearComponent($('#' + elementID), clear);
    });
}
function ClearComponent(input, clear) {
    if (!clear)
        return;

    else if ($(input).is('input.k-textbox,textarea.k-textbox,input.tzTimePicker')) {
        $(input).val('');
    }
    else if ($(input).is("input[type='checkbox'],input[type='radio']")) {
        $(input).removeAttr('checked');
        $(input).change();

    }
    else if ($(input).parent().parent().is('.k-datepicker')) {
        if ($(input).data('kendoDatePicker') == undefined)
            $(input).val('');
        else
            $(input).data('kendoDatePicker').value('');
    }
    else if ($(input).hasClass('tzGridView')) {
        if ($(input).getKendoGrid() != undefined)
            $(input).getKendoGrid().clearSelection();
    }
    else if ($(input).parent().parent().is('.k-timepicker')) {
        if ($(input).data('kendoTimePicker') == undefined)
            $(input).val('');
        else
            $(input).data('kendoTimePicker').value('');
    }
    else if ($(input).is('div.tzLookup')) {
        $(input).children('input').val('');
    }
    else if ($(input).is('fieldset')) {
        $(input).children().each(function (index, clear) {
            if ($(clear).is('.k-dropdown')) {
                ClearComponent($(clear).children('select'), clear);
            }
            else if ($(clear).is('.k-datepicker,.k-timepicker')) {
                ClearComponent($(clear).children('.k-picker-wrap').children('input'), clear);
            }
            else if ($(clear).is('div[for]')) {
                ClearComponent($(clear).children("#" + $(clear).attr('for')), clear);
            }
            else {
                ClearComponent(clear, clear);
            }
        });
    }
    else if ($(input).is('select')) {
        if ($(input).data('kendoDropDownList') != undefined) {
            $(input).data('kendoDropDownList').select(0);
            $(input).data('kendoDropDownList').$angular_scope.cmbReferal_model = 0;
            // $(input).data('kendoDropDownList').$angular_scope.$apply();
        }
    }
    else if ($(input).is('ul.tzCheckListBox')) {
        $(input).children('li').children('label').children('input.tzCheckListCheckBox').removeAttr('checked');
    }
    else if ($(input).is('div.tzFileUpload')) {
        $(input).children('input').val('');
        var element = $(input)
        $(element).attr('FileID', "-1");
        $(element).attr('value', "-1#");
        $(element).children('.input-group-btn').children('a.btn.btn-default').hide();
        $(element).children('input.form-control').val('').clone(true);
        $(element).children('input').attr('value', '');
        $(element).children('input').attr("placeholder", "");
        $(element).children('.input-group-btn').children("a.btn.btn-default").attr('href', '#');
        if ($(element).attr('customonchange') != undefined)
            eval($(element).attr('customonchange').replace('this', 'element'));
        if ($(element).attr('required') == "required") {
            $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").children().attr('required', 'required');
            $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html("<input onchange='fileUploadChange(this)' type='file' required='required'>")
        }
        else {
            $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html('');
            $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html("<input onchange='fileUploadChange(this)' type='file'>")
        }

        $(element).children('input').removeClass("fileUploaded");
        //$(input).find('a.btn.btn-default.btn-remove.glyphicon.glyphicon-remove').click();
    }
    //$(input).trigger('change');
}

// fix bug of kendo in hidden tabs
function KendoGridResizeInThisElement(thisEleent) {
    var gridItems = $(thisEleent).find('.k-grid');
    if (gridItems != undefined && gridItems != []) {
        gridItems.each

        $.each(gridItems, function (index, Element) {
            var gridObjects = $(Element).getKendoGrid();
            if (gridObjects != undefined) {
                gridObjects.resize();
            }
        });



    }
}

function DisableDiv_Toggle(boolForceSatus) {
    if (boolForceSatus != undefined) {
        if (boolForceSatus == true) {
            $(".DisableDiv").show();
            console.log("$(.DisableDiv).show()");
        }
        else {
            $(".DisableDiv").hide();
            console.log("$(.DisableDiv).hide()");
        }
    }
    else {
        $(".DisableDiv").toggle();
        console.log("$(.DisableDiv).toggle()");
    }

}

function GenerateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

function SetPublicVariable(variableName, variableValue) {
    $.ajax({
        type: "POST",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        url: tbsRootURL + "Form/SetPublicVariables",
        contentType: "application/json",
        dataType: "json",
        async: false,
        data: JSON.stringify({
            variableName: variableName,
            variableValue: variableValue
        }),
        success: function (result) {
            if (result.success != undefined && (!result.success || result.Errors)) {
                if (!result.success)
                    ShowNotification('error', result.error);

                if (result.Errors)
                    ErrorHandler(result);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ShowNotification('error', errorThrown);
        }
    });
}

function GetAggregateValue(aggrType, AggrColumName, dataGridControlId) {
    var result;
    try {

        var agg = $('#' + dataGridControlId).getKendoGrid().dataSource.aggregates()[AggrColumName];
        if (agg == undefined) {
            $('#' + dataGridControlId).getKendoGrid().dataSource.aggregate([
                { field: AggrColumName, aggregate: aggrType }
            ]);
            obj = $('#' + dataGridControlId).getKendoGrid().dataSource.aggregates()[AggrColumName];
            if (obj == undefined && aggrType == 'count')
                return 0;
            result = $('#' + dataGridControlId).getKendoGrid().dataSource.aggregates()[AggrColumName][aggrType];
            //akert(result);
            if (aggrType != 'concat' && result == '') {
                return "0";
            }
            return result
        }
        else {
            result = agg[aggrType];
        }
        if (result == undefined) {
            result = "";
        }
    }
    catch (err) {
        result = undefined;
    }
    if (result == undefined) {
        if (aggrType == 'count')
            return undefined;
        if (aggrType != 'concat') {
            return "0";
        }
        else {
            return "";
        }
    }
    else {
        if (aggrType != 'concat' && result == '') {
            return "0";
        }
        else {
            return result;
        }
    }
}
function SelectAllGridItems(e) {

    var grid = $(e).closest("div").parent().parent().data("kendoGrid");
    $.each(grid.tbody.find(">tr").toArray(), function (index, item) {
        item.children[0].children[0].checked = e.checked;

        //if (item.children[0].children[0].checked) { // اگر تیک اون ردیف خورده بود
        //    if (index != 0)
        //        strRes += '$'
        //    strRes += $(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')];
        //    debugger;
        //    //if (!$(item).hasClass('k-state-selected')) {
        //    //    $(item).addClass('k-state-selected');
        //    //}
        //    //$(item).attr('aria-selected', 'true');
        //}
    });
    ExecFormDatasources(grid, $(e).attr("ng-events").trimEnd(' '));
}
//#endregion Other From Behavior

//#region Save From Behavior
function GetValue(input, resultType) {
    if (input.length != undefined && $(input)[0] != undefined) {
        var strRes = "";
        if ($(input)[0].classList.contains('MultiSelectable') && $(input).hasClass('tzGridView') && input.data('kendoGrid') != undefined) { // اگر مالتی سلکت بود
            $.each(input.data('kendoGrid').tbody.find(">tr").toArray(), function (index, item) {
                if (item.children[0].children[0].checked) { // اگر تیک اون ردیف خورده بود
                    if (index != 0)
                        strRes += '$'
                    strRes += $(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')];
                    //if (!$(item).hasClass('k-state-selected')) {
                    //    $(item).addClass('k-state-selected');
                    //}
                    //$(item).attr('aria-selected', 'true');
                }
            });
            return strRes.trimEnd('$');
            //$.each($(input).getKendoGrid().select(), function (index, item) {
            //    if (index != 0)
            //        strRes += '$'
            //    strRes += $(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')];
            //});
            //return strRes;
        }
    }
    if ($(input).is('input') && ($(input).attr('type') == 'radio' || $(input).attr('type') == 'checkbox')) {
        return $(input).is(":checked");
    }
    else if ($(input).is('ul.tzCheckListBox')) {
        var ResultTrueItems = "";
        var AllInputItems = $('#' + $(input).attr('id') + '> li > label > input');
        if (AllInputItems.length > 0) {
            var parentId = $(AllInputItems[0]).parents('ul')[0].id;

            $.each(AllInputItems, function (index, item) {
                if ($(item).is(":checked") && $(item).attr('id') != parentId) {
                    ResultTrueItems += $(item).attr('id') + ",";
                }
            })
            if (ResultTrueItems != "") {
                ResultTrueItems = ResultTrueItems.substring(0, ResultTrueItems.length - 1);
            }
        }
        //var parentId = AllInputItems[0].offsetParent.id;

        return ResultTrueItems;
    }
    else if ($(input).is('select')) {
        if ($(input).val() == null || $(input).val() == "" || $(input).val().indexOf('undefined') >= 0) {
            if ($(input).attr('defaultvalue') != undefined && $(input).attr('defaultvalue') != '') {
                return $(input).attr('defaultvalue');
            }
            else {
                return '-1';
            }
        }
        if ($(input).val() == "")
            return '-1';
        if ($(input).val().indexOf('?') >= 0)//Load Time Value
            return '-1';
        else
            return $(input).val();
    }
    else if ($(input).hasClass('tzLookup')) {
        var val = $(input).attr('value');
        if (val == undefined)
            return "";
        if ($(input).attr('value').indexOf("#") > 0) {
            return $(input).attr('value').split("#")[0];
        }
        return $(input).attr('value');
    }
    else if ($(input).hasClass('tzGridView')) {

        strRes = "";
        var gridItem = $(input).getKendoGrid();
        if (gridItem == undefined)
            return "-1";
        var gridSelected;
        if ($(input).hasClass('MultiSelectable')) {
            gridSelected = $(input).getKendoGrid().select();
            $.each($(input).getKendoGrid().tbody.find(">tr").toArray(), function (index, item) {
                if (item.children[0].children[0].checked) { // اگر تیک اون ردیف خورده بود
                    if (index != 0)
                        strRes += '$'
                    strRes += $(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')];

                    //if (!$(item).hasClass('k-state-selected')) {
                    //    $(item).addClass('k-state-selected');
                    //}
                    //$(item).attr('aria-selected', 'true');
                }
            });


        }
        else {
            gridSelected = $(input).getKendoGrid().select();
            var strRes = "";
            if (gridSelected.length > 0) {
                $.each(gridSelected, function (index, item) {
                    if (index != 0)
                        strRes += '$'
                    //$($($(item).children()[0]).children()[0])[0].checked = true;
                    if (resultType != "" && resultType != null && resultType != undefined && resultType[0].split(':')[1] == "MultiSelectedItem") {
                        var strRes_temp = [];
                        strRes_temp.push($(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')]);
                        strRes += strRes_temp;
                    }
                    else if (resultType != "" && resultType != null && resultType != undefined && resultType[0].split(':')[1] == "RowDataString") {
                        var strRes_temp = [];
                        $.each($(item).find('span'), function (c_index, c_value) {
                            strRes_temp.push($(input).getKendoGrid().dataItem(item)[$(c_value).attr('ng-bind').split('.')[1]])
                        });
                        strRes += strRes_temp;
                    }
                    else
                        strRes += $(input).getKendoGrid().dataItem(item)[$(input).attr('keycolname')]
                })
            }
        }

        return strRes.trimEnd('$');
    }
    else if ($(input).hasClass('k-treeview')) {
        return $(input).attr('selectedvalue');
    }
    else if ($(input).hasClass('tzNumericTexbox') || $(input).hasClass('tzfloatTexbox')) {

        var DataRead = $(input).val();
        if (DataRead == undefined || DataRead == "") {
            return 0;
        }
        return DataRead.replace(/,/g, '');

    }
    else if ($(input).hasClass('tzPlayer')) {
        var DataRead = $(input).attr('FileID');
        if (DataRead == undefined || DataRead == "") {
            return 0;
        }
        return DataRead;
    }
    else if ($(input).hasClass('tzFileUpload')) {
        var DataRead = $(input).attr('FileID');
        if (DataRead == undefined || DataRead == "") {
            return "-1";
        }
        var strFileName = $(input).children('input.form-control').val();
        return DataRead + "#" + strFileName;
    }
    else if ($(input).hasClass('tz-rich-textbox')) {
        return btoa(unescape(encodeURIComponent(CKEDITOR.instances[$(input)[0].id].getData())));
        //fd.ControlValue = btoa(document.getElementById("apiRTE").ej2_instances[0].contentModule.contentPanel.innerHTML);
    }
    else
        return $(input).val();
}

function GetComponentData(input) {
    var controllerScope = angular.element(document.querySelector("[data-ng-controller='Form" + $(input).parents('form').attr('ID') + "_Controller']")).scope();
    var fd = $.extend(true, {}, controllerScope.DataValue);
    fd.ControlID = $(input).attr('id');
    fd.ControlName = $(input).attr('data-name')
    if ($(input).hasClass('tzFileUpload'))
        fd.ComponentType = "tzFileUpload";
    if ($(input).hasClass('tzLookup')) {
        if ($(input).attr('value') == undefined || $(input).attr('value') == "") {
            fd.ControlValue = "";
        }
        else if ($(input).attr('value').indexOf("#") > 0) {
            fd.ControlValue = $(input).attr('value');
        }
        else {
            fd.ControlValue = $(input).attr('value') + '#' + $(input).children('input').val();
        }
    }
    else if ($(input).hasClass('tz-rich-textbox')) {
        fd.ComponentType = "tzRichTextBoxHTML";
        fd.ControlValue = btoa(unescape(encodeURIComponent(CKEDITOR.instances[$(input)[0].id].getData())));
        //fd.ControlValue = btoa(document.getElementById("apiRTE").ej2_instances[0].contentModule.contentPanel.innerHTML);
    }

    else if ($(input).hasClass('tzComboBox')) {
        if (GetValue(input) == '-1') {
            fd.ControlValue = -1;
            fd.ControlDisplayValue = '';
        }
        else {
            fd.ControlValue = GetValue(input);
            fd.ControlDisplayValue = $($(input).getKendoDropDownList().current()).html();
        }
    }
    else {
        fd.ControlValue = GetValue(input);
    }
    return fd;
}


function dataSourceDataToTreeData(data, id, parentId) {
    var arr = Array.from(data).reduce(function (map, node) {
        map.i[node[id]] = node;
        node.items = [];
        node[parentId] === '-1' ?
            map.result.push(node) :
            map.i[node[parentId]].items.push(node);
        return map;
    }, { i: {}, result: [] }).result;

    var rv = {};
    for (var i = 0; i < arr.length; ++i)
        rv[i] = arr[i];
    rv;
    return rv;
}

function GetFormData(formID) {
    var formScope = angular.element(document.querySelector("[data-ng-controller='Form" + formID + "_Controller']")).scope();
    var formData = null;
    if (formScope != undefined) {
        formData = formScope.FormSave();
        formData.FormId = formID;
        formData.ISUpdateed = true;
        formData.IsPersistable = formScope.IsPersistable;
        $.each(formData.CheckListBoxItems, function (index, item) {
            item.ControlValue = GetValue($('ul#' + item.ControlID)).toString().replace(/,/g, "$");
        });
        $.each(formData.DataGrids, function (index, dataGridElement) {
            $.each(dataGridElement.DataGridItems, function (index, dataGridItem) {
                if (dataGridItem.IsNew) {
                    dataGridItem.PKFormId = -1;
                    dataGridItem.ISUpdateed = false;
                }
            });
        });

    }
    return formData;
}

function FormValidate(validationItemIDsList, CallBackFuncToSaveForm, BtnSender) {
    if (validationItemIDsList.length == 0) {
        CallBackFuncToSaveForm(BtnSender);
        return;
    }
    while (validationItemIDsList[0] == "") {
        validationItemIDsList.shift();
        if (validationItemIDsList.length == 0) {
            CallBackFuncToSaveForm(BtnSender);
            return;
        }
    }
    var validationItemArr = validationItemIDsList[0].split('$');
    validationItemIDsList.shift();
    var formScope = angular.element(document.querySelector("[data-ng-controller='Form" + validationItemArr[0] + "_Controller']")).scope();
    if (formScope != undefined) {
        var validateTemp = formScope["FormValidate"](validationItemArr[1], function () { FormValidate(validationItemIDsList, CallBackFuncToSaveForm, BtnSender); });
        if (!validateTemp)
            formHasError = true;
    }
    else {
        FormValidate(validationItemIDsList, CallBackFuncToSaveForm, BtnSender);
    }
}

function FormMandatory(RemainingFormItemsIdList, CallBackFuncToSaveForm, BtnSender) {
    formHasError = false;
    if (RemainingFormItemsIdList == undefined || RemainingFormItemsIdList.length == 0) {
        var ValidationItems = $(BtnSender).attr('ValidationsIDList');
        var ValidationItemsList = [];
        if (ValidationItems != undefined && ValidationItems != "")
            ValidationItemsList = ValidationItems.split(',');
        //TempValidationItemsList = ValidationItemsList.slice();
        //FormValidate(FomrItemsIdList, ValidationItemsList, TempValidationItemsList, CallBackFuncToSaveForm, BtnSender);
        FormValidate(ValidationItemsList, CallBackFuncToSaveForm, BtnSender);
    }
    else {
        var CheckResult = FormCheckRequiredFields(RemainingFormItemsIdList[0]);
        if (CheckResult) {
            RemainingFormItemsIdList.shift();
            FormMandatory(RemainingFormItemsIdList, CallBackFuncToSaveForm, BtnSender);
        }
    }
}
function FormCheckRequiredFields(FormID) {
    //var CheckResult = $('#' + FormID)[0].checkValidity();
    var validator = $('#' + FormID).getKendoValidator();
    console.log(validator);
    var CheckResult;
    try {
        CheckResult = validator.validate();
    } catch (e) {
        CheckResult = $('form[id="' + FormID + '"]')[0].checkValidity();
    }
    //CheckResult = $('#' + FormID)[0].checkValidity();
    //var CheckResult = false;
    if (!CheckResult) {

        var pattern_error = "";
        $('input.tzTextBox[aria-invalid=true]').each(function (inx, item) { pattern_error += $(item).attr('validationMessage') != undefined ? ("<p>" + $(item).attr('validationMessage') + "</p>") : "" })

        formHasError = true;
        //validator.errors().forEach(function (err , index) { pattern_error += "<p>" + err +"</p>"})
        ShowNotification('error', '<p>لطفا فیلد های دارای حاشیه ی قرمز رنگ را پر کنید</p>' + pattern_error);

        $("input[aria-invalid='true'][required='required'][type='file']").parent().parent().parent().addClass('k-invalid');

        //var RequieredItems = $("[required='required']");
        //RequieredItems.css("border", "1px solid red");
        //$("select[required='required']").parent().css("border", "1px solid red");

        //var NonRequieredItems = $("[nonRequired]");
        //RequieredItems.css({ "border-color": "#c5c5c5" });
        //$("select[nonRequired]").parent().css({"border-color":"#c5c5c5"});
    }
    //else if (validator.validate()) {
    //    ShowNotification('error', 'OKKKKKKKKKKKK');
    //}
    //if (!CheckResult) {
    //    ShowNotification('error', 'لطفا فیلد های دارای حاشیه ی قرمز رنگ را پر کنید');
    //}
    return CheckResult;
}

//#endregion Save From Behavior

//#endregion Form General

//#region DataSource
function ExecFormDatasourcesByElementId(elementId, eventsName) {

    var element = $('#' + elementId);
    ExecFormDatasources(element, eventsName);
}

var firstReloadFlag = 1;
$(".InitilizingDivSpinner").hide();


function ShowInitilizingDivSpinner() {
    var url = window.location.pathname.split("/");
    if (url[url.length - 1] == "LookUp")
        return;

    if (firstReloadFlag == 1) {
        $(".InitilizingDivSpinner").show();
    }

}

var elementxxxxxxxxxx = "";

function enableLoadingButton(element) {
    $(element).text('');
    $(element).html('<i class="fa fa-refresh fa-spin" style="font-weight: bold;"></i>');
    $(element).css('cursor', 'not-allowed');
    $(element).attr("disabled", "disabled");
}
function disableLoadingButton(element, btnText) {
    $(element).html('');
    $(element).text(btnText);
    $(element).removeAttr("disabled", "disabled");
    $(element).css('cursor', 'pointer');
}


function ExecFormDatasources(element, eventsName) {

    if ($(element).hasClass('tzButton')) {
        var btnText = $(element).text();
        enableLoadingButton(element)
    }

    setTimeout(function () {
        try {

            ShowInitilizingDivSpinner();

            var ItemDataName = $(element).attr('data-Name');
            var ccElementAttribute;
            if (ItemDataName == undefined) {

                //ccElementAttribute = ItemDataName + '_Option'

                ItemDataName = 'frm' + element;
            }
            //console.log("ExecFormDatasources : DS " + eventsName + " Called. Caller: " + ItemDataName);
            ShowDataSourcesLogger(ItemDataName, eventsName);
        }
        catch (ex) { }
        var controller;
        if (eventsName == "" || eventsName == null)
            return;
        if (element["$id"] != undefined) {
            controller = element;
        }
        else if (!isNaN(parseInt(element))) {
            controller = angular.element(document.querySelector("[data-ng-controller='Form" + element + "_Controller']")).scope();
        }
        else {
            controller = angular.element(document.querySelector("[data-ng-controller='Form" + $(element).parents('form').attr('ID') + "_Controller']")).scope();
            if (controller == undefined)
                controller = angular.element(document.querySelector("[data-ng-controller='Form" + $(element.element).parents('form').attr('ID') + "_Controller']")).scope();
        }

        ExecDataSourceCount = 0;
        ExecDataSourceCounter = 0;

        eventsName.split(',').forEach((el) => {
            if ($(controller).attr(el) != undefined) {
                ExecDataSourceCount++;
            };
        })
        $.each(eventsName.split(","), function (index, dsName) {
            if ($(controller).attr(dsName) != undefined) {
                var ccelement = $(controller).attr(dsName).select;
                $(ccelement).parent().find('.k-i-arrow-s').addClass('k-loading');
                if (firstReloadFlag != 1 && $(ccelement).is('select') && $(ccelement).val() != "")
                    $($(controller).attr(dsName).select).val("")

                // Check exportToExcel                
                //$(element).addClass('tzExportToExcel');
                $(controller).attr(dsName).options.IsExportToExcel = false;
                var exportToExcel = $(element).hasClass('tzExportToExcel');
                if (exportToExcel)
                    $(controller).attr(dsName).options.IsExportToExcel = true;

                var hasCaptcha = $(element).hasClass('tzHasCaptcha');
                $(controller).attr(dsName).options.elementId = $(element).attr('id');

                if (hasCaptcha) {
                    $(controller).attr(dsName).options.hasCaptcha = true
                    $(controller).attr(dsName).options.elementId = $(element[1]).attr('id');
                }

                $(controller).attr(dsName).options.Exec();

                //elementxxxxxxxxxx = $($(controller).attr(dsName).select).parent();
                //waitForDataSourceLoading(elementxxxxxxxxxx);
                //ajaxRequestsState.push({ 'key': dsName, 'value': "doing" });

            }
        });
        //$(".InitilizingDivSpinner").hide();
        if ($(element).hasClass('tzButton'))
            disableLoadingButton(element, btnText)
        if ($(element).attr('CloseParent')) {
            window.close();
        }
    }, 0);
}



function waitForDataSourceLoading(el) {

    if ($(el).parent().find('.k-i-arrow-s').hasClass("k-loading")) {
        window.setTimeout(waitForDataSourceLoading, 2000, el);
    }
    else {
    }
}


function waitForElement() {
    if (typeof someVariable !== "undefined") {
        //variable exists, do what you want
    }
    else {
        setTimeout(waitForElement, 250);
    }
}



function incrementAjaxCountInProcess() {
    AjaxCountInProcess++;
}

function decrementAjaxCountInProcess() {
    AjaxCountInProcess--;
    //if(AjaxCountInProcess == 0)
    //    alert("no ajax in quee!!!");
}

$(document).ready(function () {
    $('input.tzNumericTexbox').each(function (index, element) {
        $(element).on('paste', function (event) {
            if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) {
                event.preventDefault();
            }
        });
        $(element).on("keypress", function (event) {
            if (event.which < 48 || event.which > 58) {
                return false;
            }
        });
    })


    $('app-richTxtBox').each(function (index, element) {
        document.getElementById('apiRTE_rte-edit-view').innerHTML = $(element).attr("htmlvalue");
    })

})


var AjaxCountInProcess = 0;
var formHasError = false;

var MyIntCounter = 1;
var ExecDataSourceCount = 0;
var ExecDataSourceCounter = 0;
function ExecDataSource(ds) {
    try {
        //$(".InitilizingDivSpinner").show();
        //$("#" + $("[k-options='" + ds.Name + '_Option' + "']").attr('id')).parent().find('.k-i-arrow-s').addClass('k-loading')

        if (ds.IsExportToExcel) {
            ExportToExcelDataSource(ds);
            return;
        }

        incrementAjaxCountInProcess();

        var ParamsDic = [];

        $.each(ds.Params, function (index, item) {

            if (ds.Name == "dsGetResultConcat" && (ds.FormID == "2067" || ds.FormID == "2065" || ds.FormID == "2064" || ds.FormID == "2066")) {
                var gridId = "4820824516681132083";
                if (ds.FormID == "2065")
                    gridId = "5670315194150751712";
                else if (ds.FormID == "2064")
                    gridId = "4957258770284908532";
                else if (ds.FormID == "2066")
                    gridId = "5393630006156051986";

                var strConcat = "";
                if ($("#" + gridId).getKendoGrid().dataSource.options.data.length > 0 && $("#" + gridId).getKendoGrid().dataSource.options.data[0]['Col_4688305674861711543'] != "")
                    if ($("#" + gridId).getKendoGrid().dataSource.options.data[0]['Col_4688305674861711543'] == "تایید شکایت")
                        strConcat = "1¢تاييد شکايت";
                    else
                        strConcat = "2¢عدم تاييد شکايت";
                //$.each($('#4820824516681132083').getKendoGrid().select().children(), function (index, value) { strConcat.push(value.innerText) });
                ParamsDic.push({ 'key': item, 'value': strConcat });
            }
            else
                ParamsDic.push({ 'key': item, 'value': GetValue($("form#" + ds.FormID + " [data-Name='" + item + "']"), ds.ResultType) });
        });

        var formParams = $('#Form' + ds.FormID + '_Property').val();
        MyIntCounter = MyIntCounter + 1;
        var ThisFunctionID = MyIntCounter;

        let execElementId = ds.elementId;

        console.log("ExecDataSource : AjaxCall Start ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic));
        $.ajax({
            type: "POST",
            headers: {
                'RequestVerificationToken': $('#m_RequestVerificationToken').val(),
                'RequestCaptchaText': ds.hasCaptcha ? $('#' + execElementId + 'CaptchaText').val() : '',
                'RequestCaptchaGuid': ds.hasCaptcha ? $('#' + execElementId + 'CaptchaText').attr('data-guid') : '',
                'RequestExecElementId': execElementId
            },
            url: tbsRootURL + "Form/ExecDataSource",
            contentType: "application/json",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                dsName: ds.Name,
                formParams: formParams,
                Params: ParamsDic
            }),
            success: function (result) {
                if (ds.hasCaptcha == true) {
                    getCaptcha(execElementId);
                }

                if (ds.HasResultMessage) {
                    if (result[0]['ResultType'] != undefined && result[0]['ResultMessage'] != undefined) {

                        if (result[0]['ResultType'] == '1') {
                            ShowNotification('success', result[0]['ResultMessage']);
                        }
                        else {
                            ShowNotification('error', result[0]['ResultMessage']);
                        }
                    }
                }

                if (result.Errors) {
                    ErrorHandler(result);
                }
                else {

                    console.log("ExecDataSource : AjaxCall endSuccess ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic));
                    var controller = angular.element(document.querySelector("[data-ng-controller='Form" + ds.FormID + "_Controller']")).scope();
                    //$(controller).attr(ds.Name).options.data = result;

                    //controller.$apply(function () {
                    //    $(controller).attr(ds.Name).data([]);
                    //});

                    $(controller).attr(ds.Name).data(result);

                    //var richTextBox = document.getElementsByClassName("tz-rich-textbox")[0];
                    //var apiRTE_rte_edit_view = document.getElementById('apiRTE_rte-edit-view');

                    //if (apiRTE_rte_edit_view != null) {
                    //    if (angular.isDefined(richTextBox)) {
                    //        document.getElementById('apiRTE_rte-edit-view').innerHTML = $(richTextBox).attr('value');
                    //    }
                    //    else {
                    //        document.getElementById('apiRTE_rte-edit-view').innerHTML = '';
                    //    }
                    //}


                    $("form#" + ds.FormID + " :input").each(function () {
                        var input = $(this); // This is the jquery object of the input, do what you will
                        if (input.attr("data-ng-value") != null && input.attr("data-ng-value") != undefined)
                            if (input.attr("data-ng-value").indexOf(ds.Name) >= 0) {
                                if (input.attr('value') != undefined) {
                                    input.val(input.attr('value'));
                                    //if (input.hasClass('tz-rich-textbox')) {
                                    //    var editor = input.data("kendoEditor");
                                    //    editor.value($.text($.parseHTML(input.attr('value'))[0]));
                                    //}

                                }
                            }
                    });

                    if (controller.$root.$$phase != '$apply' && controller.$root.$$phase != '$digest') {
                        //controller.$digest();
                        ExecDataSourceCounter++;
                        if (ExecDataSourceCount == ExecDataSourceCounter)
                            controller.$digest();
                    }

                    //var richTextSelector = $('.tz-rich-textbox');
                    for (var i = 0; i < $('.tz-rich-textbox').length; i++) {
                        var richText = $('#' + $('.tz-rich-textbox')[i].id);
                        try {
                            // This is the jquery object of the input, do what you will
                            if (richText.attr("data-ng-value") != null && richText.attr("data-ng-value") != undefined)
                                if (richText.attr("data-ng-value").indexOf(ds.Name) >= 0) {
                                    if (richText.attr('value') != undefined) {
                                        CKEDITOR.instances[richText.attr('id')].setData(richText.attr('value'));
                                    }
                                }
                        } catch (e) {

                        }

                    }

                    ////TBS_TabControl                    
                    var tbsTabControls = $('.tzTabStrip');
                    for (var i = 0; i < tbsTabControls.length; i++) {
                        tabDsName = $('#' + tbsTabControls[i].id).attr('hidden-index-bindingDS');
                        tabFieldName = $('#' + tbsTabControls[i].id).attr('hidden-index-bindingField');

                        if (tabDsName == ds.Name) {

                            tabsDsData = $(controller).attr(ds.Name).data();
                            actionTabs = tabsDsData.map(s => s[tabFieldName]);

                            if (actionTabs.length > 0) {

                                let tabChilds = $('#' + tbsTabControls[i].id).find('ul.nav-tabs > li');

                                controlID = tbsTabControls[i].id;

                                for (var iindex = 1; iindex <= tabChilds.length; iindex++) {

                                    if (actionTabs[0].split('$').filter(x => x == iindex).length > 0) {
                                        $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ')').hide();
                                        tabcontentId = $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ') a').attr('href');
                                        $(tabcontentId).removeClass('Active in');
                                    }
                                    else {
                                        $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ')').show();
                                        tabcontentId = $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ') a').attr('href');
                                        if (!($(tabcontentId).hasClass('Active'))) {
                                            $(tabcontentId).addClass('Active in');
                                        }
                                    }
                                }
                            }
                        }
                    }

                    ////TBS_Gauge Update
                    var gaugeSelector = $('.tz-gaugeChart');
                    for (var i = 0; i < gaugeSelector.length; i++) {
                        gaugeValue = $('#' + gaugeSelector[i].id).attr('value');
                        $('#' + gaugeSelector[i].id).jqxGauge('value', (gaugeValue * 1));
                    }

                    ////TBS_LineChart Update
                    var lineChartSelector = $('.tz-lineChart');
                    for (var i = 0; i < lineChartSelector.length; i++) {
                        let chartItem = $('#' + lineChartSelector[i].id);
                        let displayText = '';
                        let valueField = '';
                        let title = '';
                        let chartType = '';
                        let colorField = '';
                        let chartColumnsColor = [];
                        let chartsData = [];

                        if (chartItem.attr("data-ng-value").indexOf(ds.Name) > -1) {
                            displayText = chartItem.attr('text-field');
                            valueField = chartItem.attr('value-field');
                            title = chartItem.attr('title');
                            chartType = chartItem.attr('chart-type').toLowerCase();
                            colorField = chartItem.attr('color-field');
                            chartsData = $(controller).attr(ds.Name).data();
                            chartColumnsColor = chartsData.map(s => s[colorField]);
                            let schemeName = 'scheme0' + (++i);
                            //$.jqx._jqxChart.prototype.colorSchemes.push({ name: schemeName, colors: chartColumnsColor });
                            $.jqx._jqxChart.prototype.colorSchemes.filter(s => s.name == schemeName)[0].colors = chartColumnsColor;
                            var chartSettings = chartSettingsMapper(chartItem.attr('id'), chartType, title, chartsData, displayText, valueField, schemeName);

                            setTimeout(function () {
                                chartItem.jqxChart(chartSettings);
                                $("text:contains(www.jqwidgets.com)").css('display', 'none');
                            }, 10);
                        }
                    }

                    //controller.$apply(function () {
                    //    $(controller).attr(ds.Name).data(result);
                    //    //$(controller).attr(ds.Name).options.data = result;
                    //});

                    //$(controller).attr(ds.Name).data(result);
                    //if (!(controller.$$phase))
                    //    controller.$digest();


                }

                //$('#5473661419023344718').parent().find('.k-i-arrow-s').addClass('k-loading')

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (ds.hasCaptcha == true) {
                    getCaptcha(execElementId);
                }

                if (XMLHttpRequest.status == 426) {
                    ErrorHandler(XMLHttpRequest.status);
                }
                else {
                    ShowNotification('error', errorThrown);
                }

                console.log("ExecDataSource : AjaxCall endError ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic));
                //ShowNotification('error', errorThrown);
            },
            complete: function (data) {
                decrementAjaxCountInProcess();
                //A function to be called when the request finishes 
                // (after success and error callbacks are executed). 
            }


        });
        //$(".InitilizingDivSpinner").hide();
    }
    catch (ex) {
        console.log(ex.message);
        //if loading div is in show,hide it
        //if ($(".InitilizingDivSpinner").css('display') != 'none' || $(".InitilizingDivSpinner").css("visibility") != "hidden") {
        //    $(".InitilizingDivSpinner").hide();
        //}
    }

}

function ExportToExcelDataSource(ds) {
    try {
        incrementAjaxCountInProcess();

        var ParamsDic = [];

        $.each(ds.Params, function (index, item) {

            if (ds.Name == "dsGetResultConcat" && (ds.FormID == "2067" || ds.FormID == "2065" || ds.FormID == "2064" || ds.FormID == "2066")) {
                var gridId = "4820824516681132083";
                if (ds.FormID == "2065")
                    gridId = "5670315194150751712";
                else if (ds.FormID == "2064")
                    gridId = "4957258770284908532";
                else if (ds.FormID == "2066")
                    gridId = "5393630006156051986";

                var strConcat = "";
                if ($("#" + gridId).getKendoGrid().dataSource.options.data.length > 0 && $("#" + gridId).getKendoGrid().dataSource.options.data[0]['Col_4688305674861711543'] != "")
                    if ($("#" + gridId).getKendoGrid().dataSource.options.data[0]['Col_4688305674861711543'] == "تایید شکایت")
                        strConcat = "1¢تاييد شکايت";
                    else
                        strConcat = "2¢عدم تاييد شکايت";
                //$.each($('#4820824516681132083').getKendoGrid().select().children(), function (index, value) { strConcat.push(value.innerText) });
                ParamsDic.push({ 'key': item, 'value': strConcat });
            }
            else
                ParamsDic.push({ 'key': item, 'value': GetValue($("form#" + ds.FormID + " [data-Name='" + item + "']"), ds.ResultType) });
        });

        var formParams = $('#Form' + ds.FormID + '_Property').val();
        MyIntCounter = MyIntCounter + 1;
        var ThisFunctionID = MyIntCounter;

        let execElementId = ds.elementId;

        console.log("ExportExcelDataSource : AjaxCall Start ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic));

        $.ajax({
            type: "POST",
            headers: {
                'RequestVerificationToken': $('#m_RequestVerificationToken').val(),
                'RequestCaptchaText': ds.hasCaptcha ? $('#' + execElementId + 'CaptchaText').val() : '',
                'RequestCaptchaGuid': ds.hasCaptcha ? $('#' + execElementId + 'CaptchaText').attr('data-guid') : '',
                'RequestExecElementId': execElementId
            },
            url: tbsRootURL + "Form/ExportExcelDataSource",
            contentType: "application/json",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                dsName: ds.Name
                , formParams: formParams
                , Params: ParamsDic
            }),
            success: function (result) {

                if (result.Errors) {
                    ErrorHandler(result);
                }
                else {

                    result = result[0];

                    console.log("ExportExcelDataSource : AjaxCall endSuccess ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic)
                        + " FileId : " + result.ControlValue);

                    const url = window.location.href.match(/^.*\//)[0] + "Attachment/DownloadAttachment?FileId=" + result.ControlValue;
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;

                    a.download = result.NamePersist;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);

                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("ExecDataSource : AjaxCall endError ID : " + ThisFunctionID + " ds.Name : " + ds.Name + " ParamsDic : " + JSON.stringify(ParamsDic));
                ShowNotification('error', errorThrown);
            },
            complete: function (data) {
                decrementAjaxCountInProcess();
                //A function to be called when the request finishes 
                // (after success and error callbacks are executed). 
            }


        });
        //$(".InitilizingDivSpinner").hide();
    }
    catch (ex) {
        console.log(ex.message);
        //if loading div is in show,hide it
        //if ($(".InitilizingDivSpinner").css('display') != 'none' || $(".InitilizingDivSpinner").css("visibility") != "hidden") {
        //    $(".InitilizingDivSpinner").hide();
        //}
    }

}

//#region tzCheckListBox
function onSelectedAllCheckList(el) {
    var elementId = el.offsetParent.id;
    var elementIsChecked = $(el).prop('checked');
    $(`.chl_${elementId}`).each(function () {
        if ($(this).prop('checked') != elementIsChecked)
            $(this).prop('checked', elementIsChecked);
    });
}
//#endregion tzCheckListBox

function ExecDataGridDataSource(ds) {

    incrementAjaxCountInProcess();
    //var ParamsDic = new Array();
    //$.each(ds.Params, function (index, item) {
    //    ParamsDic.push({ 'key': item, 'value': GetValue($("[data-Name='" + item + "']")) });
    //});
    var formParams = $('#Form' + ds.FormID + '_Property').val();
    $.ajax({
        type: "POST",
        url: tbsRootURL + "Form/ExecDGDataSource",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        contentType: "application/json",
        dataType: "json",
        async: true,
        data: JSON.stringify({
            dgID: ds.DataGridID
            , bindingFormID: ds.BindingFormID
            , formParams: formParams
        }),
        success: function (result) {
            if (result.Errors) {
                ErrorHandler(result);
            }
            else {
                //ds.data = result;
                $.each(result, function (index, dgFormData) {
                    dgFormData.IsNew = false;
                    ReplyDataGrid(ds.FormID, ds.DataGridID, dgFormData);
                });
                if (!(angular.element(document.querySelector("[data-ng-controller='Form" + ds.FormID + "_Controller']")).scope().$$phase))
                    angular.element(document.querySelector("[data-ng-controller='Form" + ds.FormID + "_Controller']")).scope().$digest();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ShowNotification('error', errorThrown);
        },
        complete: function (data) {
            decrementAjaxCountInProcess();
            //A function to be called when the request finishes 
            // (after success and error callbacks are executed). 
        }
    });
}

//#endregion DataSource

//#region Grids
function DataGrid_OnClick(sender) {
    var gridElement = $(sender).parents('.tzDataGrid').getKendoGrid();
    var senderFormID = $(sender).parents('form').attr('ID');
    var senderID = $(sender).parents('.tzDataGrid').attr('ID');
    var senderName = $(sender).parents('.tzDataGrid').attr('data-name');
    var controller = angular.element(document.querySelector("[data-ng-controller='Form" + senderFormID + "_Controller']")).scope();
    var layoutID = -1;
    if ($(sender).parents('.tzDataGrid').attr('ViewLayoutID') != undefined)
        layoutID = $(sender).parents('.tzDataGrid').attr('ViewLayoutID');

    if ($(sender).hasClass('tbsDataGridBtn-Del')) {
        var DeleteValidationsID = $(sender).parents('.tzDataGrid').attr('DeleteValidationIDsList');
        if (DeleteValidationsID != undefined) {
            FormValidate([DeleteValidationsID], function () {
                if (gridElement.select().length == 1) {
                    ShowNotification('inf', 'آیا مطمئن هستید؟', function () { }, function () {

                        var selectedItem = gridElement.dataItem(gridElement.select());
                        controller[senderName + 'DS'].data = $.grep(controller[senderName + 'DS'].data, function (e) {
                            return e.DataGridKey != selectedItem.DataGridKey;
                        });

                        controller.$digest();

                        setTimeout(function () {

                            controller[senderName].calcAggregate();

                            controller.$digest();

                        }, 1000);

                        var dataGridFormDataIndex = FindIndexInArrayByAttr(controller.FormData.DataGrids, "ForingComponentId", senderID);
                        var dgFormDataRecordIndex = FindIndexInArrayByAttr(controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems, "DataGridKey", selectedItem.DataGridKey);

                        if (controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex].IsNew) {
                            controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems = $.grep(controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems, function (e) {
                                return e.DataGridKey != selectedItem.DataGridKey;
                            });
                        }
                        else {
                            controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex].ISDeleted = true;
                            AddItemInArrayNoRepeat(controller.FormData.DataGrids[dataGridFormDataIndex].CopyDataGridItems, controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex], "DataGridKey");
                        }
                    });
                }
                return;
            }, sender)
        }
        else {
            if (gridElement.select().length == 1) {
                ShowNotification('inf', 'آیا مطمئن هستید؟', function () { }, function () {

                    var selectedItem = gridElement.dataItem(gridElement.select());
                    controller[senderName + 'DS'].data = $.grep(controller[senderName + 'DS'].data, function (e) {
                        return e.DataGridKey != selectedItem.DataGridKey;
                    });

                    controller.$digest();

                    setTimeout(function () {

                        controller[senderName].calcAggregate();

                        controller.$digest();

                    }, 1000);

                    var dataGridFormDataIndex = FindIndexInArrayByAttr(controller.FormData.DataGrids, "ForingComponentId", senderID);
                    var dgFormDataRecordIndex = FindIndexInArrayByAttr(controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems, "DataGridKey", selectedItem.DataGridKey);

                    if (controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex].IsNew) {
                        controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems = $.grep(controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems, function (e) {
                            return e.DataGridKey != selectedItem.DataGridKey;
                        });
                    }
                    else {
                        controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex].ISDeleted = true;
                        AddItemInArrayNoRepeat(controller.FormData.DataGrids[dataGridFormDataIndex].CopyDataGridItems, controller.FormData.DataGrids[dataGridFormDataIndex].DataGridItems[dgFormDataRecordIndex], "DataGridKey");
                    }
                });
            }
            return;
        }
    }

    var formID = $(sender).parents('.tzDataGrid').attr('BindingForm');
    var senderFormParams = $('#Form' + $(sender).parents('form').attr('ID') + '_Property').val();
    var strBindingFormParam = $(sender).parents('.tzDataGrid').attr('BindingFormParams');
    var bindingFormParamsArray = strBindingFormParam.split('|');
    var PopupValidationsID = $(sender).parents('.tzDataGrid').attr('PopupValidationIDsList');
    if (PopupValidationsID == undefined) {
        PopupValidationsID = "";
    }
    $.each(bindingFormParamsArray, function (inedx, bindFP) {
        var strTemp = bindFP.split('=');
        if (strTemp[1] == undefined || strTemp[1] == '')
            return;
        var paramComponentID = strTemp[1].replace(/'/g, "");
        strBindingFormParam = strBindingFormParam.replace(paramComponentID, GetValue($('#' + paramComponentID)));
    });

    if ($(sender).hasClass('tbsDataGridBtn-Add')) {
        var AddValidationsID = $(sender).parents('.tzDataGrid').attr('AddValidationIDsList');
        if (AddValidationsID != undefined) {
            FormValidate([AddValidationsID], function () {
                OpenPopUp(tbsRootURL + "Form/DataGrid" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&bindingFormParams=' + strBindingFormParam + '&PopupValidationsID=' + PopupValidationsID + '&layoutID=' + layoutID + '&eventMode=add', true);
            }, sender)
        }
        else {
            OpenPopUp(tbsRootURL + "Form/DataGrid" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&bindingFormParams=' + strBindingFormParam + '&PopupValidationsID=' + PopupValidationsID + '&layoutID=' + layoutID + '&eventMode=add', true);
        }
    }
    else if ($(sender).hasClass('tbsDataGridBtn-Edit')) {
        var EditValidationsID = $(sender).parents('.tzDataGrid').attr('EditValidationIDsList');
        if (EditValidationsID != undefined) {
            FormValidate([EditValidationsID], function () {
                if (gridElement.select().length == 1) {
                    var selectedItem = gridElement.dataItem(gridElement.select());

                    var dg = $.grep(controller.FormData.DataGrids, function (e) { return e.ForingComponentId == senderID; });
                    var elementFormData = $.grep(dg[0].DataGridItems, function (e) {
                        return e.DataGridKey == selectedItem.DataGridKey;
                    })[0];
                    elementFormData.ISUpdateed = true;
                    $.ajax({
                        headers: {
                            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
                        },
                        url: tbsRootURL + "Form/SetFormData",
                        data: JSON.stringify({
                            formData: elementFormData
                        }),
                        type: 'POST',
                        contentType: "application/json",
                        dataType: "json",
                        success: function (response) {
                            if (response != '0') {
                                OpenPopUp(tbsRootURL + "Form/DataGrid" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&bindingFormParams=' + strBindingFormParam + "&dataGridKey=" + elementFormData.DataGridKey + '&formDataGUID=' + response + '&PopupValidationsID=' + PopupValidationsID + '&layoutID=' + layoutID + '&eventMode=edit', true);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            ShowNotification('error', errorThrown);
                        }
                    });

                }
            }, sender)
        }
        else {
            if (gridElement.select().length == 1) {
                var selectedItem = gridElement.dataItem(gridElement.select());

                var dg = $.grep(controller.FormData.DataGrids, function (e) { return e.ForingComponentId == senderID; });
                var elementFormData = $.grep(dg[0].DataGridItems, function (e) {
                    return e.DataGridKey == selectedItem.DataGridKey;
                })[0];
                elementFormData.ISUpdateed = true;
                $.ajax({
                    headers: {
                        'RequestVerificationToken': $('#m_RequestVerificationToken').val()
                    },
                    url: tbsRootURL + "Form/SetFormData",
                    async: true,
                    data: JSON.stringify({
                        formData: elementFormData
                    }),
                    type: 'POST',
                    contentType: "application/json",
                    dataType: "json",
                    success: function (response) {
                        if (response != '0') {
                            OpenPopUp(tbsRootURL + "Form/DataGrid" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&bindingFormParams=' + strBindingFormParam + "&dataGridKey=" + elementFormData.DataGridKey + '&formDataGUID=' + response + '&PopupValidationsID=' + PopupValidationsID + '&layoutID=' + layoutID + '&eventMode=edit', true);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        ShowNotification('error', errorThrown);
                    }
                });

            }
        }
    }
}

function ReplyDataGrid(formID, dataGridID, formData, dataGridKey, eventMode) {

    formData.DataGridKey = dataGridKey;
    var controller = angular.element(document.querySelector("[data-ng-controller='Form" + formID + "_Controller']")).scope();
    if (formData.PKFormId == -1) {
        formData.IsNew = true;
    }

    if (formData.DataGridKey == undefined || formData.DataGridKey == null || formData.DataGridKey == "")
        formData.DataGridKey = GenerateUUID();

    var dgName = $('#' + dataGridID).attr('data-name');
    var datagridDS = controller[dgName + "DS"];
    var datagridDSAggregateItems = controller[dgName + "DS_aggregateItems"];

    var gridRecord = { DataGridKey: formData.DataGridKey };

    //$.each(formData.Components, function (index, component) {
    //    if (component.ControlDisplayValue != undefined && component.ControlDisplayValue != null && component.ControlDisplayValue != "")
    //        gridRecord['Col_' + component.ControlID] = component.ControlDisplayValue;
    //    else
    //        gridRecord['Col_' + component.ControlID] = component.ControlValue;
    //});

    $.each(formData.Components, function (index, component) {
        if (component.ControlDisplayValue != undefined && component.ControlDisplayValue != null && component.ControlDisplayValue != "") {
            if (datagridDSAggregateItems == undefined || datagridDSAggregateItems[0] == undefined) {
                gridRecord['Col_' + component.ControlID] = component.ControlDisplayValue;
            }
            else {
                $.each(datagridDSAggregateItems, function (index, item) {
                    if (item["fieldID"] == "Col_" + component.ControlID && item["dataType"] == "number") {
                        gridRecord['Col_' + component.ControlID] = parseInt(component.ControlDisplayValue);
                    }
                    else {
                        gridRecord['Col_' + component.ControlID] = component.ControlDisplayValue;
                    }

                });
            }
        }

        else {
            if (datagridDSAggregateItems == undefined || datagridDSAggregateItems[0] == undefined || datagridDSAggregateItems.filter(item => item.fieldID == 'Col_' + component.ControlID).length == 0) {
                gridRecord['Col_' + component.ControlID] = component.ControlValue;
            }
            else {
                $.each(datagridDSAggregateItems, function (index, item) {

                    if (item["fieldID"] == "Col_" + component.ControlID) {
                        if (item["dataType"] == "number") {
                            gridRecord['Col_' + component.ControlID] = parseInt(component.ControlValue);
                        }
                        else {
                            gridRecord['Col_' + component.ControlID] = component.ControlValue;
                        }
                    }

                });
            }
        }

    });

    AddItemInArrayNoRepeat(datagridDS.data, gridRecord, "DataGridKey");

    controller.$digest();

    if (datagridDSAggregateItems != undefined) {
        setTimeout(function () {

            controller[dgName].calcAggregate();

            controller.$digest();

        }, 1000);
    }

    var formDataGridIndex = FindIndexInArrayByAttr(controller.FormData.DataGrids, "ForingComponentId", dataGridID);
    if (formDataGridIndex < 0) {
        var dg = $.extend(true, {}, controller.DataGridItem);
        dg.ForingComponentId = dataGridID;
        formDataGridIndex = controller.FormData.DataGrids.push(dg) - 1;
    }

    //var strTemp = formData.Components[0].ControlID;
    //if (strTemp.indexOf('frm') != 0)
    //    formData.Components.unshift({ ControlDisplayValue: formData.PKFormId, ControlID: "frm" + formData.FormId + "Id", ControlValue: formData.PKFormId, IsPersistable: false, NamePersist: null });
    //AddItemInArrayNoRepeat(controller.FormData.DataGrids[formDataGridIndex].DataGridItems, formData, "DataGridKey");
    //if (!formData.IsNew && formData.ISUpdateed) {
    //    AddItemInArrayNoRepeat(controller.FormData.DataGrids[formDataGridIndex].CopyDataGridItems, formData, "DataGridKey");
    //}


    var strTemp = formData.Components[0].ControlID;
    if (strTemp.indexOf('frm') != 0)
        formData.Components.unshift({ ControlDisplayValue: formData.PKFormId, ControlID: "frm" + formData.FormId + "Id", ControlValue: formData.PKFormId, IsPersistable: false, NamePersist: null });
    AddItemInArrayNoRepeat(controller.FormData.DataGrids[formDataGridIndex].DataGridItems, jQuery.extend(true, {}, formData), "DataGridKey");
    if (!formData.IsNew && formData.ISUpdateed) {
        AddItemInArrayNoRepeat(controller.FormData.DataGrids[formDataGridIndex].CopyDataGridItems, jQuery.extend(true, {}, formData), "DataGridKey");
    }

    if (eventMode != null || eventMode != undefined) {
        controller[dgName + "_ExecDsEvents"](eventMode);
    }

}

function GridView_OnClick(sender) {

    var gridElement = $(sender).parents('.tzGridView').getKendoGrid();
    if ($(sender).hasClass('tbsDataGridBtn-Excel')) {
        gridElement.dataSource.options.data = gridElement.dataSource._pristineData;
        gridElement.options.excel.allPages = true;
        gridElement.saveAsExcel("asdasd");
    }

    var formID = $(sender).parents('.tzGridView').attr('BindingForm');
    var keyColName = $(sender).parents('.tzGridView').attr('KeyColName');
    if (formID == undefined || keyColName == undefined)
        return;

    var senderFormID = $(sender).parents('form').attr('ID');
    var senderID = $(sender).parents('.tzGridView').attr('ID');
    var senderName = $(sender).parents('.tzGridView').attr('data-name');
    var popupValidations = $(sender).parents('.tzGridView').attr('PopUpValidations');
    var strBindingFormParam = $(sender).parents('.tzGridView').attr('BindingFormParams');
    if (strBindingFormParam != undefined) {
        var bindingFormParamsArray = strBindingFormParam.split('|');
        $.each(bindingFormParamsArray, function (inedx, bindFP) {
            var strTemp = bindFP.split('=');
            if (strTemp[1] == undefined || strTemp[1] == '')
                return;
            var paramComponentID = strTemp[1].replace(/'/g, "");
            strBindingFormParam = strBindingFormParam.replace(paramComponentID, GetValue($('#' + paramComponentID)));
        });
    }
    else
        strBindingFormParam = '';
    if (popupValidations == undefined)
        popupValidations = '';
    var controller = angular.element(document.querySelector("[data-ng-controller='Form" + senderFormID + "_Controller']")).scope();

    var layoutID = $(sender).parents('.tzGridView').attr('ViewLayoutID');

    if (layoutID == undefined) {
        layoutID = -1;
    }
    var selectedItem = gridElement.dataItem(gridElement.select())
    var selectedID = null;
    if (selectedItem != undefined && selectedItem != null) {
        selectedID = selectedItem[keyColName];
    }

    var senderFormParams = $('#Form' + $(sender).parents('form').attr('ID') + '_Property').val();

    if ($(sender).hasClass('tbsDataGridBtn-Del')) {
        if (gridElement.select().length == 1) {
            ShowNotification('inf', 'آیا مطمئن هستید؟', function () { }, function () {
                $.ajax({
                    type: "POST",
                    url: tbsRootURL + "Form/GridViewOnLineDelete",
                    headers: {
                        'RequestVerificationToken': $('#m_RequestVerificationToken').val()
                    },
                    contentType: "application/json",
                    dataType: "json",
                    async: false,
                    data: JSON.stringify({
                        formId: formID,
                        pkFormId: selectedID,
                        ChecklistBoxIds: ''
                    }),
                    success: function (result) {
                        if (result.Errors) {
                            ErrorHandler(result);
                        }
                        else {
                            gridElement.dataSource.options.Exec();

                            ReplyGridView(senderFormID, senderID, senderFormParams, '', 'delete');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        ShowNotification('error', errorThrown);
                    }
                });
            });
        }
        return;
    }

    else if ($(sender).hasClass('tbsDataGridBtn-Add')) {
        OpenPopUp(tbsRootURL + "Form/GridView" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&layoutID=' + layoutID + '&primaryIDName=' + keyColName + '&primaryID=-1' + '&popupValidations=' + popupValidations + "&bindingFormParams=" + strBindingFormParam + '&eventMode=add', true);
    }

    else if ($(sender).hasClass('tbsDataGridBtn-Edit') || $(sender).parent().children('.k-grid-toolbar').children().hasClass('tbsDataGridBtn-Edit')) {
        if (gridElement.select().length == 1) {
            var selectedItem = gridElement.dataItem(gridElement.select());
            OpenPopUp(tbsRootURL + "Form/GridView" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&layoutID=' + layoutID + '&primaryIDName=' + keyColName + '&primaryID=' + selectedID + '&popupValidations=' + popupValidations + "&bindingFormParams=" + strBindingFormParam + '&eventMode=edit', true);
        };
    }

    else {
        if (gridElement.select().length == 1) {
            var selectedItem = gridElement.dataItem(gridElement.select());
            senderFormParams += "ViewMode=details";
            OpenPopUp(tbsRootURL + "Form/GridView" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&layoutID=' + layoutID + '&primaryIDName=' + keyColName + '&primaryID=' + selectedID + '&popupValidations=' + popupValidations + "&bindingFormParams=" + strBindingFormParam + "'", true);
        };
    }

}

function ReplyGridView(formID, dataGridID, formData, dataGridKey, eventMode) {

    var controller = angular.element(document.querySelector("[data-ng-controller='Form" + formID + "_Controller']")).scope();
    controller.FormData.GridViews.push({ ForingComponentId: dataGridID, Components: formData.Components });

    var dgName = $('#' + dataGridID).attr('data-name');
    var datagridDS = controller[dgName + "DS"];
    var datagridDSAggregateItems = controller[dgName + "DS_aggregateItems"];

    var gridRecord = { DataGridKey: formData.DataGridKey };

    if (eventMode != null || eventMode != undefined) {
        controller[dgName + "_ExecDsEvents"](eventMode);
    }
}


function GridWorkFlowInstanceID_OnClick(sender) {
    OpenPopUp(tbsRootURL + "Task/IndexWithWorkflowInstance" + '?WorkflowInstanceId=' + $(sender).attr('data-navigate'), false);
}

//base64 to fileDownload
function base64ToFileDownload(result, contentType = '', sliceSize = 512) {
    const byteCharacters = atob(result);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);

        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });

    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = result.fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
}

function downloadFileUpload(sender) {
    let fileName = $(sender).parent().parent().children('input')[0].value;
    let url = tbsRootURL + "Attachment/DownloadAttachments",
        dataItem = { fileId: parseInt($(sender).data().fileid) };


    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(dataItem)
    })
        .then((resp) => {
            try {
                if (resp.url.indexOf("Attachment/DownloadAttachments") == -1) {
                    history.pushState(null, "", "");
                    window.location.href = resp.url;
                }
                else {
                    responseData = resp.clone();
                    return resp.blob();
                }
            }
            catch (ex) {
                return resp;
            }
        })
        .then((blob) => {
            try {
                if (blob.type == 'application/json') {
                    responseData.json()
                        .then((data) => {
                            if ((typeof data === 'object' || data instanceof Object) && data['code'] == 400) {
                                ErrorHandler(data.message);
                            }
                        });
                }
                else {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }
            catch (ex) {
            }
        })
        .catch((ex) => {
            ErrorHandler("انجام عملیات با خطا مواجه گردید");
        });
};

function downloadFileHref(sender) {

    var href = $(sender).attr("href");
    if (href.indexOf(tbsRootURL) == -1) {
        $(sender).attr("href", tbsRootURL + href);
    }
    return false;
}

function GridWorkFlowInstanceID_OnClickForOpenSearchForm(sender) {

    controlId = $(sender).attr('ParentGridControlId');
    var grid = $('#' + controlId).data("kendoGrid");
    RowID = sender.parentElement.parentElement.getAttribute('data-uid');
    var row = grid.table.find("tr[data-uid='" + RowID + "']");
    grid.select(row);
    //_GridWorkFlowInstanceID_OnClickForOpenSearchForm(sender)
    if (!sender.tagName == 'A')
        GridView_OnClick(sender)
    setTimeout(_GridWorkFlowInstanceID_OnClickForOpenSearchForm, 1000, sender)

}

function _GridWorkFlowInstanceID_OnClickForOpenSearchForm(_sender) {
    OpenPopUp(tbsRootURL + "SearchForm?SearchFormID=" + $(_sender).attr('data-navigate'), false);
}

function HelpDeskOnclick(sender) {
    var senderID = $(sender).attr('ID');
    var senderFormID = $(sender).parents('form').attr('ID');
    OpenPopUp(tbsRootURL + "HelpDesk/Index" + '?HelpDeskID=' + senderID + "&formID=" + senderFormID, 800, 600, true);

}

function FindIndexInArrayByAttr(array, attr, value) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i][attr] === value)
            return i; // Return as soon as the object is found
    }
    return -1; // The object was not found
}

function AddItemInArrayNoRepeat(array, item, key) {
    var itemIndex = FindIndexInArrayByAttr(array, key, item[key]);
    if (itemIndex < 0) {
        itemIndex = array.push(item) - 1;
    }
    else {
        array[itemIndex] = item;
    }
}


//#endregion Grids

//#region Lookup
function LookUp_OnClick(sender) {
    var formID = $(sender).parent().attr('data-SearchFormID');
    var senderFormID = $(sender).parents('form').attr('ID');
    var senderID = $(sender).parent().attr('ID');
    var gridViewID = $(sender).parent().attr('data-SearchDataGridId');
    var gridValueMemberColumn = $(sender).parent().attr('data-ValueMemberColumn');
    var gridDisplayMemberColumn = $(sender).parent().attr('data-DisplayMemberColumn');
    var strBindingFormParam = $(sender).parent().attr('BindingFormParams');

    if (strBindingFormParam != undefined) {
        var bindingFormParamsArray = strBindingFormParam.split('|');
        $.each(bindingFormParamsArray, function (inedx, bindFP) {
            var strTemp = bindFP.split('=');
            if (strTemp[1] == undefined || strTemp[1] == '')
                return;
            var paramComponentID = strTemp[1].replace(/'/g, "");
            strBindingFormParam = strBindingFormParam.replace(paramComponentID, GetValue($('#' + paramComponentID)));
        });
    }
    else
        strBindingFormParam = '';


    var senderFormParams = $('#Form' + $(sender).parents('form').attr('ID') + '_Property').val();

    OpenPopUp(tbsRootURL + "Form/LookUp" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID + '&formID=' + formID + '&gridViewID=' + gridViewID + '&gridValueMemberColumnName=' + gridValueMemberColumn + '&gridDisplayMemberColumnName=' + gridDisplayMemberColumn + '&bindingFormParams=' + strBindingFormParam + "'", true);
}

function ExcuteDataSourecFromChild(formId, eventsName) {
    var controller;
    if (eventsName == "" || eventsName == null)
        return;
    controller = angular.element(document.querySelector("[data-ng-controller='Form" + formId + "_Controller']")).scope();

    ExecDataSourceCount = 0;
    ExecDataSourceCounter = 0;

    eventsName.split(',').forEach((el) => {
        if ($(controller).attr(el) != undefined) {
            ExecDataSourceCount++;
        };
    })

    $.each(eventsName.split(","), function (index, dsName) {
        if ($(controller).attr(dsName) != undefined) {
            var ccelement = $(controller).attr(dsName).select;
            $(ccelement).parent().find('.k-i-arrow-s').addClass('k-loading');
            if (firstReloadFlag != 1 && $(ccelement).is('select') && $(ccelement).val() != "")
                $($(controller).attr(dsName).select).val("")
            $(controller).attr(dsName).options.Exec();

        }
    });

}
function ReplyLookup(formID, lookupID, value, text) {
    var lookupItem = $("form[id='" + formID + "'] #" + lookupID);
    $(lookupItem).attr('value', value);
    $(lookupItem).children('input').val(text).change();
}

function ReplyHelpDesk(formID, HelpDeskID, Summary, text, Title, nodeId) {
    try {
        var HelpDeskItem = $("form[id='" + formID + "'] #" + HelpDeskID);
        if ($(HelpDeskItem) != null && $(HelpDeskItem) != undefined) {
            var summaryrelatedcomponnettxtArr = $(HelpDeskItem).attr('summaryrelatedcomponnet');// $("input[data-name='" + $(HelpDeskItem).attr('summaryrelatedcomponnet') + "']");
            if (summaryrelatedcomponnettxtArr != undefined && summaryrelatedcomponnettxtArr != null && summaryrelatedcomponnettxtArr != '')
                $.each(summaryrelatedcomponnettxtArr.split(","), function (index, summaryrelatedcomponnettxt) {
                    var summaryrelatedComponent = $("input[data-name='" + summaryrelatedcomponnettxt + "']");
                    $(summaryrelatedComponent).val(Summary);
                    summaryrelatedComponent.change();
                });

            var titlerelatedcomponnettxtArr = $(HelpDeskItem).attr('titlerelatedcomponnet');// $("input[data-name='" + $(HelpDeskItem).attr('summaryrelatedcomponnet') + "']");
            if (titlerelatedcomponnettxtArr != undefined && titlerelatedcomponnettxtArr != null && titlerelatedcomponnettxtArr != '')
                $.each(titlerelatedcomponnettxtArr.split(","), function (index, titlerelatedcomponnettxt) {
                    var titlerelatedcomponnet = $("input[data-name='" + titlerelatedcomponnettxt + "']");
                    $(titlerelatedcomponnet).val(Title);
                    titlerelatedcomponnet.change();
                });

            var IdRelatedComponnettxtArr = $(HelpDeskItem).attr('IdRelatedComponnet');// $("input[data-name='" + $(HelpDeskItem).attr('summaryrelatedcomponnet') + "']");
            if (IdRelatedComponnettxtArr != undefined && IdRelatedComponnettxtArr != null && IdRelatedComponnettxtArr != '')
                $.each(IdRelatedComponnettxtArr.split(","), function (index, IdRelatedComponnettxt) {
                    var IdRelatedComponnet = $("input[data-name='" + IdRelatedComponnettxt + "']");
                    $(IdRelatedComponnet).val(nodeId);
                    IdRelatedComponnet.change();
                });


            var textrelatedcomponnettxtArr = $(HelpDeskItem).attr('textrelatedcomponnet');// $("input[data-name='" + $(HelpDeskItem).attr('summaryrelatedcomponnet') + "']");
            if (textrelatedcomponnettxtArr != undefined && textrelatedcomponnettxtArr != null && textrelatedcomponnettxtArr != '')
                $.each(textrelatedcomponnettxtArr.split(","), function (index, textrelatedcomponnettxt) {
                    var textrelatedcomponnet = $("input[data-name='" + textrelatedcomponnettxt + "']");
                    if (textrelatedcomponnet.attr('id') != undefined) {
                        $(textrelatedcomponnet).val(text);
                        textrelatedcomponnet.change();
                    }
                    else {
                        textrelatedcomponnet = $("textarea[data-name='" + textrelatedcomponnettxt + "']");
                        if (textrelatedcomponnet.attr('id') != undefined) {
                            //var editor = textrelatedcomponnet.data("kendoEditor");
                            //editor.value(text)
                            //textrelatedcomponnet.attr('value', text);
                            //textrelatedcomponnet.change();

                            CKEDITOR.instances[textrelatedcomponnet.attr('id')].setData(text);
                        }
                    }
                });
            $(HelpDeskItem).change();
        }
    } catch (e) {

    }



    //alert($(HelpDeskItem).attr('textrelatedcomponnet'));
    //alert($(HelpDeskItem).attr('titlerelatedcomponnet'));

}

//#endregion Lookup

//#region HyperLink
function AudioPalayerLaodData(sender) {
    alert(sender);
}

function tzHyperlinkHTML_onClick(sender) {
    if ($(sender).is("[disabled='disabled']"))
        return;
    var senderFormID = $(sender).parents('form').attr('ID');
    var senderID = $(sender).attr('ID');
    var senderName = $(sender).attr('data-name');
    var formID = $(sender).attr('BindingForm');
    var senderFormParams = $('#Form' + $(sender).parents('form').attr('ID') + '_Property').val();
    var strBindingFormParam = $(sender).attr('BindingFormParams');
    var formLayoutID = $(sender).attr('BindingFormLayoutID');
    var workflow = $(sender).attr('Workflow');
    var WorkflowInstanceId = $(sender).attr('WorkflowInstanceId');
    var bindingFormParamsArray = strBindingFormParam.split('|');
    $.each(bindingFormParamsArray, function (inedx, bindFP) {
        var strTemp = bindFP.split('=');
        if (strTemp[1] == undefined || strTemp[1] == '')
            return;
        var paramComponentID = strTemp[1].replace(/'/g, "").replace(' ', '');
        strBindingFormParam = strBindingFormParam.replace(paramComponentID, GetValue($('#' + paramComponentID)));
    });
    //if (WorkflowInstanceId != undefined || WorkflowInstanceId > 0)
    if (WorkflowInstanceId != undefined) {
        if ($.isNumeric(WorkflowInstanceId))
            OpenPopUp(tbsRootURL + "Task/IndexWithWorkflowInstance?WorkflowInstanceId=" + WorkflowInstanceId, false);
        else
            window.open(WorkflowInstanceId, '_blank', 'scrollbars=yes,location=no,width=500,height=500');

    }
    else if (workflow != undefined || workflow > 0)
        OpenPopUp(tbsRootURL + "NewWorkFlow" + '?WorkflowId=' + workflow, false);
    else
        OpenPopUp(tbsRootURL + "Form/Hyperlink" + '?senderFormID=' + senderFormID + '&senderFormParams=' + senderFormParams + '&senderID=' + senderID
            + '&formID=' + formID + '&bindingFormParams=' + strBindingFormParam + '&formLayoutID=' + formLayoutID, true);
}

//#endregion HyperLink

//#region DatePicker
function GetDatePickerInputWithTrueFormat(DatePickerValue) {
    var FormatIsCorrect = Date.parse(DatePickerValue);
    if (FormatIsCorrect == 'NaN') {
        return '';
    }
    else {
        return DatePickerValue;
    }
}

function DatePickerValidateInputData(Element, CallBackEventFunction) {
    var DatePItem = $(Element).getKendoDatePicker();
    var oldValue = '';
    if (DatePItem != undefined) {
        var oldValue = $(Element).val();
    }
    if (oldValue != '') {
        var IsDate = Date.parse(oldValue);
        if (IsDate == 'NaN') {
            DatePItem.value('');
        }
    }
    if (CallBackEventFunction != undefined) {
        CallBackEventFunction();
    }

}

//#endregion DatePicker

//#region DatePicker
function GetBoolean(stringValue) {
    alert(stringValue);
    if (stringValue == undefined)
        return false;
    if (stringValue == "")
        return false;
    if (stringValue.toLowerCase() == "true")
        return true;
    if (stringValue.toLowerCase() == "false")
        return false;
    if (stringValue == "0")
        return false;
    if (stringValue == "1")
        return true;
    return false;
    //return stringValue != undefined && stringValue.toLowerCase() === "true";
}
//#endregion DatePicker

//#region Player
function setAudioSrc(sender) {
    var fileID = $(sender).attr('FileID');
    if (Number.isInteger(fileID))
        $(sender).attr('src', tbsRootURL + 'FileServer.ashx?FileID=' + fileID);
    else
        $(sender).attr('src', fileID);
}
var divIDs = new Array();
var mustBeSelecteds = new Array();
var columnFilters = new Array();
function setGridViewSelectedData(sender) {
    if ($(sender).attr('selectedData') != undefined) {
        divIDs.push($(sender).attr('id'));
        mustBeSelecteds.push($(sender).attr('selectedData').split('$'));
        columnFilters.push($(sender).attr('keycolname'));
    }

}
//#endregion Player

//#region FileUploade
function fileUploadChange(sender) {
    var element1 = $(sender).parents(".tzFileUpload");
    $(element1).children('input').attr("placeholder", "در حال بارگذاری...");

    var files = sender.files;
    var name = files[0].name;

    if (window.FormData !== undefined) {
        var data = new FormData();
        data.append("formId", $('form').attr('id'));
        //for (var x = 0; x < files.length; x++) {
        //    data.append("file" + x, files[x]);
        //}
        data.append("UploadedFile", files[0]);
    }

    $.ajax({
        url: tbsRootURL + 'Attachment/UploadFile',
        type: 'POST',
        data: data,
        success: function (res) {

            if ((typeof res === 'object' || res instanceof Object) && res['code'] == 400) {
                $(element1).children('input').attr("placeholder", "");
                ErrorHandler(res.message);
                resetFileUpload(sender);
            }
            else if (res > -1) {
                $(sender).parent().parent().siblings('input.form-control').val(name);
                var element = $(sender).parents(".tzFileUpload");
                $(element).attr('FileID', res);
                setUploadeData(element);
                if ($(element).attr('customonchange') != undefined)
                    eval($(element).attr('customonchange').replaceAll('this', '$(sender)'));
                $(element).removeClass("k-invalid");
                $(element).children('input').addClass("fileUploaded");
                $(element).children().children('a.btn-download').attr('data-fileid', res);

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == 409) {
                ShowNotification('error', "<p>خطا در ارسال درخواست تکراری ... لطفا دوباره تلاش کنید</p>");
            }
            else {
                ShowNotification('error', errorThrown);
            }
            resetFileUpload(sender);
        },
        cache: false,
        contentType: false,
        processData: false
    });
}

function resetFileUpload(sender) {
    debugger
    var element = $(sender).parents(".tzFileUpload");
    if ($(element).hasClass('tzDisabled') || sender.hasAttribute('disabled'))
        return;
    if ($(element).attr('value') != '-1#' && $(element).attr('value') != '') {
        if (!confirm('آیا از حذف این فایل اطمینان دارید؟'))
            return;
    }

    $(element).attr('FileID', "-1");
    $(element).attr('value', "-1#");
    $(sender).parent().children('a.btn.btn-default').hide();
    $(element).children('input.form-control').val('').clone(true);
    $(element).children('input').attr('value', '');
    $(element).children('input').attr("placeholder", "");
    $(element).children('.input-group-btn').children("a.btn.btn-default").attr('href', '#');
    if ($(element).attr('customonchange') != undefined)
        eval($(element).attr('customonchange').replace('this', 'element'));
    if ($(element).attr('required') == "required") {
        $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").children().attr('required', 'required');
        $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html("<input onchange='fileUploadChange(this)' type='file' required='required'>")
    }
    else {
        $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html('');
        $(element).children('.input-group-btn').children("span.btn.btn-default.btn-file").html("<input onchange='fileUploadChange(this)' type='file'>")
    }

    $(element).children('input').removeClass("fileUploaded");
}

function setUploadeHreff(sender) {
    var fileID = $(sender).attr('FileID');
    if (fileID != undefined && fileID != "" && parseInt(fileID) > 0) {
        $(sender).children('.input-group-btn').children("a.btn.btn-default:first").attr('href', tbsRootURL + 'FileServer.ashx?FileID=' + fileID);
        $(sender).children('.input-group-btn').children("a.btn.btn-default").show();
    }
    else {
        $(sender).children('.input-group-btn').children("a.btn.btn-default").hide();
    }
}

function setUploadeData(sender) {
    var fileID = $(sender).attr('FileID');
    if (fileID != undefined && fileID != "" && parseInt(fileID) > 0) {
        $(sender).children('.input-group-btn').children("a.btn.btn-default").show();
        $(sender).children('.input-group-btn').children("a.btn-download").data().fileid = fileID;

        //$('.tzFileUpload input.form-control').css("width", $('.tzFileUpload').width() - 100 + "px");
    }
    else {
        $(sender).children('.input-group-btn').children("a.btn.btn-default").hide();
    }
}
//#endregion FileUploade


function GetformParams(formID) {
    var formParams = $('#Form' + formID + '_Property').val();
    var FormParamsObject = new Object();
    var listrFormParams = formParams.split(' ');
    $.each(listrFormParams, function (index, paramValue) {
        if (paramValue.indexOf("=") > -1) {
            var temp = paramValue.split("=");
            FormParamsObject[temp[0]] = temp[1].replace(/'/g, "");
        }
    });
    return FormParamsObject;

}
//reportViewer
function GetReportParams(reportParamsStructure, reportId, formID) {

    var reportParams = new Object();
    var formParams = GetformParams(formID);
    $.each(JSON.parse(reportParamsStructure), function (index, paramKey) {
        if (!paramKey.includes("(@"))
            reportParams[index] = GetValue($('#' + paramKey));
        else {
            $.each(formParams, function (formParamIndex, formParamKey) {
                if (formParamIndex == paramKey.match(/[^\(@]+/g).join('(').match(/[^\)]+/g).join(')'))
                    reportParams[index] = formParamKey;
            });
        }
    });
    return reportParams





    //for (var f_param in formParams) {

    //    reportParams["Variable1"].match(/[^\(@]+/g).join('(').match(/[^\)]+/g).join(')')
    //}
    //return getReportByAjax($(sender).attr('data-ReportID'), JSON.stringify(reportParams), formParams)


    //document.getElementById(reportViewerId).innerHTML = ShowReport(formID, element);
    //return ShowReport(formID, element);
}
function getReportByAjax(ReportID, reportParams, formParams) {
    var htmlReport;
    $.ajax({
        type: "POST",
        url: tbsRootURL + "Report/GetHTMLReport",
        contentType: "application/json",
        async: false,
        data: JSON.stringify({
            ReportID: ReportID,
            jsReportParams: reportParams,
            FormParams: formParams
        }),
        success: function (result) {
            htmlReport = result;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ShowNotification('error', errorThrown);
            console.error("there is an error on generate Report : reportResult=>");
            console.log(reportResult);
            return;
        }
    });
    return htmlReport;
}


function onDataBound(e) {
    var colorfield = "";
    var grid = e.sender;
    $.each(e.sender.columns, function (i, column) {
        if (column.IsRowColorField == 'true') {
            try {
                grid.hideColumn(column)
            } catch (e) {
                console.log(e)
            }
            colorfield = column.field;

        }
    });
    $.each(e.sender.dataItems(), function (i, row) {
        $('tr[data-uid="' + row.uid + '"]').css("background-color", row[colorfield]);
    });
    $(".multiSelectBox").bind("click", function (e) {

        //var ds = $(e.target).attr("ng-events").split(",");
        //var parentGrid = $(e.target).closest("div").parent().data("kendoGrid");
        //$.each(ds, function (index, item) {
        //    ExecFormDatasources(parentGrid, item)
        //})

        e.stopPropagation();
        var row = $(e.target).closest("tr");
        //if (!row.hasClass("k-state-selected")) {
        //    $(e.target).removeClass("k-state-selected");
        //}
        //row.toggleClass("k-state-selected");
        var parent = $(e.target).closest("div").parent().data("kendoGrid");
        //var row = parent.tbody.find(e.target);
        parent.select(row);
    });

    //if (e.sender._data.length == 0) {
    //    var contentDiv = this.wrapper.children(".k-grid-content"),
    //        dataTable = contentDiv.children("table");
    //    if (!dataTable.find("tr").length) {
    //        dataTable.children("tbody").append("<tr colspan='" + this.columns.length + "'><td style='border:0px;'> </td></tr>");
    //        //if ($.browser.msie) {
    //        //    dataTable.width(this.wrapper.children(".k-grid-header").find("table").width());
    //        //    contentDiv.scrollLeft(1);
    //        //}
    //    }
    //}
}


function onkendoComboBoxFiltering(e) {
    if (e.filter != null && e.filter.value != null) {
        console.log(e.filter.value);
        x = e.filter.value;
        //x = x.replace('ی', '1');
        //x = x.replace('ک', '2');

        //x = x.replace('ي', '3');
        //x = x.replace('ک', '4');
        //x = x.replace('ی', '5');
        console.log(x);
        e.filter.value = e.filter.value
            .replaceAll('ي', 'ی')
            .replaceAll('ك', 'ک');
    }

}


function treeViewFilter(controlId) {
    var id = '#filterText_' + controlId;
    var filterText = $(id).val();
    if (filterText !== "") {
        $("#" + controlId + ".k-group .k-group .k-in").closest("li").hide();
        $("#" + controlId + " .k-group").closest("li").hide();
        $("#" + controlId + " .k-in:contains(" + filterText + ")").each(function () {
            $(this).removeClass('findFromFilter');
            $(this).parents("ul, li").each(function () {

                var treeView = $("#" + controlId).data("kendoTreeView");
                treeView.expand($(this).parents("li"));
                $(this).show();
            });
        });
        $("#" + controlId + " .k-group .k-in").each(function () {
            $(this).removeClass('findFromFilter');
        });

        $("#" + controlId + " .k-group .k-in:contains(" + filterText + ")").each(function () {
            $(this).addClass('findFromFilter');
            $(this).parents("ul, li").each(function () {
                $(this).show();
            });
        });
    }
    else {
        $("#" + controlId + " .k-group .k-in").each(function () {
            $(this).removeClass('findFromFilter');
        });

        $("#" + controlId + " .k-group").find("li").show();

        var nodes = $("#" + controlId + " > .k-group > li");

        $.each(nodes, function (i, val) {
            if (nodes[i].getAttribute("data-expanded") == null) {
                $(nodes[i]).find("li").hide();
            }
        });


    }

}


function TransferToIVR(IVRNodeCode) {

    var CallID = window.opener.document.getElementById('p_CallID').value;
    var CallerID = window.opener.document.getElementById('p_CallerID').value;
    var AgentID = window.opener.document.getElementById('p_AgentID').value;
    $.ajax({
        type: "POST",
        url: tbsRootURL + "CallCenter/TransferToIVR",
        contentType: "application/json",
        async: false,
        data: JSON.stringify({
            CallId: CallID,
            CallerId: CallerID,
            agentId: AgentID,
            IVRNodeCode: IVRNodeCode,
            Des_agentId: ''

        }),
        success: function (result) {

            ShowNotification('success', 'تماس با موفقیت به IVR انتقال پیدا کرد.');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ShowNotification('error', errorThrown);
            console.error("there is an error on generate Report : reportResult=>");
            console.log(reportResult);
            return;
        }
    });


}

function onkendoGridFiltering(e, grid) {
    if (e != null) {
        $.each(e.filters, function (index, item) {
            item.value = item.value.replace('ی', 'ي');
            item.value = item.value.replace('ی', 'ي');
            item.value = item.value.replace('ك', 'ک');
        });
    }
    if (arguments.length > 0) {
        grid.trigger("filtering", arguments);
    }
    // Call the original filter function.
    var result = grid.dataSource.originalFilter.apply(grid, arguments);
    return result;
}

function reportViewrCheck(reportID) {
    let id = reportID.controls.viewer.id;
    var textList = $('#' + id + ' text');

    if (textList.length > 0) {
        for (var i = 0; i < textList.length; i++) {
            if ($(textList[i]).prev().is('g')) {
                let rectList = $(textList[i]).prev().find('rect');
                for (var j = 0; j < rectList.length; j++) {

                    $(textList[i]).css('font-size', '14px');

                    $(rectList[j]).attr('width', $(rectList[j]).attr('width') * 2);
                    $(rectList[j]).attr('height', $(rectList[j]).attr('height') * 2);

                    let wid = $(rectList[j]).attr('width') / 3;
                    $(rectList[j]).attr('x', $(rectList[j]).attr('x') - wid);
                    //let hei = $(rectList[j]).attr('height') / 2;
                    //$(rectList[j]).attr('y', $(rectList[j]).attr('y') - hei);
                }

            }
        }
    }
}

function UpdateRelated(input) {    
    //$.ajax({
    //    type: "POST",
    //    headers: {
    //        'RequestVerificationToken': $('#m_RequestVerificationToken').val()
    //    },
    //    url: tbsRootURL + "Form/UpdateRelated",
    //    contentType: "application/json",
    //    dataType: "json",
    //    async: false,
    //    data: JSON.stringify({
    //        formID: $(input).parents('form').attr('ID'),
    //        controlID: $(input).attr('id'),
    //        enable: $(input).is(":checked")
    //    }),
    //    success: function (result) {
    //        debugger;
    //    },
    //    error: function (XMLHttpRequest, textStatus, errorThrown) {

    //        if (XMLHttpRequest.status == 426) {
    //            ErrorHandler(XMLHttpRequest.status);
    //        }
    //        else {
    //            ShowNotification('error', errorThrown);
    //        }
    //    },
    //    complete: function (data) {
    //    }

    //});
}

