$(window).on("load", function () {
    var radios = document.getElementsByTagName('input');
    for (i = 0; i < radios.length; i++) {
        if (radios[i].type == 'radio' && radios[i].checked) {
            var id = radios[i].id;
            $('#' + id).trigger('click');
        }
    }

    $('.tbs-binding').each(function (inedx, item) {
        var parentId = $(this).attr('ng-parentid');
        var dataName = $(this).attr('ng-elementName');
        var pathName = $(this).attr('ng-pathName');
        var btn = $(this).attr('ng-btnType');
        var dataValue = $('input#' + $('input[data-name = ' + dataName + ']').attr('id'))[0][pathName];
        var raisorId = $('input#' + $('input[data-name = ' + dataName + ']').attr('id'));
        if (parentId != null && dataValue != null && raisorId != null)
            EnableComponent($('#' + parentId + ' ' + btn), dataValue, raisorId);
    });

    $('.tzFileUpload input.form-control').css("width", $('.tzFileUpload').width() - 100 + "px");

    $(document).on("blur change", ".tzMandatory, [required]", function () {
    const $this = $(this);

    if ($this.val().trim()) {
        $this.removeClass("k-invalid").css("border", "");
        $this.parents().removeClass("k-invalid").css("border", "");
    }
    });
});

function ToKendoNumericTextBox(selector) {
    if ($('#' + selector + '').is('input.k-textbox')) {
        $('#' + selector + '').kendoNumericTextBox({ value: 0 });
        $('#' + selector + '').parent().children("input").css('position', 'static');
        if ($('#' + selector + '').hasClass('tzInVisible')) {
            $('#' + selector + '').parent().parent().hide();
        }
    }
}

function checkDataSourceExist(ds, dsname) {

    if (ds == undefined || ds == null)
        ss = "Not show";
    // ShowNotification('error', dsname + ' Not Found!!!');
    //alert(dsname + ' Not Found!!!');

}

function ToKendoDropDownList(selector, dataSourceName, dataValueField, dataTextField) {
    if ($('#' + selector + '').is(':visible')) {
        //$('#' + selector + '').kendoDropDownList({
        //    dataSource: dataSourceName,
        //    dataTextField: dataTextField,
        //    dataValueField: dataValueField
        //});
    }
    if ($('#' + selector + '').is('select')) {
        $('#' + selector + '').attr('kendo-drop-down-list', '');
        $('#' + selector + '').attr('k-data-source', dataSourceName + '.Data()');
        $('#' + selector + '').attr('k-data-value-field', "'" + dataValueField + "'");
        $('#' + selector + '').attr('k-data-text-field', "'" + dataTextField + "'");
    }
}


function ToKendoDatePicker(selector) {

    if ($('#' + selector).is(':visible')) {
        //$('#' + selector + '').css('left', parseInt($('#' + selector + '').css('left')) - 15);
        //$('#' + selector + '').kendoMaskedTextBox({
        //    mask: "00/00/0000"
        //}); 
    }
    if ($('#' + selector).is('input')) {
        if ($('#' + selector).hasClass('tzGregorianMode')) {
            $('#' + selector).kendoDatePickerEn({
                culture: 'en-US',
                format: "yyyy/MM/dd",
                value: '',
                height: '20px'
            });

            $('#' + selector + '').inputmask("9999/99/99", { "placeholder": "____/__/__" });
        }
        else {
            $('#' + selector).kendoDatePicker({
                culture: 'fa-IR',
                value: '',
                height: '20px'
            });

            $('#' + selector + '').inputmask("9999/99/99", { "placeholder": "____/__/__" });
        }

        $('#' + selector + '').css('position', 'static');

    }
}



function ToKendoButton(selector) {
    //if ($('#' + selector + '').is(':visible')) {
    if ($('#' + selector + '').is('button')) {
        $('#' + selector + '').kendoButton({ spriteCssClass: "k-icon " });
    }
    //}
}
function SetDefualtValue() {
    return;
    var FormID = 1;
    var val = $('#Form' + FormID + '_Property').val();
    val += "UserID='" + window.opener.document.getElementById('p_UserId').value + "' ";
    val += "CallID='" + window.opener.document.getElementById('p_CallID').value + "' ";
    val += "CallType='" + window.opener.document.getElementById('p_CallType').value + "' ";
    val += "CallerID='" + window.opener.document.getElementById('p_CallerID').value + "' ";
    val += "AgentID='" + window.opener.document.getElementById('p_AgentID').value + "' ";
    val += "ClientIP='" + window.opener.document.getElementById('p_ClientIP').value + "' ";
    val += "CallData='" + window.opener.document.getElementById('p_CallData').value + "' ";
    val += "WaitInQueueDuration='" + window.opener.document.getElementById('p_WaitInQueueDuration').value + "' ";

    if (angular.element("[value='@pCallID']") != null) {
        angular.element("[value='@pCallID']").val(window.opener.document.getElementById('p_CallID').value);
    }
    if (angular.element("[value='@pCallData']") != null) {
        angular.element("[value='@pCallData']").val(window.opener.document.getElementById('p_CallData').value);
    }

    if (angular.element("[value='@pCallType']") != null) {
        angular.element("[value='@pCallType']").val(window.opener.document.getElementById('p_CallType').value);
    }

    if (angular.element("[value='@pCallerID']") != null) {
        angular.element("[value='@pCallerID']").val(window.opener.document.getElementById('p_CallerID').value);
    }

    if (angular.element("[value='@pAgentID']") != null) {
        angular.element("[value='@pAgentID']").val(window.opener.document.getElementById('p_AgentID').value);
    }

    if (angular.element("[value='@pWaitInQueueDuration']") != null) {
        angular.element("[value='@pWaitInQueueDuration']").val(window.opener.document.getElementById('p_WaitInQueueDuration').value);
    }

    $('#Form' + FormID + '_Property').val(val);

    //CallID =&#39; 1 &#39; CallType =&#39; 0 &#39; CallerID =&#39; 1 &#39; AgentID =&#39; 1 &#39;
    //UserID =&#39; 1 &#39; ClientIP =&#39;:: 1 &#39;
}
function ShowReport(formID, sender) {

    controller = angular.element(document.querySelector("[data-ng-controller='Form" + formID + "_Controller']")).scope();
    reportParamsStructure = controller['Repoert_' + $(sender).attr('data-ReportID') + '_ReportParams'];
    var reportParams = new Object();
    $.each(Object.keys(reportParamsStructure), function (index, paramKey) {
        try {
            reportParams[paramKey] = GetValue($('#' + reportParamsStructure[paramKey])); //.push({ 'key': paramKey, 'value': GetValue($('#' + reportParamsStructure[paramKey])) });
        } catch (e) {
            reportParams[paramKey] = reportParamsStructure[paramKey];
        }
    });
    var formParams = $('#Form' + formID + '_Property').val();

    if ($(sender).attr('triger') == "datSource") {
        //

        //for (var f_param in formParams)
        //        {
        //    var strNameToMatchWithFormParams = Regex.Replace(f_param, strFormParamPattern, strReplacementParam);
        //            if (dicFormParams.ContainsKey(strNameToMatchWithFormParams))
        //            {
        //                ReportParams[ReportParams.ElementAt(i).Key] = dicFormParams[strNameToMatchWithFormParams];
        //            }
        //        }
        //return getReportByAjax($(sender).attr('data-ReportID'), JSON.stringify(reportParams), formParams)
        return reportParams
    }

    //var url = tbsRootURL + "Report/ShowReport" + '?reportID=' + $(sender).attr('data-ReportID') + '&jsReportParams=' + JSON.stringify(reportParams) + '&FormParams=' + formParams;
    //var popUpObj = window.open(url, '', 'directories=no,toolbar=no,location=no,status=no,menubar=no,width=900,height=600');
    //popUpObj.focus();

    var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = tbsRootURL + "Report/ShowReport";

    var reportID = document.createElement("input");
    reportID.type = "hidden";
    reportID.name = "reportID";
    reportID.value = $(sender).attr('data-ReportID');
    mapForm.appendChild(reportID);

    var jsReportParams = document.createElement("input");
    jsReportParams.type = "hidden";
    jsReportParams.name = "jsReportParams";
    jsReportParams.value = JSON.stringify(reportParams);
    mapForm.appendChild(jsReportParams);

    var FormParams = document.createElement("input");
    FormParams.type = "hidden";
    FormParams.name = "FormParams";
    FormParams.value = JSON.stringify(formParams);
    mapForm.appendChild(FormParams);

    document.body.appendChild(mapForm);

    map = window.open("", "Map", "status=0,title=0,height=900,width=800,scrollbars=1");
    try {
        if (map) {
            mapForm.submit();
            mapForm.removeChild("reportID");
            mapForm.removeChild("jsReportParams");
            mapForm.removeChild("FormParams");
            mapForm.focus();
        } else {
            alert('خطا در نمایش گزارش');
        }
    }
    catch (ex) { }

}

function ToKendoTimePicker(selector) {
    //if ($('#' + selector + '').is(':visible')) {
    if ($('#' + selector + '').is('input')) {
        $('#' + selector + '').kendoTimePicker({ format: "HH:mm" });
        $('#' + selector + '').css('position', 'static');
        //$('#' + selector + '').kendoMaskedTextBox({
        //    mask: "00:00"
        //});
    }
    //}
}

function ToTZTimePicker(selector) {
    if ($('#' + selector + '').is('input')) {
        $('#' + selector + '').inputmask("h:s", { "placeholder": "00/00" });
    }
}

//function ToKendoDataGrid(selector,columns) {
//    if ($('#' + selector + '').is(':visible')) {
//        if ($('#' + selector + '').is('div')) {
//            $('#' + selector + '').kendoGrid({
//                toolbar: kendo.template($("#tzDataGridTemplate").html()),
//                sortable: true,
//                columns: columns
//            });
//        }
//    }
//    $('#' + selector + '> .k-grid-toolbar > .tbsBtn-Add').kendoButton({
//        imageUrl: "Content/Image/Form/DataGrid/Add_x24.png",
//    });
//    $('#' + selector + '> .k-grid-toolbar > .tbsBtn-Edit').kendoButton({
//        imageUrl: "Content/Image/Form/DataGrid/Edit_x24.png",
//    });
//    $('#' + selector + '> .k-grid-toolbar > .tbsBtn-Del').kendoButton({
//        imageUrl: "Content/Image/Form/DataGrid/Delete_x24.png",
//    });
//}

function ToKendoGridView(selector, columns) {
    //if ($('#' + selector + '').is(':visible')) {
    if ($('#' + selector + '').is('div')) {
        $('#' + selector + '').kendoGrid({
            columns: columns
        });
    }
    //}
}


function ToKendoTabStrip(selector) {
    //if ($('#' + selector + '').is(':visible')) {

    if ($('#' + selector + '').is('div')) {
        var tabstrip = $('#' + selector + '').kendoTabStrip({ animation: false }).data("kendoTabStrip");
        tabstrip.select(0);
    }
    //}
}

function ToTazarvLookup(selector, dataValue) {
    if (dataValue == undefined) {
        dataValue = "";
    }
    //if ($('#' + selector + '').is(':visible')) {
    if ($('#' + selector + '').is('div')) {
        $('#' + selector + '').attr('value', dataValue.split('#')[0]);
        $('#' + selector + '').append("<input disabled='disabled' type='text' class='k-textbox' /><button type='button' class='tbsButton k-button' onclick='LookUp_OnClick(this)' >...</button>");
        $('#' + selector + ' input').attr('onchange', $('#' + selector + '').attr('onchange'));
        $('#' + selector + ' input').val(dataValue.split('#')[1]);
        $('#' + selector + '').removeAttr('onchange');
    }
    //}
}

function ToTazarvFieldSet(selector) {
    //if ($('#' + selector + '').is(':visible')) {
    if ($('#' + selector + '').is('fieldSet')) {
        //$('#' + selector + '').css('left', parseInt($('#' + selector + '').css('left')) - 9);
        //$('#' + selector + '').css('top', parseInt($('#' + selector + '').css('top')) + 10);
    }
    //}
}

function getCaptcha(captchaId) {
    $.ajax({
        type: 'GET',
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        url: "Account/GetCaptchaResponse"
    })
        .done(function (data) {            
            let result = JSON.parse(data);
            $('#' + captchaId + 'CaptchaImage').attr('src', 'data:image/gif;base64,' + result.CaptchaImage);
            $('#' + captchaId + 'CaptchaText').attr('data-guid', result.CaptchaGuid);
            $('#' + captchaId + 'CaptchaText').val('');
        });

}

$(document).ready(function () {

    var ctrlScope = angular.element(document.querySelector("[data-ng-controller='Form" + $('form').attr('id') + "_Controller']")).scope();    

    //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 || !tabFieldName) {
            continue;
        }

        if ($(ctrlScope).attr(tabDsName) != undefined) {
            tabDsData = $(ctrlScope).attr(tabDsName).data();
            actionTabs = tabDsData.map(s => s[tabFieldName]);
            if (actionTabs.length > 0) {

                for (let iindex of actionTabs[0].split('$')) {
                    controlID = tbsTabControls[i].id;

                    setTimeout(function () {
                        $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ')').hide();
                        tabcontentId = $('#' + controlID + ' .nav-tabs li:nth-child(' + iindex + ') a').attr('href');
                        $(tabcontentId).removeClass('Active in');
                    }, 0);
                }
            }
        }
        
    }

    //Captcha
    let captchaImageList = $('.captchaImage');
    for (var i = 0; i < captchaImageList.length; i++) {        
        let id = $(captchaImageList[i]).parents('div.input-group').attr('id');
        getCaptcha(id);
    }

    //RichText
    var richTextSelector = $('.tz-rich-textbox');
    const ckeConfigh = [];

    for (var i = 0; i < richTextSelector.length; i++) {

        CKEDITOR.replace((richTextSelector[i]).id, {
            language: 'fa'
        });

        var width = richTextSelector[i].offsetWidth > 0 ? richTextSelector[i].offsetWidth : $(richTextSelector[i]).width();
        var height = richTextSelector[i].offsetHeight > 0 ? richTextSelector[i].offsetHeight : $(richTextSelector[i]).height();
        var left = richTextSelector[i].offsetLeft > 0 ? richTextSelector[i].offsetLeft : $(richTextSelector[i]).offset().left;
        var top = richTextSelector[i].offsetTop > 0 ? richTextSelector[i].offsetTop : $(richTextSelector[i]).offset().top;

        if ($('form').hasClass('isresponsive'))
            ckeConfigh.push(" width: " + width + "px; min-height: " + height + "px !important; left: " + left + "px; top: " + top + "px;");
        else
            ckeConfigh.push("position: absolute; width: " + width + "px; height: " + height + "px !important; left: " + left + "px; top: " + top + "px;");

        var t = 0;
        CKEDITOR.on('instanceReady', function (event) {

            $('#cke_' + richTextSelector[t].id)
                .attr('style', ckeConfigh[t]);

            if ($(richTextSelector[t]).hasClass('tzDisabled')) {
                $('#cke_' + richTextSelector[t].id).addClass('k-state-disabled');
            }

            t < richTextSelector.length - 1 ? t++ : t = t;

            $($($('#cke_' + richTextSelector[t].id).find('#cke_1_contents'))[0]).height((height - 101));

            event.editor.on("beforeCommandExec", function (event) {
                // Show the paste dialog for the paste buttons and right-click paste
                if (event.data.name == "paste") {
                    event.editor._.forcePasteDialog = true;
                }
                // Don't show the paste dialog for Ctrl+Shift+V
                if (event.data.name == "pastetext" && event.data.commandData.from == "keystrokeHandler") {
                    event.cancel();
                }
            })

        });

        try {
            window.atob(richTextSelector[i].value);

            var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } };
            CKEDITOR.instances[richTextSelector[i].id].setData(Base64.decode(richTextSelector[i].value));
        } catch (e) {
            CKEDITOR.instances[richTextSelector[i].id].setData(richTextSelector[i].value);
        }

        ///change Event
        CKEDITOR.instances[richTextSelector[i].id].on('change', function () {

            $($('#' + this.name)[0]).trigger('change');

        });

    }

    ////TBS_Gauge   

    var gaugeSelector = $('.tz-gaugeChart');

    for (var i = 0; i < gaugeSelector.length; i++) {

        gaugeTitle = $('#' + gaugeSelector[i].id).attr('title');
        if (gaugeTitle.length == 0) gaugeTitle = '...';
        gaugeValue = $('#' + gaugeSelector[i].id).attr('value');
        minValue = $('#' + gaugeSelector[i].id).attr('minvalue') * 1;
        maxValue = $('#' + gaugeSelector[i].id).attr('maxvalue') * 1;
        startAngle = $('#' + gaugeSelector[i].id).attr('startAngle') * 1;
        endAngle = $('#' + gaugeSelector[i].id).attr('endAngle') * 1;
        ticksMinor = $('#' + gaugeSelector[i].id).attr('minorDivisionCount');
        ticksMajor = $('#' + gaugeSelector[i].id).attr('majorDivisionCount');
        width = $('#' + gaugeSelector[i].id).css('width');
        height = $('#' + gaugeSelector[i].id).css('height');

        $('#' + gaugeSelector[i].id)
            .jqxGauge({
                border: { showGradient: true, size: '2%', style: { stroke: '#898989' }, visible: true },
                caption: { value: gaugeTitle, position: 'bottom', offset: [0, 35], visible: true },
                labels: { interval: ticksMajor, visible: true, formatValue: function (value) { return value; } },
                ranges: eval(ctrlScope["ranges_" + gaugeSelector[i].id]),
                ticksMinor: { interval: ticksMinor, size: '5%' },
                ticksMajor: { interval: ticksMajor, size: '9%' },
                colorScheme: "scheme06",
                animationDuration: 1200,
                min: minValue, max: maxValue,
                startAngle: startAngle, endAngle: endAngle,
                width: width,
                height: height
            })
            .jqxGauge('value', 0);

        gaugeValueText = '<label id="' + gaugeSelector[i].id + '_gaugeValue" class="gaugeValue" style="' +
            'top:' + ($('#' + gaugeSelector[i].id + ' .jqx-gauge-caption').attr('y') - 50) + 'px !important;' +
            'left:' + (($('#' + gaugeSelector[i].id + ' .jqx-gauge-caption').attr('x') * 1) + ($('#' + gaugeSelector[i].id + ' .jqx-gauge-caption').attr('width') * 1) / 2 - 21) + 'px !important;"></label>';


        $('#' + gaugeSelector[i].id).append($(gaugeValueText));

        $('#' + gaugeSelector[i].id).on('valueChanging', function (e) {
            v1 = Math.round(e.args.value);
            $('#' + $(this).attr('id') + '_gaugeValue').html(v1);
        });
    }
    setTimeout(function () {
        var gaugeSelector = $('.tz-gaugeChart');
        for (var i = 0; i < gaugeSelector.length; i++) {
            gaugeValue = $('#' + gaugeSelector[i].id).attr('value');
            try {
                $('#' + gaugeSelector[i].id).jqxGauge('value', (gaugeValue * 1));
            }
            catch (e) { }
        }
    }, 0);

    ////TBS_LineChart
    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 = 'Color';
        let chartColumnsColor = [];
        let chartsData = [];

        chartsData = eval(ctrlScope["chartsData_" + lineChartSelector[i].id]);
        if (chartsData && chartsData.length > 0) {
            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');
            chartColumnsColor = chartsData.map(s => s[colorField]);
            let schemeName = 'scheme0' + (++i);
            //$.jqx._jqxChart.prototype.colorSchemes.push({ name: 'myScheme', colors: ['#ffff00', '#ff0000', '#ccff00', '#00ffff', '#aaaaaa'] });
            $.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 () {
        var lineChartSelector = $('.tz-lineChart');
        for (var i = 0; i < lineChartSelector.length; i++) {
            try {
                $('#' + lineChartSelector[i].id).jqxChart(chartSettings)
                $("text:contains(www.jqwidgets.com)").css('display', 'none');
            }
            catch (e) { }
        }
    }, 20);

    $(".tzfloatTexbox").inputmask('decimal', { rightAlign: true });

    $('input[type="radio"]').bind('click', function () {
        $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('onchange');
    });


    var ctrlDown = false,
        ctrlKey = 17,
        cmdKey = 91,
        vKey = 86,
        cKey = 67;

    $(document).keydown(function (e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
    }).keyup(function (e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
    });


    $('.tzNumericTexbox').keydown(function (e) {
        //if ((e.which < '0'.charCodeAt(0) || e.which > "9".charCodeAt(0)) && (e.which != '.'.charCodeAt(0)))
        if (e.which == 9) {
            $('.tzDatePicker').blur();
            return;
        }
        if (!((e.which >= 48 && e.which <= 57) // Numbers
            || (e.which >= 96 && e.which <= 105) // numpad
            || (e.which >= 35 && e.which <= 40) //End Home Left arrow Up arrow Right arrow Down arrow
            || (e.which == 16) //Shift
            || (e.which == 8) //Backspace
            || (e.which == 45) //Insert
            || (e.which == 46) //Delete
            || (ctrlDown && (e.which == 86 || e.which == 67 || e.which == 97 || e.which == 65)) //ctrl-c and ctrl-v and ctrl-Aa
            || (e.which == 109 && $(this).val().indexOf("-") < 0 && this.selectionStart <= 0)  // -
        ))
            e.preventDefault();
    });

    $('.tzDatePicker').blur(function (e) {
        var arr = $(this).val().split('/');
        if (!$.isNumeric(arr[0]) || !$.isNumeric(arr[1]) || !$.isNumeric(arr[2])) {
            $(this).val('');
            return;
        }

        if ($(this).hasClass('tzGregorianMode')) {
            if (arr[1] > 12) {
                $(this).val('');
                return;
            }
            if (arr[2] > 31) {
                $(this).val('');
                return;
            }
            if (arr[0] > 2100 || arr[0] < 1940) {
                $(this).val('');
                return;
            }
        }
        else {
            if (arr[0] > 1500 || arr[0] < 1200) {
                $(this).val('');
                return;
            }
            if (arr[1] > 12) {
                $(this).val('');
                return;
            }
            if (arr[2] > 31) {
                $(this).val('');
                return;
            }
        }

    });

    $('.tzDatePicker').keydown(function (e) {
        //if (e.which == 9 || e.currentTarget.value.replaceAll('__', '').length == 10) {

        if (e.which == 9) {
            $('.tzDatePicker').blur();
            return;
        }
        var arr = $(this).val().split('/');
        if (arr[0] > 1500 || arr[0] < 1200) {
            $(this).val('');
            return;
        }
        if (arr[1] > 12) {
            $(this).val(arr[0]);
            return;
        }
        if (arr[2] > 31) {
            $(this).val(arr[0] + arr[1]);
            return;
        }

        //if ((e.which < '0'.charCodeAt(0) || e.which > "9".charCodeAt(0)) && (e.which != '.'.charCodeAt(0)))
        if (!((e.which >= 48 && e.which <= 57) // Numbers
            || (e.which >= 96 && e.which <= 105) // numpad
            || (e.which >= 35 && e.which <= 40) //End Home Left arrow Up arrow Right arrow Down arrow
            || (e.which == 16) //Shift
            || (e.which == 8) //Backspace
            || (e.which == 45) //Insert
            || (e.which == 46) //Delete
            || (e.which == 191) // slash
            || (e.which == 111) // Numpad slash
        ))
            e.preventDefault();
    });

    $('.tzTimePicker').keydown(function (e) {
        if (e.which == 9) {
            $('.tzDatePicker').blur();
            return;
        }
        //if ((e.which < '0'.charCodeAt(0) || e.which > "9".charCodeAt(0)) && (e.which != '.'.charCodeAt(0)))
        if (!((e.which >= 48 && e.which <= 57) // Numbers
            || (e.which >= 96 && e.which <= 105) // numpad
            || (e.which >= 35 && e.which <= 40) //End Home Left arrow Up arrow Right arrow Down arrow
            || (e.which == 16) //Shift
            || (e.which == 8) //Backspace
            || (e.which == 45) //Insert
            || (e.which == 46) //Delete
            || (e.which == 186) // : for all Without FireFox
            || (e.which == 59) // : for Firfox
        ))
            e.preventDefault();
    });


    if ($("body .Popup_ConditionSection > button").length > 0)
        $("body[data-ng-app='TBSFormApp']").css('padding-top', '46px');

    $('.tzGridView').each(function (index, item) {

        setGridViewSelectedData(item);
    });

    $('.tzPlayer').each(function (index, item) {
        setAudioSrc(item);
    })

    $('.tzFileUpload').each(function (index, item) {
        //setUploadeHref(item);
        setUploadeData(item);
    })

    $('.tzTextBox').each(function (index, item) {
        $(item).keydown(function (e) {
            if (e.ctrlKey) {
                if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
                    $(item).select();
                }
            } else {

            }
        });
        $(item).bind("paste", function (e) {
            setTimeout(function () {
                textBoxCharacterHandle(item);
            }, 100);

        });
        $(item).keypress(function (e) {
            var currentTXBox = this;
            setTimeout(function () {
                textBoxCharacterHandle(currentTXBox);
            }, 100);
        })
    })
    function textBoxCharacterHandle(item) {
        var position = item.selectionStart;
        $(item).val($(item).val().replace(/ک/g, 'ک').replace(/ی/g, 'ی').replace(/ى/g, 'ی').replace(/ي/g, 'ی').replace(/ك/g, 'ک'));
        if (item.selectionStart != position) {
            item.selectionStart = position;
        }
        item.selectionEnd = position
    }
    if ($('.GeneratedForm').length > 0) {
        if ($('.GeneratedForm').html().indexOf('kendo') < 0)
            setTimeout(function () { FormInitialized(); }, 3000);
    }

    //if (Stimulsoft && Stimulsoft.Base && Stimulsoft.Base.StiLicense && Stimulsoft.Base.StiLicense.Key) {
    //    Stimulsoft.Base.StiLicense.Key = "6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn0s4gy0Fr5YoUZ9V00Y0igCSFQzwEqYBh/N77k4f0fWXTHW5rqeBNLkaurJDenJ9o97TyqHs9HfvINK18Uwzsc/bG01Rq+x3H3Rf+g7AY92gvWmp7VA2Uxa30Q97f61siWz2dE5kdBVcCnSFzC6awE74JzDcJMj8OuxplqB1CYcpoPcOjKy1PiATlC3UsBaLEXsok1xxtRMQ283r282tkh8XQitsxtTczAJBxijuJNfziYhci2jResWXK51ygOOEbVAxmpflujkJ8oEVHkOA/CjX6bGx05pNZ6oSIu9H8deF94MyqIwcdeirCe60GbIQByQtLimfxbIZnO35X3fs/94av0ODfELqrQEpLrpU6FNeHttvlMc5UVrT4K+8lPbqR8Hq0PFWmFrbVIYSi7tAVFMMe2D1C59NWyLu3AkrD3No7YhLVh7LV0Tttr/8FrcZ8xirBPcMZCIGrRIesrHxOsZH2V8t/t0GXCnLLAWX+TNvdNXkB8cF2y9ZXf1enI064yE5dwMs2fQ0yOUG/xornE";
    //}
    try {
        if (StiOptions && StiOptions.WebServer) {
            if (StiOptions.WebServer.encryptData)
                StiOptions.WebServer.encryptData = false;

            if (StiOptions.WebServer.checkDataAdaptersVersion)
                StiOptions.WebServer.checkDataAdaptersVersion = false;
        }

    } catch (e) {

    }
});

function FormInitialized() {

    $('.k-filtercell').each(function (index, item) {
        $(item.children[0].children[0].children[0]).keyup(function () {
            $(this).val($(this).val().replace(/ک/g, 'ک').replace(/ی/g, 'ی').replace(/ى/g, 'ی').replace(/ي/g, 'ی').replace(/ك/g, 'ک'));

        });
        console.log(item);
    })

    $('form .k-grid-content tbody tr[role=row]').dblclick(function (el) { GridView_OnClick($(this).parent().parent().parent()) });

    ////console.log('heeeeeey');
    //$.when(function () {
    //$('.tbsDataGridBtn-Add').kendoButton({
    //    imageUrl: tbsRootURL + "/Content/Image/Form/DataGrid/Add_x24.png",
    //});
    //$('.tbsDataGridBtn-Edit').kendoButton({
    //    imageUrl: tbsRootURL + "/Content/Image/Form/DataGrid/Edit_x24.png",
    //});
    //$('.tbsDataGridBtn-Del').kendoButton({
    //    imageUrl: tbsRootURL + "/Content/Image/Form/DataGrid/Delete_x24.png",
    //});


    //}).done(function () {
    var ss = $("form.GeneratedForm");
    ss.each(function (index, element) {
        $(element).kendoValidator({
            validate: function (e) {
                $("span.k-invalid-msg").hide();
            }
        });
        controller = angular.element(document.querySelector("[data-ng-controller='Form" + $(element).attr('ID') + "_Controller']")).scope();
        controller.FormDone();
        //});
    }).promise().done(function () {
        ////console.log("Form End Rendered: " + new Date());



        AjaxStopORFormRenderd();


        //$(".tzDisabled").each(function (index, element) {
        //    EnableComponent(element, false, this);
        //});
        ////}).done(function () {
        //$(".tzInVisible").each(function (index, element) {
        //    ShowComponent(element, false, this);
        //});
        //$(".tzMandatory").each(function (index, element) {
        //    ChangeRequirement($(element), true, this);
        //});

    });


    $(document).ready(function () {
        $(document).ajaxStop(function () {
            AjaxStopORFormRenderd();
        });
    });



    function AjaxStopORFormRenderd() {

        window.setTimeout(function () {
            if (AjaxCountInProcess == 0 && firstReloadFlag == 1) {
                //change visibility state of components
                for (var i in ComponentVisibiltyRepository) {
                    var item = ComponentVisibiltyRepository[i]
                    ShowComponent(item.key, item.value, item.raiser);
                }
                ComponentVisibiltyRepository = [];

                //change activity state of components
                for (var i in ComponentsDiplayStatus) {
                    var item = ComponentsDiplayStatus[i]
                    $.each(item.key.split(","), function (index, elementID) {
                        EnableComponent($('#' + elementID), item.value, item.raiser);
                    });
                }
                ComponentsDiplayStatus = [];

                $("select[kendo-drop-down-list]").each(function () {
                    var cb = $(this).getKendoDropDownList();
                    cb.list.width("auto");
                    if (cb && cb._bound == false) {
                        cb.dataSource.read();
                    }
                });


                $(".k-dropdown").keydown(function (event) {
                    if (event.which == "46")
                        ClearComponents($(this).find('select').attr('id'), true)
                });

                $('input.decimal-mark')
                    .inputmask("numeric", {
                        radixPoint: ".",
                        autoGroup: true,
                        groupSeparator: ",",
                        digits: 2,
                        rightAlign: false,
                        allowMinus: true
                    }).on('blur', function () {
                        $(this).trigger('onchange');
                    });

                $('body').on('scroll', function (e) {
                    $("select.tzComboBox").each(function () {
                        var ddl = $(this).getKendoDropDownList();
                        if (ddl) {
                            ddl.close();
                        }
                    });
                });

                $('.override-Kendo-Width > ul.nav.nav-tabs').each(function (index, element) {
                    $(element).parent().prepend($(element)[0].outerHTML);
                    $(element).remove()
                })

                $(".tzDisabled").each(function (index, element) {
                    EnableComponent(element, false, this);
                });
                //}).done(function () {
                $(".tzInVisible").each(function (index, element) {
                    ShowComponent(element, false, this);
                });
                $(".tzMandatory").each(function (index, element) {
                    ChangeRequirement($(element), true, this);
                });

                $('textarea.tz-rich-textbox').each(function (index, item) {
                    var table = $(item).closest('table.k-editor');
                    $(table).css("position", $(item).css("position"));
                    $(table).css("top", $(item).css("top"));
                    $(table).css("left", $(item).css("left"));
                    //console.log(table)
                });


                firstReloadFlag = 0;
                $(".InitilizingDivSpinner").hide();
                $(".Popup_ConditionSection").removeAttr('disabled');

                $(".Popup_ConditionSection").children('button').each(function (index, child) {
                    $(child).removeAttr('disabled');
                });
                $(document).ready(function () {
                    //$(".multiSelectBox").bind("click", function (e) {
                    //    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);
                    //});
                    for (var i = 0; i < divIDs.length; i++) {
                        var tableContent = $($($('#' + divIDs[i])[0]).find('.k-grid-content')[0]).find('table > tbody > tr');
                        for (var j = 0; j < tableContent.length; j++) {
                            $(tableContent[j]).find('td > span').each(function (index, item) {
                                if ($(item).attr('ng-bind') == 'dataItem.' + columnFilters[i]) {
                                    $(mustBeSelecteds[i]).each(function (splitIndex, splitItem) {
                                        if ($(item).text() == splitItem) {
                                            $(item).parent().parent().find('.multiSelectBox')[0].checked = true;
                                            //$($(item).parent().parent().find('.multiSelectBox')[0]).addClass('k-state-selected');
                                            //$(item).parent().parent().addClass('k-state-selected');
                                            //$(item).parent().parent().addClass('k-alt');
                                            //این ردیف باید select شود

                                        }
                                    });

                                }
                            });
                        }
                    }
                });

                //console.log("end of load page=> " + new Date().toUTCString())


            }

        }, 500);
    }

    $('body').on('scroll', function (e) {
        $('#contentDiv.jqx-rc-all').parent().hide();
    });

    //.done(function () {
    $("input[type='checkbox'][onchange]").each(function (index, element) {

        if ($(element).attr('ng-checked') == 'true')
            $(element).trigger('onchange');
    });
    //})
    //.done(function () {
    $("input[type='radio']:not([novalue])[onchange]").each(function (index, element) {
        $(element).trigger('onchange');
    });
    //})

    //$("form[id='" + formID + "'] .tzDisabled").each(function (index, element) {
    //    EnableComponent(element, false);
    //})

    $('legend').click(function() {
        $(this).parent().children(":first").toggle(300);
    })


}
    //----------------- TZRadioButton Default Value ↓

