// #region Packages Events
//function tsPackagesOnShow(e) {
//}
//function tsPackagesOnSelect(e) {
//    initializeTabsImage(e.item.id);
//} 
//function tsPackagesOnActivate(e) {
//    if (e.item.id != 'AdvanceSearchTab' && e.item.id != 'MessagesTab' && e.item.id != 'SchedulerTab' && e.item.id != 'HomeDashboardTab')
//        initializePackagesTab(e.item.id);

//    else if (e.item.id == 'MessagesTab') {
//        removeMessageseGridFieldsForXSDisplay();
//    }
//}
//function tsPackagesOnContentLoad(e) {
//}
//function tsPackagesOnError(e) {
//}
// #endregion Packages Events

//#region Initializations
function PageReady_ReadData() {
    //Initial_HomePageCharts();
    initialAdvanceSearchParameters();
    HomePackagesCountLabel_cartable_ReadFromServer();
    HomePackagesCountLabel_groupTask_ReadFromServer();
    HomePackagesCountLabel_SuccessorTask_ReadFromServer();
    HomeMessageCountLabel_ReadFromServer();
}
function initializeTabsImage(tabID) {
    if (tabID != undefined && tabID != "") {
        //$('#tsPackages > ul > li').each(function (index, tabHead) {
        //    $('#' + tabHead.id + ' a img').attr('src', (tabHead.id == 'AdvanceSearchTab') ? '@Url.Content("~/~/Content/Image/TaskManager/Search-Black.png")' : (tabHead.id == 'MessagesTab') ? '@Url.Content("~/~/Content/Image/TaskManager/Massege-B.png")' : (tabHead.id == 'Package-2') ? '@Url.Content("~/~/Content/Image/TaskManager/Task-B.png")' : (tabHead.id == 'Package-1') ? '@Url.Content("~/~/Content/Image/TaskManager/GroupTask-B.png")' : '@Url.Content("~/~/Content/Image/TaskManager/Defult-B.png")');
        //})
        //$('#' + tabID + ' a img').attr('src', (tabID == 'AdvanceSearchTab') ? '@Url.Content("~/~/Content/Image/TaskManager/Search-W.png")' : (tabID == 'MessagesTab') ? '@Url.Content("~/~/Content/Image/TaskManager/Massege-W.png")' : (tabID == 'Package-2') ? '@Url.Content("~/~/Content/Image/TaskManager/Task-Withe.png")' : (tabID == 'Package-1') ? '@Url.Content("~/~/Content/Image/TaskManager/GroupTask-W.png")' : '@Url.Content("~/~/Content/Image/TaskManager/Defult-W.png")');
        //$('#tsPackages > ul > li').each(function (index, tabHead) {
        //    $('#' + tabHead.id + ' a img').attr('src', (tabHead.id == 'AdvanceSearchTab') ? tbsRootURL + '/Content/Image/TaskManager/Search-Black.png' : (tabHead.id == 'MessagesTab') ? tbsRootURL + '/Content/Image/TaskManager/Massege-B.png' : (tabHead.id == 'Package-2') ? tbsRootURL + '/Content/Image/TaskManager/Task-B.png' : (tabHead.id == 'Package-1') ? tbsRootURL + '/Content/Image/TaskManager/GroupTask-B.png' : tbsRootURL + '/Content/Image/TaskManager/Defult-B.png');
        //})
        //$('#' + tabID + ' a img').attr('src', (tabID == 'AdvanceSearchTab') ? tbsRootURL + '/Content/Image/TaskManager/Search-W.png' : (tabID == 'MessagesTab') ? tbsRootURL + '/Content/Image/TaskManager/Massege-W.png' : (tabID == 'Package-2') ? tbsRootURL + '/Content/Image/TaskManager/Task-Withe.png' : (tabID == 'Package-1') ? tbsRootURL + '/Content/Image/TaskManager/GroupTask-W.png' : tbsRootURL + '/Content/Image/TaskManager/Defult-W.png');
        $('#tsPackages > ul > li').each(function (index, tabHead) {
            var ResultBlack = $('#' + tabHead.id + '> a > .TabImage').css('background-image');
            if (ResultBlack != undefined && ResultBlack != "") {
                ResultBlack = ResultBlack.replace("-W.png", "-B.png");
                $('#' + tabHead.id + '> a > .TabImage').css('background-image', ResultBlack);
            }
        });
        var ResultWhite = $('#' + tabID + '> a > .TabImage').css('background-image');
        if (ResultWhite != undefined) {
            ResultWhite = ResultWhite.replace("-B.png", "-W.png");
            $('#' + tabID + '> a > .TabImage').css('background-image', ResultWhite);
        }
    }
}
function initializePackagesTab(packagesTabID) {
    //if ($('#grd' + packagesTabID + 'sTasks').data('kendoGrid').dataSource.data().length < 1)
    var InnerGridElement = $('#grd' + packagesTabID + 'sTasks');
    var InnerGridItem = InnerGridElement.getKendoGrid();
    if (InnerGridItem != undefined) {
        InnerGridItem.dataSource.read();
    }
    if (packagesTabID != 'Package-1') {
        if ($('#lvTaskGroupAccessPanelPackage').data('kendoListView') != null && $('#lvTaskGroupAccessPanelPackage').data('kendoListView').dataSource.data().length < 1)
            $('#lvTaskGroupAccessPanelPackage').data('kendoListView').dataSource.read();
        if ($('#lvFormAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvFormAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvFormAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();
        if ($('#lvWorkflowAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvWorkflowAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvWorkflowAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();
        if ($('#lvReportAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvReportAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvReportAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();

        if ($('#lvModalTaskGroupAccessPanelPackage').data('kendoListView') != null && $('#lvModalTaskGroupAccessPanelPackage').data('kendoListView').dataSource.data().length < 1)
            $('#lvModalTaskGroupAccessPanelPackage').data('kendoListView').dataSource.read();
        if ($('#lvModalFormAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvModalFormAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvModalFormAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();
        if ($('#lvModalWorkflowAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvModalWorkflowAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvModalWorkflowAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();
        if ($('#lvModalReportAccessPanel' + packagesTabID).data('kendoListView') != null && $('#lvModalReportAccessPanel' + packagesTabID).data('kendoListView').dataSource.data().length < 1)
            $('#lvModalReportAccessPanel' + packagesTabID).data('kendoListView').dataSource.read();

        if (packagesTabID == 'Package-2') {
            HomePackagesCountLabel_cartable_ReadFromServer();
        }
    }
    if (InnerGridItem != undefined) {
        removeCartableGridFieldsForXSDisplay($(InnerGridElement));
    }
}
//#endregion Initializations

//#region Open WF
function openTasksForm(taskID) {
    window.open(tbsRootURL + 'Task' + '?TaskID=' + taskID, "'" + taskID + "'");
    //window.open('@Url.Action("Index", "NewWorkFlow")' + '?WorkFlowID=' + accessPanelItem.WorkflowId, '_blank');
    //
    //HomeCurrentCartable_ChangeItemStatusToType1_ByTaskID(taskID);
    HomeCartable_ChangeItemStatus_ByTaskID(taskID, 1);
}
//function openTaskGroupsForm(taskID) {
//    window.open(tbsRootURL + 'Task' + '?TaskID=' + taskID, '_blank');
////    HomeCartable_ChangeItemStatus_ByTaskID(taskID, 1);
//    HomeCartable_ChangeItemStatus_ByTaskID(taskID, 1);
//}

function openUserList(fullScreenPopUp, queryParam) {
    debugger
    //OpenPopUp('dfdsfsdf', true)
    OpenPopUp(tbsRootURL + 'AAA', true, fullScreenPopUp, '', '', queryParam);
    //window.open('@Url.Action("Index", "NewWorkFlow")' + '?WorkFlowID=' + accessPanelItem.WorkflowId, '_blank');

}

function openTasksFormforSuccessor(taskID, SuccessorUserId) {
    window.open(tbsRootURL + 'Task' + '?TaskID=' + taskID + '&SuccessorUserId=' + SuccessorUserId, "'" + taskID + "'", 'directories=no,toolbar=no,location=no,status=no,menubar=no,resizable=yes,fullscreen=no,height=700,width=1000');
    //HomeCurrentCartable_ChangeItemStatusToType1_ByTaskID(taskID);
    HomeCartable_ChangeItemStatus_ByTaskID(taskID, 1);
}
function openTasksWithWorkflowInstanceID(WorkflowInstanceID) {
    //window.open('@Url.Action("IndexWithWorkflowInstance", "Task")' + '?WorkflowInstanceId=' + WorkflowInstanceID, "'" + WorkflowInstanceID + "'", 'directories=no,toolbar=no,location=no,status=no,menubar=no,resizable=yes,fullscreen=no,height=700,width=1000');
    //window.open(tbsRootURL + 'Task/IndexWithWorkflowInstance' + '?WorkflowInstanceId=' + WorkflowInstanceID, "'" + WorkflowInstanceID + "'", 'directories=no,toolbar=no,location=no,status=no,menubar=no,resizable=yes,fullscreen=no,height=700,width=1000');
    window.open(tbsRootURL + 'Task/IndexWithWorkflowInstance' + '?WorkflowInstanceId=' + WorkflowInstanceID, "'" + WorkflowInstanceID + "'");
}

//#endregion Open WF

// #region Displays And Responsive Funcs
//function TabStripFixSize() {
//    var tabStripElement = $("#tsPackages");
//    var tabStrip = tabStripElement.data("kendoTabStrip");
//    tabStripElement.children(".k-content").css('top', tabStripElement.children(".k-tabstrip-items").height() + 4);
//    //tabStripElement.children(".k-content").css('top', tabStripElement.children(".k-tabstrip-items").css('height'));
//}
function removeCartableGridFieldsForXSDisplay(Element) {
    var WindowWidth = $(window).width()
    if (WindowWidth < 768) {
        $(Element).getKendoGrid().hideColumn("WorkflowInstanceName");
        $(Element).getKendoGrid().hideColumn("UserName");
        $(Element).getKendoGrid().hideColumn("GroupName");
        $(Element).getKendoGrid().hideColumn("RoleName");
    }
    else {
        $(Element).getKendoGrid().showColumn("WorkflowInstanceName");
        $(Element).getKendoGrid().showColumn("UserName");
        $(Element).getKendoGrid().showColumn("GroupName");
        $(Element).getKendoGrid().showColumn("RoleName");
    }
}
function removeMessageseGridFieldsForXSDisplay() {
    var WindowWidth = $(window).width();
    var InboxMessageGrid = $('#InboxMessageGrids').getKendoGrid();
    //var OutboxMessageGrid = $('#OutboxMessageGrids').getKendoGrid();
    if (WindowWidth < 768) {
        InboxMessageGrid.hideColumn("CreatePersianDate");
        InboxMessageGrid.hideColumn("IsDirty");
        InboxMessageGrid.hideColumn("IsDeleted");
    }
    else {
        InboxMessageGrid.showColumn("CreatePersianDate");
        InboxMessageGrid.showColumn("IsDirty");
        InboxMessageGrid.showColumn("IsDeleted");
    }
}
window.onresize = function (event) {
    //resizeGrid();
    HomeCharts_Refresh();

    var SelectedTabWithCartable = $('#tsPackages > .k-content.k-state-active > .dvWorkflowGrids > .k-grid');
    if (SelectedTabWithCartable != undefined && SelectedTabWithCartable != null && SelectedTabWithCartable.getKendoGrid() != null) {
        removeCartableGridFieldsForXSDisplay(SelectedTabWithCartable);
    }
    else {
        SelectedTabWithCartable = $('#tsPackages > .k-content.k-state-active > .MesssagesTabContent .k-grid');
        if (SelectedTabWithCartable != undefined && SelectedTabWithCartable != null && SelectedTabWithCartable.getKendoGrid() != null) {
            removeMessageseGridFieldsForXSDisplay();
        }
    }
}
function DisableGridDiv_ToggleDivVisibility() {
    $('.collapse').collapse('hide');
}
//function DisableDiv_Toggle() {
//    $(".DisableDiv").toggle();
//}
function DisableDiv_Toggle(boolForceSatus) {
    if (boolForceSatus != undefined) {
        if (boolForceSatus == true) {
            $(".DisableDiv").show();
            //console.log(.log("$(.DisableDiv).show()");
        }
        else {
            $(".DisableDiv").hide();
            //console.log(.log("$(.DisableDiv).hide()");
        }
    }
    else {
        $(".DisableDiv").toggle();
        //console.log(.log("$(.DisableDiv).toggle()");
    }

}
// #endregion Displays And Responsive Funcs

//#region Home Charts
function Initial_HomePageCharts() {
    //  Initial_HomePage_PieChart();
    //  Initial_HomePage_BarChart();
}
//function Initial_HomePage_PieChart() {
//    var HomePie = $('#tsPackages .Dashboard_Body .Dashboard_Element #Piechart');
//    HomePie.kendoChart({
//        dataSource: {
//            transport: {
//                read: {
//                    url: tbsRootURL + "Home/DoingTasksProportion_Read"
//                }
//            },
//        },
//        theme: 'Material',
//        legend: {
//            position: "bottom"
//        },
//        seriesDefaults: {
//            labels: {
//                visible: true,
//                format: "{0}"
//            }
//        },
//        series: [{
//            type: "pie",
//            field: "value",
//            categoryField: "category"
//        }],
//        seriesColors: MyColorSeriesTheme,
//        tooltip: {
//            visible: true,
//            format: "{0}"
//        }
//    });

//}
//function Initial_HomePage_BarChart() {
//    var HomePie = $('#tsPackages .Dashboard_Body .Dashboard_Element #Barchart');
//    var ChartType;
//    if ($(window).width() < 922) {
//        ChartType = "bar";
//    }
//    else {
//        ChartType = "column";
//    }
//    HomePie.kendoChart({
//        dataSource: {
//            transport: {
//                read: {
//                    url: tbsRootURL + "Home/TaskCountPerWorkFlow_Read"
//                }
//            },

//        },
//        theme: 'Material',
//        legend: {
//            position: "bottom"
//        },
//        series:
//                [{
//                    field: "value",
//                    name: "در حال انجام"
//                },
//                {
//                    field: "value2",
//                    name: "جدید"
//                },
//                {
//                    field: "value3",
//                    name: "در انتظار"
//                }],
//        seriesColors: MyColorSeriesTheme,
//        seriesDefaults: {
//            type: ChartType,
//            spacing: 0.1,
//            gap: 0.5
//        },
//        categoryAxis: {
//            field: "category",
//            majorGridLines: {
//                visible: true
//            }
//        },
//        tooltip: {
//            visible: true,
//            format: "{0}"
//        }

//    });
//}
function HomeCharts_Refresh() {
    var chart = $('#tsPackages .Dashboard_Body .Dashboard_Element #Barchart').getKendoChart();
    if (chart != null) {
        if ($(window).width() < 922) {
            chart.options.series[0].type = "bar";
            chart.options.series[0].gap = 0.5;
            chart.options.series[0].spacing = 0.1;
        }
        else {
            chart.options.series[0].type = "column";
            chart.options.series[0].gap = 0.5;
            chart.options.series[0].spacing = 0.1;
        }
        chart.refresh();
    }

}
var MyColorSeriesTheme = ["#f35800", "rgb(160, 167, 0)", "#009bd7"];
//#endregion Home Charts

// #region TaskNewCount And Grids Updates

//New Count
function HomePackagesCountLabel_add(tabTypeName, tabId, countToAdd) {
    if (countToAdd != undefined) {
        var controller = angular.element(document.querySelector("[data-ng-controller='Home_Controller']")).scope();
        var tabElementIdAngularObjectName = tabTypeName + tabId;

        controller.$apply(function () {
            switch (tabTypeName) {
                case "CartableTab":
                    var OldContent = controller.packagesNewTasksCount[tabElementIdAngularObjectName];
                    var newContent = OldContent + countToAdd;
                    controller.packagesNewTasksCount[tabElementIdAngularObjectName] = newContent;
                    break;
                case "GeneralUserTab":
                    var OldContent = controller.UnreadMessagesCount[tabElementIdAngularObjectName];
                    var newContent = OldContent + countToAdd;
                    controller.UnreadMessagesCount[tabElementIdAngularObjectName] = newContent;
                    break;
            }
        });
    }
}
function HomePackagesCountLabel_set(tabTypeName, tabID, countToSet) {

    if (countToSet != undefined) {
        var controller = angular.element(document.querySelector("[data-ng-controller='Home_Controller']")).scope();
        var tabElementIdAngularObjectName = tabTypeName + tabID;
        controller.$apply(function () {
            switch (tabTypeName) {
                case "CartableTab":
                    controller.packagesNewTasksCount[tabElementIdAngularObjectName] = countToSet;
                    break;
                case "GeneralUserTab":
                    controller.UnreadMessagesCount[tabElementIdAngularObjectName] = countToSet;
                    break;
            }
        });
    }
}

//Saved Count
function HomePackagesSavedCountLabel_add(tabTypeName, tabId, countToAdd) {
    if (countToAdd != undefined) {
        var controller = angular.element(document.querySelector("[data-ng-controller='Home_Controller']")).scope();
        var tabElementIdAngularObjectName = tabTypeName + tabId;

        controller.$apply(function () {
            switch (tabTypeName) {
                case "CartableTab":
                    var OldContent = controller.packagesSavedTasksCount[tabElementIdAngularObjectName];
                    var newContent = OldContent + countToAdd;
                    controller.packagesSavedTasksCount[tabElementIdAngularObjectName] = newContent;
                    break;
                case "GeneralUserTab":
                    var OldContent = controller.UnreadSavedMessagesCount[tabElementIdAngularObjectName];
                    var newContent = OldContent + countToAdd;
                    controller.UnreadSavedMessagesCount[tabElementIdAngularObjectName] = newContent;
                    break;
            }
        });

    }
}
function HomePackagesSavedCountLabel_set(tabTypeName, tabID, countToSet) {

    if (countToSet != undefined) {
        var controller = angular.element(document.querySelector("[data-ng-controller='Home_Controller']")).scope();
        var tabElementIdAngularObjectName = tabTypeName + tabID;
        controller.$apply(function () {
            switch (tabTypeName) {
                case "CartableTab":
                    controller.packagesSavedTasksCount[tabElementIdAngularObjectName] = countToSet;
                    break;
                case "GeneralUserTab":
                    controller.UnreadSavedMessagesCount[tabElementIdAngularObjectName] = countToSet;
                    break;
            }
        });
    }

}


function HomePackagesCountLabel_cartable_ReadFromServer() {

    $.ajax({
        type: "POST",
        url: tbsRootURL + "Task/GetNewTaskCount",
        contentType: "application/json",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        dataType: "json",
        async: false,
        //data: JSON.stringify({
        //    objectPackageID: accessPanelItem.ID
        //    , isInFavorite: accessPanelItem.IsInFavorite
        //}),
        success: function (result) {
            if (result.Errors) {
                ErrorHandler(result);
            }
            else {
                HomePackagesCountLabel_set('CartableTab', '1', result);
            }
        }
    });
}

function HomePackagesCountLabel_groupTask_ReadFromServer() {
    //message-tasks-Grouptasks
    $.ajax({
        type: "POST",
        url: tbsRootURL + "Task/GetGroupsNewTaskCount",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        contentType: "application/json",
        dataType: "json",
        async: false,
        //data: JSON.stringify({
        //    objectPackageID: accessPanelItem.ID
        //    , isInFavorite: accessPanelItem.IsInFavorite
        //}),
        success: function (result) {
            if (result.Errors) {
                ErrorHandler(result);
            }
            else {
                HomePackagesCountLabel_set('CartableTab', '2', result);
            }
        }
    });
}

function HomePackagesCountLabel_SuccessorTask_ReadFromServer() {
    $.ajax({
        type: "POST",
        url: tbsRootURL + "Task/GetSuccessorNewTaskCount",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        contentType: "application/json",
        dataType: "json",
        async: false,
        data: JSON.stringify({
            packageId: 3,
            packageType: 'GeneralUserTab',
            jsFilterParams: null,
            "__RequestVerificationToken": $('#m_RequestVerificationToken').val()
        }),
        success: function (result) {
            if (result.Errors) {
                ErrorHandler(result);
            }
            else {
                HomePackagesCountLabel_set('GeneralUserTab', '3', result);
            }
        }
    });

}

function HomeMessageCountLabel_ReadFromServer() {
    $.ajax({
        type: "POST",
        headers: {
            'RequestVerificationToken': $('#m_RequestVerificationToken').val()
        },
        url: tbsRootURL + "Message/GetNewMessageCount",
        contentType: "application/json",
        dataType: "json",
        async: false,
        //data: JSON.stringify({
        //    objectPackageID: accessPanelItem.ID
        //    , isInFavorite: accessPanelItem.IsInFavorite
        //}),
        success: function (result) {
            if (result.Errors) {
                ErrorHandler(result);
            }
            else {
                HomePackagesCountLabel_add('GeneralUserTab', '1', result);
            }
        }
    });
}


//function HomeCurrentCartable_ChangeItemStatusToType1_ByTaskID(TaskItemID) {
//    debugger;
//    var CurrentTasksGrid = $('#tsPackages > div.tab-content > div.tab-pane.fade.in.active .k-grid') //$($('#tsPackages > ul.nav > li.active:not([tab-type="CartableTab"][tab-id="2"]) > a').attr('href') + ' .k-grid');;
//    if (CurrentTasksGrid != null && CurrentTasksGrid[0] != undefined) {
//        var GridItem = CurrentTasksGrid.getKendoGrid();
//        var SelectedItem = GridItem.dataSource.get(TaskItemID);
//        if (SelectedItem != null && SelectedItem.TaskStatusId == 6) {
//            SelectedItem.TaskStatusId = 1;
//            SelectedItem.TaskStatus.Name = 'در حال انجام';
//            SelectedItem.TaskStatus.ID = 1;
//            GridItem.refresh();
//            //HomePackagesCountLabel_cartable_add(-1);
//        }
//    }
//}

function HomeCartable_ChangeFavourite_ByTaskID(WfinstanceId, TaskID, isfav) {
    var CurrentTasksGrid = $('#tsPackages > div.tab-content > div.tab-pane.fade.in.active .k-grid');
    if (CurrentTasksGrid != null && CurrentTasksGrid[0] != undefined) {
        var GridItem = CurrentTasksGrid.getKendoGrid();

        var SelectedItem = GridItem.dataSource.get(TaskID);
        if (SelectedItem == undefined)
            SelectedItem = GridItem.dataSource.get(WfinstanceId);
        if (SelectedItem == undefined)
            return;
        SelectedItem.IsFavouriteWfid = isfav;
        GridItem.refresh();
    }
}



function HomeCartable_ChangeItemStatus_ByTaskID(TaskID, newStatus, gridID) {

    var CurrentTasksGrid = $('#tsPackages > div.tab-content > div.tab-pane.fade.in.active .k-grid');

    if (gridID != undefined || gridID != null)
        CurrentTasksGrid = $('#' + gridID);

    if (CurrentTasksGrid != null && CurrentTasksGrid[0] != undefined) {

        var GridItem = CurrentTasksGrid.getKendoGrid();
        var SelectedItem = GridItem.dataSource.get(TaskID);
        if (SelectedItem != null) {

            if (newStatus == 1 && SelectedItem.TaskStatusId == 6) {
                SelectedItem.TaskStatusId = 1;
                SelectedItem.TaskStatus.Name = 'در حال انجام';
                SelectedItem.TaskStatus.ID = 1;
                GridItem.refresh();
            }
            else if (newStatus == 6 && SelectedItem.TaskStatusId == 1) {
                SelectedItem.TaskStatusId = 6;
                SelectedItem.TaskStatus.Name = 'جدید';
                SelectedItem.TaskStatus.ID = 6;
                GridItem.refresh();

                switch (CurrentTasksGrid.attr('id')) {
                    case "grdPackageCartableTab1sTasks":
                        HomeCartable_RemoveItem_ByTaskID(TaskID, CurrentTasksGrid.attr('id'));

                        break;
                    case "grdPackageCartableTab2sTasks":
                        var currentNewTask = CurrentTasksGrid.data("kendoGrid").dataSource.view().filter(x => x.TaskStatusId == newStatus).length;
                        HomePackagesCountLabel_set('CartableTab', '2', currentNewTask);

                        break;

                }
            }
        }

    }
}

function HomeCartable_RemoveItem_ByTaskID(TaskItemID, gridID) {
    var CurrentTasksGrid = $('#tsPackages > div.tab-content > div.tab-pane.fade.in.active .k-grid');

    if (gridID != undefined || gridID != null)
        CurrentTasksGrid = $('#' + gridID);

    if (CurrentTasksGrid != null && CurrentTasksGrid[0] != undefined) {
        var GridItem = CurrentTasksGrid.getKendoGrid();
        var selectedItem = GridItem.dataSource.get(TaskItemID);
        if (selectedItem)
            CurrentTasksGrid.data("kendoGrid").dataSource.remove(selectedItem);

        switch (CurrentTasksGrid.attr('id')) {
            case "grdPackageCartableTab1sTasks":

                break;
            case "grdPackageCartableTab2sTasks":
                var currentNewTask = CurrentTasksGrid.data("kendoGrid").dataSource.view().filter(x => x.TaskStatusId == 6).length;
                HomePackagesCountLabel_set('CartableTab', '2', currentNewTask);

                break;

            default:
        }

    }
}

function HomeCartable_Refresh(gridID) {

    var CurrentTasksGrid = $('#tsPackages > div.tab-content > div.tab-pane.fade.in.active .k-grid');

    if (gridID != undefined || gridID != null)
        CurrentTasksGrid = $('#' + gridID);

    if (CurrentTasksGrid != null && CurrentTasksGrid[0] != undefined)
        CurrentTasksGrid.getKendoGrid().dataSource.read();
}

// #endregion TaskNewCount And Grids Updates

//#region TaskGroup Functions
function TaskGroup_Open(sender) {

    var lvAccessPanelItem = $(sender).parents('.k-listview').data('kendoListView');
    var accessPanelItem = lvAccessPanelItem.dataSource.getByUid($(sender).parent().attr('data-uid'));
    var KendoTabItem = $('#tsPackages').getKendoTabStrip();

    var $dummy = $("<div>");
    $dummy.load("Home/TaskGroup_LoadItem?id=" + accessPanelItem.ID, function (response, status, xhr) {
        if (status != "success") {
            ErrorHandler(response);
        }
        else {
            KendoTabItem.append({
                text: "<span class='TabTitle '>" + accessPanelItem.Name + "</span>",
                encoded: false,
                id: 'tsPackagesTaskGroup-' + accessPanelItem.ID,
                content: "<div>alireza mirmahdi</div>"
            });
        }
        $dummy.remove();
    });

    //var lvAccessPanelItem = $(sender).parents('.k-listview').data('kendoListView');
    //var accessPanelItem = lvAccessPanelItem.dataSource.getByUid($(sender).parent().attr('data-uid'));
    //var toggleFavoriteActionURL;
    //if (accessPanelItem.FormId > 0)
    //    toggleFavoriteActionURL = '@Url.Action("ToggleFormPackageUserfavorite", "Package")';
    //else if (accessPanelItem.WorkflowId > 0)
    //    toggleFavoriteActionURL = '@Url.Action("ToggleWorkflowPackageUserfavorite", "Package")';
    //else if (accessPanelItem.ReportId > 0)
    //    toggleFavoriteActionURL = '@Url.Action("ToggleReportPackageUserfavorite", "Package")';

    //$.ajax({
    //    type: "POST",
    //    url: toggleFavoriteActionURL,
    //    contentType: "application/json; charset=utf-8",
    //    dataType: "json",
    //    async: false,
    //    data: JSON.stringify({
    //        objectPackageID: accessPanelItem.ID
    //        , isInFavorite: accessPanelItem.IsInFavorite
    //    }),
    //    success: function (result) {
    //        if (result.Errors) {
    //            ErrorHandler(result);
    //        }
    //        else {
    //            $('.dvAccessPanels .k-listview').each(function (index, listItem) {
    //                $(listItem).data('kendoListView').dataSource.read();
    //            })
    //        }
    //    },
    //    error: function (XMLHttpRequest, textStatus, errorThrown) {
    //        ShowNotification('error', errorThrown);
    //    }
    //});

}
//#endregion TaskGroup Functions

//#region Tabs Other Functions

function TabFilterObject_ToJson(controllerName, filterModel) {
    var MyController = angular.element(document.querySelector("[data-ng-controller='" + controllerName + "']")).scope();
    return JSON.stringify(MyController[filterModel]());
}

function TabContent_AllDataSources_read(selectedTab) {
    HomePackagesCountLabel_cartable_ReadFromServer();
    var Contenct = $(selectedTab).attr('href');
    TabGrid_DataSources_read(Contenct);
    TabAccessPanel_DataSources_read(Contenct);
}
function TabGrid_DataSources_read(tabContentID) {
    var TabGrid = $(tabContentID + ' .dvWorkflowGrids .k-grid');
    if (TabGrid != undefined) {
        var GridItem = TabGrid.getKendoGrid();
        if (GridItem != undefined) {
            GridItem.dataSource.read();
        }
    }
}
function TabAccessPanel_DataSources_read(tabContentID) {
    var TabGrid = $(tabContentID + ' .dvWorkflowGrids .k-grid');
    if (TabGrid != undefined) {
        var GridItem = TabGrid.getKendoGrid();
        if (GridItem != undefined) {
            GridItem.dataSource.read();
        }
    }
}

//function TabFilterObject_GetObject(ClearPackageName) {
//    var MyController = angular.element(document.querySelector("[data-ng-controller='" + ClearPackageName + "_Content_Controller']")).scope();
//    return MyController["grdPackage"+ClearPackageName+"_Filter_Model"]();
//}


//function CartableTab_ReadAction_Data(TabID,ControllerName,FilterModel) {
//    return {
//        packageGroupID: TabID,
//        packageType: (TabID == -2) ? 0 : (TabID == -1) ? 1 : 2,
//        jsFilterParams: TabFilterObject_ToJson(ControllerName, FilterModel)
//    };
//}

//function GetClearPackageName(PackageID){
//    var ClearPackageName = "";
//    if (PackageID == -2)
//    {
//        ClearPackageName = "CartableTab";
//    }
//    else if (PackageID == -1)
//    {
//        ClearPackageName = "GroupCartableTab";
//    }
//    else if (PackageID > 0)
//    {
//        ClearPackageName = "PackageTab" + PackageID;
//    }
//    return ClearPackageName;
//}

function Tab_grid_setFilter(GridID) {
    var MyTab = $('#' + GridID).getKendoGrid();
    if (MyTab != undefined) {
        MyTab.dataSource.read();
    }

}

//#endregion Tabs Other Functions


//setup ajax error handling
$(function () {
    $.ajaxSetup({
        error: function (x, status, error) {
            switch (x.status) {
                case 403, 200:
                    window.location.reload();
                    //ShowNotification('error', "نشست شما منقضي شده است ، لطفا دوباره وارد شوید");
                    //setTimeout(function(){
                    //    window.location.reload()}
                    //    , 1000);
                    break;

                    break;
                default:
            }
        }
    });
});
//End of setup ajax error handling


function savedTaskCount(cartableNumber, amount) {
    switch (cartableNumber) {
        case 1:
            if (parseInt($('#savedTaskCartableCount').text()) + amount > -1)
                $('#savedTaskCartableCount').text(parseInt($('#savedTaskCartableCount').text()) + amount);
            break;
        case 2:
            if (parseInt($('#savedTaskGroupCartableCount').text()) + amount > -1)
                $('#savedTaskGroupCartableCount').text(parseInt($('#savedTaskCartableCount').text()) + amount);
            break;
    }
    if (parseInt($('#savedTaskCartableCount').text()) == 0)
        $('#savedTaskCartableCount').hide();
    else
        $('#savedTaskCartableCount').show();
    if (parseInt($('#savedTaskGroupCartableCount').text()) == 0)
        $('#savedTaskGroupCartableCount').hide();
    else
        $('#savedTaskGroupCartableCount').show();
}

function disableCartableSearch() {
    $('[href="#collapse_grdCartableTab1_filter"]').removeAttr("data-toggle");
    $('[href="#collapse_grdCartableTab1_filter"]').text("فرآیند های اخیر");
}
function enableCartableSearch() {
    $('[href="#collapse_grdCartableTab1_filter"]').attr("data-toggle", "collapse");
    $('[href="#collapse_grdCartableTab1_filter"]').text("جستجو");
    $('[href="#collapse_grdCartableTab1_filter"]').prepend($('<span class="glyphicon glyphicon-filter" ></span >'));
}

function onCartableSearchFiltering(e) {
    e.value = e.value
        .replaceAll('ي', 'ی')
        .replaceAll('ك', 'ک');
}

var chartArray = [];
function chartSettingsMapper(chartId, chartType, chartTitle, chartData, displayText, dataField, colorScheme = 'scheme02', resize = false) {

    var settings;
    let width = $('#' + chartId).width();
    let height = $('#' + chartId).height();

    if (!resize) {
        let chartItemIndex = chartArray.findIndex(s => s.chartId == chartId);
        if (chartItemIndex > -1) {
            chartArray.splice(chartItemIndex, 1);
        }
        chartArray.push({ chartId: chartId, chartType: chartType, chartTitle: chartTitle, chartData: chartData, displayText: displayText, dataField: dataField, colorScheme: colorScheme });
    }

    if (chartType == 'pie') {
        (width > height) ? width = height : height = width;
        settings = {
            source: chartData,
            title: chartTitle,
            titlePadding: { left: 0, top: 0, right: 0, bottom: 10 },
            description: '',
            enableAnimations: true,
            showLegend: false,
            legendPosition: { left: 520, top: 140, width: 100, height: 100 },
            showBorderLine: false,
            padding: { left: 5, top: 5, right: 5, bottom: 5 },
            colorScheme: colorScheme,
            seriesGroups: [
                {
                    type: chartType,
                    showLabels: true,
                    series:
                        [
                            {
                                dataField: dataField,
                                displayText: displayText,
                                //labelRadius: 190,
                                initialAngle: 15,
                                radius: (((width) / 2) + ((height) / 2)) / 3,
                                centerOffset: 0,
                                formatSettings: { sufix: '%', decimalPlaces: 1 }
                            }
                        ]
                }
            ]
        };
    }
    else if (chartType == 'column' || chartType == 'line') {
        settings = {
            source: chartData,
            title: chartTitle,
            titlePadding: { left: 90, top: 0, right: 0, bottom: 10 },
            description: '',
            enableAnimations: true,
            showLegend: false,
            padding: { left: 5, top: 5, right: 5, bottom: 5 },
            xAxis:
            {
                visible: true,
                dataField: 'Title',
                valuesOnTicks: false,
                //textRotationAngle: -90,
                labels:
                {
                    angle: -90,
                    verticalAlignment: 'botton',
                    rotationPoint: 'right'
                }

            },
            colorScheme: colorScheme,
            columnSeriesOverlap: false,
            valueAxis:
            {
                visible: true,
                title: { text: '' },
                labels: {
                    horizontalAlignment: 'right'
                }
            },
            seriesGroups:
                [
                    {
                        type: 'column',

                        series:
                            [
                                {
                                    dataField: 'count',
                                    displayText: 'count',
                                    toolTipFormatFunction: function (value, itemIndex, serie, group, xAxisValue, xAxis) {
                                        var formattedTooltip = "<div>" +
                                            //xAxisValue + "</br>" +
                                            value +
                                            "</div>";
                                        return formattedTooltip;
                                    },
                                }
                            ]
                    },
                ]
        };
    }

    return settings;
}

var rtime, timeout = false, delta = 50;
$(window).resize(function () {
    rtime = new Date();
    if (timeout === false) {
        timeout = true;
        setTimeout(resizeend, delta);
    }
});
function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
        chartArray.forEach(function (chartItem) {
            var chartSettings = chartSettingsMapper(chartItem.chartId, chartItem.chartType, chartItem.chartTitle, chartItem.chartData, chartItem.displayText, chartItem.dataField, chartItem.colorScheme, true);
            $('#' + chartItem.chartId).jqxChart(chartSettings);
            $("text:contains(www.jqwidgets.com)").css('display', 'none');
        });
    }
}