
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Right-click context menu functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

// Remember the last context menu item element for later use
var ContextMenuItemElement;

function AjaxGetObjectContextMenu(event, element, ObjectDataType, ObjectTable, ObjectRecordId, SelectedCellTable, SelectedCellColumnId) {

    // https://github.com/m-thalmann/contextmenujs
    // https://www.cssscript.com/multi-level-context-menu/

    event.preventDefault();

    // Check values
    //if (!ObjectDataType)
    //    return;
    //if (!ObjectTable)
    //    return;
    //if (!ObjectRecordId)
    //    return;

    var ContentType = GetSelectedContentType();
    var FilterJsonString = GetSelectedContentPaneFilterJsonString();
    var SettingsJsonString = GetSelectedContentPaneSettingsJsonString();
    var SelectedGridItems = GetSelectedIdsFromGridId();
    if (!SelectedGridItems)
        SelectedGridItems = {};

    var params = {
        "ContentType": ContentType,
        "DataType": ObjectDataType,
        "TableName": ObjectTable,
        "RecordId": ObjectRecordId,
        "SelectedCellTable": SelectedCellTable,
        "SelectedCellColumnId": SelectedCellColumnId,
        "FilterJsonString": FilterJsonString,
        "SettingsJsonString": SettingsJsonString,
        "SelectedDbTableCsvIds": SelectedGridItems.SelectedDbTableCsvIds,
        "SelectedDbRecordCsvIds": SelectedGridItems.SelectedDbRecordCsvIds,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetObjectContextMenu",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                //var menuitemsTest = [
                //    {
                //        "text": "Item 1",
                //        "icon": "&#9819;",
                //        "sub": [
                //            {
                //                "text": "Item 1.1",
                //                "enabled": false
                //            }
                //        ]
                //    },
                //    {
                //        "text": "Item 2",
                //        "events": {                              // Adds eventlisteners to the item (you can use any event there is)
                //            "click": function (e) {
                //                alert("Item 2 clicked");
                //            }
                //        }
                //    }
                //];
                //var menu = new ContextMenu(menuitems);

                // Remember the last context menu item element for later use
                ContextMenuItemElement = element;

                var menuitems = JSON.parse(response.ContextMenuItems);
                var menu = new ContextMenu(menuitems);
                menu.display(event);
            }
            else if (response.ErrorResults) {
                ToastError("Menu command", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxGetObjectContextMenu", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}



function AjaxGridColumnHeaderContextMenu(event, ObjectDataType, ObjectTable, DbColumn, ColumnIndex, SelectedDataType, SelectedTableId, SelectedRecordId) {

    // https://github.com/m-thalmann/contextmenujs
    // https://www.cssscript.com/multi-level-context-menu/

    event.preventDefault();

    // Check values
    if (!ObjectDataType)
        return;
    if (!ObjectTable)
        return;

    var params = {
        "ContentType": ObjectDataType,
        "TableName": ObjectTable,
        "DbColumn": DbColumn,
        "ColumnIndex": ColumnIndex,
        "SelectedDataType": SelectedDataType,
        "SelectedTableId": SelectedTableId,
        "SelectedRecordId": SelectedRecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetColumnHeaderContextMenu",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                //var menuitemsTest = [
                //    {
                //        "text": "Item 1",
                //        "icon": "&#9819;",
                //        "sub": [
                //            {
                //                "text": "Item 1.1",
                //                "enabled": false
                //            }
                //        ]
                //    },
                //    {
                //        "text": "Item 2",
                //        "events": {                              // Adds eventlisteners to the item (you can use any event there is)
                //            "click": function (e) {
                //                alert("Item 2 clicked");
                //            }
                //        }
                //    }
                //];
                //var menu = new ContextMenu(menuitems);

                var menuitems = JSON.parse(response.ContextMenuItems);
                var menu = new ContextMenu(menuitems);
                menu.display(event);
            }
            else if (response.ErrorResults) {
                ToastError("Menu command", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("GetColumnHeaderContextMenu", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}




var bIgnoreNextContextMenuEvent = false;

/**
 * Called when grid is right-clicked
 * @param {any} GridElement
 * @param {any} event
 */
function OnGridContextMenuEvent(GridElement, event) {

    if (!GridElement)
        return;
    if (!event)
        return;
    if (!event.target)
        return;

    // Already handled elsewhere
    // Occurs when clicking on specific grid elements, like Gantt bars
    if (bIgnoreNextContextMenuEvent) {
        bIgnoreNextContextMenuEvent = false;
        return;
    }

    // Do not open context menu while actively editing a grid cell
    // This popup is too disruptive to the editing process
    if (IsGridInEditMode())
        return;

    event.preventDefault();

    // https://www.igniteui.com/help/api/2021.2/ui.iggrid

    var IgGrid = GridElement.igGrid();
    var GridId = GridElement.attr("id");
    var ClickedCellHtmlElement = event.target;
    var ClickedCellElement = $(ClickedCellHtmlElement);
    var ClickedParentHtmlElement = ClickedCellHtmlElement.parentElement;
    var RowObject = GetRowObjectFromElement(ClickedCellElement);
    var ColumnObject = GetColumnObjectFromElement(ClickedCellElement);
    var RowIndex = -1;
    var ColumnIndex = -1;
    var ColumnKey = "";
    if (RowObject)
        RowIndex = RowObject[0].rowIndex;
    if (ColumnObject) {
        ColumnIndex = ColumnObject[0].cellIndex;
        ColumnKey = ColumnObject.attr("id");
        if (ColumnKey)
            ColumnKey = ColumnKey.replace(GridId+"_", "");
    }

    // Find the actual SPAN child inside this TD
    // This SPAN will contain attributes to identify the database record
    var sGridDbTable = $(IgGrid).attr('data-dbtable');
    var sSelectedCellDbTable = $(ClickedCellElement).attr('data-dbtable');
    var sSelectedCellDbColumn = $(ClickedCellElement).attr('data-dbcolumn');

    var RowKey = GetRowKeyFromElement(ClickedParentHtmlElement);
    if (!RowKey)
        return;

    var IgClickedRow = GridElement.igGrid("rowById", RowKey);
    var RecordTableName = GridElement.igGrid("getCellValue", RowKey, "COL_DBTABLE");

    // False information from Infragistics support
    //let cell = evt.target;
    //let rowID = evt.target.parentElement.attributes["data-id"].value;
    //let cellIndex = cell.cellIndex
    //let columnKey = $("#gridProducts").igGrid("option", "columns")[cellIndex].key;

    var ObjectDataType = "stdata.BaseDataSet";
    var ObjectTable = RecordTableName;
    var ObjectRecordId = RowKey;
    AjaxGetObjectContextMenu(event, ClickedCellElement, ObjectDataType, ObjectTable, ObjectRecordId, sSelectedCellDbTable, sSelectedCellDbColumn);
}


function OnGridHeaderContextMenuEvent(GridElement, HeaderElement, event) {

    if (!GridElement)
        return;
    if (!HeaderElement)
        return;
    if (!event)
        return;
    if (!event.target)
        return;

    event.preventDefault();

    var GridId = GridElement.attr('id');
    //GridId = GridId.replace("_headers", "");


    var ClickedCellHtmlElement = event.target;
    var ClickedCellElement = $(ClickedCellHtmlElement);
    var ColumnObject = GetColumnObjectFromElement(ClickedCellElement);
    var ColumnIndex = -1;
    var ColumnKey = "";
    if (ColumnObject) {
        ColumnIndex = ColumnObject[0].cellIndex;
        ColumnKey = ColumnObject.attr("id");
        if (ColumnKey)
            ColumnKey = ColumnKey.replace(GridId + "_", "");
    }

    var ContentType = $(GridElement).attr('data-gridcontenttype');
    var sGridDbTable = $(GridElement).attr('data-dbtable');

    // Single item selected
    // Delete the selected record in the active grid
    // First get the selected recordset
    var SelectedDataType = $('input[id="HiddenSelectedDataTypeId"]').val();
    var SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
    var SelectedRecordId = $('input[id="HiddenSelectedRecordId"]').val();

    // No hidden values? Set them from the current selection
    if (!SelectedTableId || !SelectedRecordId) {

        // Try getting values from selection
        SetHiddenRecordValuesFromSelection();

        // Try again
        SelectedDataType = $('input[id="HiddenSelectedDataTypeId"]').val();
        SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
        SelectedRecordId = $('input[id="HiddenSelectedRecordId"]').val();
    }

    // Search deeper for recordsetvaluelist attribues
    // These occur in timesheets where multiple values are aggregated into single cells
    // See stdata.RecordSetListValue.GetJsonValues()
    var GridId = $('input[id="HiddenSelectedGridId"]').val();
    if (GridId) {
        var GridObj = $("#" + GridId);
        if (GridObj && GridObj.length) {
            var RecordsetValueList = GetRecordsetListValueFromSelectedCells(GridObj);
            if (RecordsetValueList) {
                if (RecordsetValueList.Table && RecordsetValueList.ID) {
                    SelectedTableId = RecordsetValueList.Table;
                    SelectedRecordId = RecordsetValueList.ID;
                }
            }
        }
    }


    // Open context menu
    AjaxGridColumnHeaderContextMenu(event, ContentType, sGridDbTable/*ObjectTable*/, ColumnKey, ColumnIndex, SelectedDataType, SelectedTableId, SelectedRecordId);
}




/**
 * Get a single menu command from the server: DELETE
 * Execute the command after receiving it from the server
 * Example: Are you sure you want to delete the project?
 * @param {any} ObjectDataType
 * @param {any} ObjectTable
 * @param {any} ObjectRecordId
 */
function AjaxExecuteDeleteMenuCmd(ObjectDataType, ObjectTable, ObjectRecordId, SelectedCellTable, SelectedCellColumnId) {

    // Check values
    //if (!ObjectDataType)
    //    return;
    //if (!ObjectTable)
    //    return;
    //if (!ObjectRecordId)
    //    return;

    var ContentType = GetSelectedContentType();

    var params = {
        "ContentType": ContentType,
        "DataType": ObjectDataType,
        "TableName": ObjectTable,
        "RecordId": ObjectRecordId,
        "SelectedCellTable": SelectedCellTable,
        "SelectedCellColumnId": SelectedCellColumnId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetObjectContextMenu",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                var menuitems = JSON.parse(response.ContextMenuItems);
                if (menuitems && menuitems.length > 0) {

                    // Find the Delete menu
                    var menucmd = FindDeleteCmd(menuitems);
                    if (menucmd) {

                        // Execute the Delete menu
                        OnMenuItemClick(menucmd);
                        return;
                    }
                }

                // No stdata.MenuCmdItem.CMD_DELETE
                ToastError("Delete", "This record doesn't have a delete command");
            }
            else if (response.ErrorResults) {
                ToastError("Menu command", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxExecuteDeleteMenuCmd", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


function FindDeleteCmd(menuitems) {

    if (!menuitems)
        return null;
    if (!menuitems.length)
        return null;

    // Find stdata.MenuCmdItem.CMD_DELETE
    for (var i = 0; i < menuitems.length; i++) {

        var menucmd = menuitems[i];

        if (menucmd.text === menucmd.DeleteCmdName)
            return menucmd.MenuCmd;

        // Try subitems
        if (menucmd.sub) {
            var found = FindDeleteCmd(menucmd.sub);
            if (found)
                return found;
        }
    }

    // Nope, can't find it
    return null;
}




/**
 * Click callback
 * See; li.addEventListener() in contextmenu.js
 * @param {any} menucmd
 */
function OnMenuItemClick(menucmd) {

    // See; contextmenu.js
    if (!menucmd)
        return;

    // Is there a prompt to be answered?
    // Example: "Are you sure you wish to delete the project?"
    // If so, satisfy the prompt first, which will call the callback if "OK" is clicked
    if (menucmd.Prompt)
        Prompt(menucmd.Prompt, ExecuteMenuCmd, menucmd);
    else
        ExecuteMenuCmd(menucmd.Prompt, menucmd);
}



/**
 * Execute a menu command
 * Prompts have already been satisfied, results sent as a parameter
 * See JSMenuCmdItem in HomeController.cs
 * @param {any} prompt
 * @param {any} menucmd
 */
function ExecuteMenuCmd(prompt, menucmd) {

    // See JSMenuCmdItem in HomeController.cs
    if (!menucmd)
        return;

    // Open a new tab
    if (menucmd.NewWindowInfo) {
        ExecuteMenuCmdNewWindow(menucmd);
        return;
    }

    // Call a function to perform the action
    if (menucmd.PerformMenuAction) {
        ExecuteMenuCmdPerformMenuAction(menucmd);
        return;
    }

    // Perform action on a recordset
    if (menucmd.TargetRecordset) {

        // Properties menu
        if (menucmd.text === menucmd.PropertiesCmdName /*"Properties"*/) {

            // Fill properties with partial view from server
            AjaxRefreshPropertyGridView($("#"+PropertyGridPartialViewDivId), "OBJECT", menucmd.TargetRecordset.datatype, menucmd.TargetRecordset.tablename, menucmd.TargetRecordset.recordid, ""/*SelectedCellTable*/, ""/*SelectedCellColumnId*/, ""/*PropertyValuesJsonString*/);
            AddPropertiesGridToContentArray(menucmd.TargetRecordset.datatype, menucmd.TargetRecordset.tablename, menucmd.TargetRecordset.recordid, ""/*SelectedCellTable*/, ""/*SelectedCellColumnId*/);

            // Show the panel
            ShowPropertiesPane();
            return;
        }
        else if (menucmd.text === menucmd.ProjectAssistantCmdName /*"Project Assistant"*/) {
            ShowProjectAssistant();
            return;
        }

        ExecuteMenuCmdRecordset(menucmd);
        return;
    }

    // Open a dialog to create a new record (Example: stdata.ProjectTaskSet)
    if (menucmd.CreateNewObjectType) {
        AjaxCreateNewContentRecordFromObjectType(menucmd.CreateNewObjectType);
        return;
    }

    // Open a new report window
    if (menucmd.OpenReportByPathname) {
        ShowReportView(menucmd.OpenReportByPathname);
        return;
    }

    // Special report menu handler
    if (menucmd.TargetReportPath) {
        ExecuteMenuCmdReport(menucmd);
        return;
    }

    // Nothing else to do but prompt the user?
    // This menu command has already done that, so its job is complete
    if (menucmd.Prompt)
        return;

    // Unhandled menu
    // Not sure what to do
    var UnhandedMsg = menucmd.text;
    if (menucmd.PerformMenuAction)
        UnhandedMsg += ", Perform: " + menucmd.PerformMenuAction;
    ToastError("Unhandled ExecuteMenuCmd", UnhandedMsg);
}



function ExecuteMenuCmdRecordset(menucmd) {

    // See JSMenuCmdItem.JSRecordset in HomeController.cs
    if (!menucmd)
        return;
    if (!menucmd.TargetRecordset)
        return;

    // Call Ajax to execute command on server
    AjaxExecuteMenuCmd(menucmd);
}




/**
 * Special report menu handler
 * */
function ExecuteMenuCmdReport(menucmd) {

    // See JSMenuCmdItem.JSRecordset in HomeController.cs
    if (!menucmd)
        return;
    if (!menucmd.TargetReportPath)
        return;

    // "Click" this object so hidden values are saved and used for ajax calls
    // The Properties grid will use the hidden selected object values set up by this call
    OnClickReportObject(ContextMenuItemElement);

    // Properties menu
    if (menucmd.text === menucmd.PropertiesCmdName /*"Properties"*/) {
        ShowPropertiesPane();
        return;
    }
    else if (menucmd.text === menucmd.DeleteCmdName /*"Delete"*/) {
        AjaxExecuteMenuCmd(menucmd);
        return;
    }

    // Call Ajax to execute command on server
    AjaxExecuteMenuCmd(menucmd);
}



/**
 * Open a new window or tab
 * @param {any} menucmd
 */
function ExecuteMenuCmdNewWindow(menucmd) {

    // See JSMenuCmdItem.JSNewWindowInfo in HomeController.cs
    if (!menucmd)
        return;
    if (!menucmd.NewWindowInfo)
        return;

    if (menucmd.NewWindowInfo.sContentType) {

        // Get the filter choices for this content
        var JsonFilterString = "";
        if (menucmd.NewWindowInfo.DisplayOptionsFilterDictionary)
            JsonFilterString = JSON.stringify(menucmd.NewWindowInfo.DisplayOptionsFilterDictionary);

        // Open a new tab for this content
        ShowStContent(menucmd.NewWindowInfo.sContentType, ""/*ValueString*/, menucmd.NewWindowInfo.sTitle, JsonFilterString);

        // Delay until new panel is open
        setTimeout(function () {
            SaveContentTypeFilterJsonStringToCookie(menucmd.NewWindowInfo.sContentType, JsonFilterString);
            RefreshSelectedContent();
        }, 1000);
    }
}


/**
 * Call a function to perform the menu action
 * @param {any} menucmd
 */
function ExecuteMenuCmdPerformMenuAction(menucmd) {

    // See JSMenuCmdItem in HomeController.cs
    if (!menucmd)
        return;

    // See: Form1_Events.cs in Windows app for methods
    if (!menucmd.PerformMenuAction)
        return;

    var bContentShown = false;

    // Special case first
    if (menucmd.PerformMenuActionParameters) {
        bContentShown = ShowContentByMethodName(menucmd.PerformMenuAction, menucmd.PerformMenuActionParameters);
        if (bContentShown)
            return;
    }

    // Normal case here
    // Try sending the entire menu command to the method
    bContentShown = ShowContentByMethodName(menucmd.PerformMenuAction, menucmd);
    if (bContentShown)
        return;

    // Default:
    // Tell user that this contect cannot be shown
    // Maybe they will complain to tech support so we can fix it
    // This happens when we forgot to add a specific check for the method name
    ToastError("PerformMenuAction failed", menucmd.PerformMenuAction);
}









/**
 * Call Ajax to execute a menu command
 * @param {any} menucmd
 */
function AjaxExecuteMenuCmd(menucmd) {

    if (!menucmd)
        return;

    var SelectedGridItems = GetSelectedIdsFromGridId();
    if (!SelectedGridItems)
        SelectedGridItems = {};

    // Ajax:
    //    public JsonResult ExecuteMenuCmd(JSMenuCmdItem MenuCmd)
    var params = {
        "JSMenuCmd": menucmd,
        "SelectedDbTableCsvIds": SelectedGridItems.SelectedDbTableCsvIds,
        "SelectedDbRecordCsvIds": SelectedGridItems.SelectedDbRecordCsvIds,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxExecuteMenuCmd",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // Execute this new command
                if (response.PostProcessMenuCmdItem) {

                    if (response.PostProcessMenuCmdItem.Prompt) {
                        Prompt(response.PostProcessMenuCmdItem.Prompt, ExecuteMenuCmd, response.PostProcessMenuCmdItem);
                        return;
                    }

                    // Execute the post-process command
                    var emptyprompt = {};
                    ExecuteMenuCmd(emptyprompt, response.PostProcessMenuCmdItem);
                }

                // Pop up a message after executing this menu command
                // Usually an error resulting from executing command
                if (response.PromptJsonString) {
                    var ResponsePrompt = JSON.parse(response.PromptJsonString);
                    Prompt(ResponsePrompt, ExecuteMenuCmd, null/*proceedobject*/);
                }

                if (response.ExportDataBase64String && response.ExportDataBase64String.length > 0) {
                    var blob = Base64StringToBlob(response.ExportDataBase64String);
                    download(blob, response.ExportFilename, response.ExportFileExt);
                }


                // Refresh the grid contents to show the new property value
                SetSelectRecordIdAfterRebuild("", response.NewRecordId);
                RefreshSelectedContent();

                //ToastMessage("Menu command", "Success");
            }
            else {
                ToastError("Menu command", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxExecuteMenuCmd", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}




/**
 * Called when tree is right-clicked
 * @param {any} TreeElement
 * @param {any} event
 */
function OnTreeContextMenuEvent(TreeElement, event) {

    if (!TreeElement)
        return;
    if (!event)
        return;
    if (!event.target)
        return;

    // No browser right-click menu
    event.preventDefault();

    var ClickedHtmlElement = event.target;
    var Node = $(TreeElement).igTree('nodeFromElement', $(event.target).closest('li[data-role=node]'));
    if (!Node)
        return;
    if (!Node.data)
        return;
    if (!Node.data.Text)
        return;
    if (!Node.data.Value)
        return;

    var ParentNode = GetParentTreeNode(TreeElement, Node);
    var TopLevelNode = GetTopLevelTreeNode(TreeElement, Node);
    if (!ParentNode)
        return;
    if (!TopLevelNode)
        return;
    if (!TopLevelNode.data.Value)
        return;

    var NodeText = Node.data.Text;
    var NodeValue = Node.data.Value;

    // Open context menu for the object
    var ObjectDataType = "stdata.BaseDataSet";
    var ObjectTable = TopLevelNode.data.Value; // "Projects"
    var ObjectRecordId = NodeValue; // "GUID"
    AjaxGetObjectContextMenu(event, ClickedHtmlElement, ObjectDataType, ObjectTable, ObjectRecordId);
}




/**
 * Grab all the tabs and buttons in this div
 * Turn them into a context menu
 * @param {any} DivElement
 * @param {any} ListElement
 */
function HarvestMenuItemsFromTabsInDiv(DivElement, ListElement) {

    if (!DivElement)
        return null;
    if (!ListElement)
        return null;

//    var menuitemsTest = [
//        {
//            "text": "Item 1",
//            "icon": "&#9819;",
//            "sub": [
//                {
//                    "text": "Item 1.1",
//                    "enabled": false
//                }
//            ]
//        },
//        {
//            "text": "Item 2",
//            "events": {                              // Adds eventlisteners to the item (you can use any event there is)
//                "click": function (e) {
//                    alert("Item 2 clicked");
//                }
//            }
//        }
//    ];
//    return menuitemsTest;

    var menuitems = [];

    // Begin with tab names
    listItems = $(ListElement).find("li").each(function () {
        var listitem = $(this);
        var listitemhtml = listitem.html();

        // Each list item is an <a> anchor with href and text
        var listitemelement = $($.parseHTML(listitemhtml));
        if (!listitemelement)
            return true;

        // Get text and href from anchor element
        // The href is a child div with buttons inside
        var TabText = listitemelement.text();
        var TabDivId = listitemelement.attr('href');

        // New menu item for the main ribbon tabs
        // Each tab will contain button subitems
        var menuitem = {};
        menuitem.text = TabText;

        // Buttons inside tab div
        var TabDiv = $(TabDivId);
        if (TabDiv) {
            var submenuitems = [];

            // Find all the buttons inside the tab div
            // These serve as subitems in the main menu
            $(TabDiv).find("button").each(function () {
                var BtnElement = $(this);

                // Button values
                var BtnText = BtnElement.text();
                var BtnClickHandler = BtnElement.attr("onclick");
                var data_stcontent = BtnElement.attr("data-stcontent");
                var data_title = BtnElement.attr("data-title");
                var data_url = BtnElement.attr("data-url");

                var btnmenuitem = {};
                btnmenuitem.text = BtnText;
                btnmenuitem.clickhandler = BtnClickHandler;
                btnmenuitem.stcontent = data_stcontent;
                btnmenuitem.title = data_title;
                btnmenuitem.launchurl = data_url;
                submenuitems.add(btnmenuitem);
            });

            menuitem.sub = submenuitems;
        }

        // Add to list menu
        menuitems.add(menuitem);
    });

    return menuitems;
}



/**
 * Get list of all record items
 * Display them in a context menu
 *     Examples:
 *       All projects
 *       All inventory items
 * 
 * @param {any} ContentType
 * @param {any} onclickfunction
 */
function AjaxGetRecordItemsContentMenu(event, element, ContentType, TableName, RecordId, PerformMenuAction) {

    var params = {
        "ContentType": ContentType,
        "TableName": TableName,
        "RecordId": RecordId,
        "PerformMenuAction": PerformMenuAction
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetRecordItemsContentMenu",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                // Remember the last context menu item element for later use
                ContextMenuItemElement = element;
                var menuitems = JSON.parse(response.ContextMenuItems);
                var menu = new ContextMenu(menuitems);
                menu.display(event);
            }
            else {
                if (response.ErrorResults)
                    ToastError("AjaxGetRecordItemsContentMenu", response.ErrorResults);
                else if (response.ToastMessage)
                    ToastError("Menu items", response.ToastMessage);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + BarcodeText;
            ToastError("AjaxGetRecordItemsContentMenu", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




