
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Reports menu functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

/**
 * Set up all the button in a div (called from an <img> within that div)
 * @param {any} element
 */
function SetupReportFilesInDivFromElement(element) {

    if (!element)
        return;

    // Convert a raw html element to jQuery
    element = $(element);
    if (!element)
        return;

    // "ReportFilesDiv"
    var ElementId = element.attr('id');
    var ParentDiv = $(element).parent();

    // Remove the element that started this process
    // Do not come back here
    element.remove();

    SetupReportFilesInParentDiv(ParentDiv);
}

function SetupReportFilesInParentDiv(ParentDiv) {

    if (!ParentDiv)
        return;
    var ParentDivId = ParentDiv.attr('id');

    // Set up images and click event handlers
    AjaxSetupReportFoldersInDiv(ParentDiv);
}

function SetupReportFilesInReportFilesDiv() {

    var ReportFilesDiv = $("#ReportFilesDiv");
    if (!ReportFilesDiv)
        return;

    // Still got an image loader?
    // If so, emumerate reports
    // But if the image loader has been removed then the enumeration has already been done
    var LoaderImg = ReportFilesDiv.find(`[data-loader-img='true']`);
    if (LoaderImg && LoaderImg.get(0)) {

        // The  image loader still exists
        // It will be delete by this function so we don't come back here
        SetupReportFilesInDivFromElement(LoaderImg.get(0));
    }
    else {
        // No loader image. This happens when the image has been replaced by reports (coming here for the second time)
        // Clear the div and refill with reports
        ReportFilesDiv.html("");
        SetupReportFilesInParentDiv(ReportFilesDiv);
    }
}



/**
 * Call Ajax to get all report folders
 * Create a new button for 
 *  report folder
 * See: RibbonView.cshtml
 * Parent: <div id="ReportFilesDiv">
 * @param {any} ParentDiv
 */
function AjaxSetupReportFoldersInDiv(ParentDiv) {

    if (!ParentDiv)
        return;

    var params = {
    };

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

                    // Build JavaScript array from results
                    // Use this to build buttons for each report folder
                    var ReportFilesArray = $.parseJSON(response.ReportFiles); //convert to javascript array
                    if (ReportFilesArray && ReportFilesArray.length) {

                        $.each(ReportFilesArray, function (index) {
                            AddReportFileButton(ParentDiv, ReportFilesArray[index]);
                        });
                        //ToastError("AjaxSetupReportFoldersInDiv", ReportFilesArray.length);

                        // Add images and click event callbacks to each button
                        SetupElementImagesInDivByParent(ParentDiv);
                    }
                }
            }
            else {
                ToastError("Set up report files", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxSetupReportFoldersInDiv", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}




/**
 * Create a new button for a report folder
 * See: RibbonView.cshtml
 * Parent: <div id="ReportFilesDiv">
 * @param {any} ParentDiv
 * @param {any} name
 */
function AddReportFileButton(ParentDiv, menucmd/*JSContextMenuItem*/) {

    if (!ParentDiv)
        return;
    if (!menucmd)
        return;
    if (!menucmd.text)
        return;

    // Set up values
    var NewButtonId = GetUniqueId("ReportButton-");
    var ReportButtonJsonItems = "";
    if (menucmd.sub)
        ReportButtonJsonItems = JSON.stringify(menucmd.sub);
    ReportButtonJsonItems = ReportButtonJsonItems.replaceAll("\"", "~-~");

    // Create the button
    var $input = $('<button id="' + NewButtonId + '" class="ribbonbuttonsmall"  data-reportjsonitems="' + ReportButtonJsonItems + '" onclick="OnReportButtonClick()" >' + menucmd.icon + "&nbsp;" + menucmd.text + '</button>');
    $input.appendTo(ParentDiv);
}


/**
 * onclick event
 * A report button was clicked
 * Open a menu with a list of reports for this folder
 * Example:
 *          Time Logs
 *              List, but employee
 *              List, but project, employee
 * @param {any} event
 */
function OnReportButtonClick() {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    event.preventDefault();

// Testing..............................
    //var menuitems = [
    //    {
    //        "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);
    //menu.display(event);
    //return;



    try {
        var element = event.currentTarget;
        var ReportButtonElement = $(element);
        var ReportButtonElementId = ReportButtonElement.attr('id');

        // List of reports stored inside this button as a JSON string
        var ReportButtonJsonItems = ReportButtonElement.attr('data-reportjsonitems');
        if (ReportButtonJsonItems) {

            // Convert JSON string to array of objects
            // Each object is a report file
            // Display a menu of report files to choose from
            // Example:
            //          Time Logs
            //              List, but employee
            //              List, but project, employee
            ReportButtonJsonItems = ReportButtonJsonItems.replaceAll("~-~", "\"");
            var ReportButtonArray = $.parseJSON(ReportButtonJsonItems); //convert to javascript array
            if (ReportButtonArray && ReportButtonArray.length > 0) {

                // Open the reports menu
                OpenReportButtonMenu(event, ReportButtonArray);
                return;
            }
        }
    }
    catch (err) {
        // Oops
    }
    finally {
    }

    ToastError("Reports", "No reports to display for this item!");

    //alert("OnReportButtonClick: " + event.clientX + ", " + event.clientY);
}



/**
 * Open a menu with reports to choose from
 * @param {any} event
 * @param {any} ReportButtonArray
 */
function OpenReportButtonMenu(event, menuitems) {

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

    //var menuitems = JSON.parse(response.ContextMenuItems);
    //var menu = new ContextMenu(menuitems);
    //menu.display(event);

// Testing................
    //menuitems = [
    //    {
    //        "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);
    menu.display(event);

    //ToastError("OpenReportButtonMenu", ReportButtonArray.length);
}


function OnOpenReport() {

    // TODO: P8 Upload reports from client machine to server to run
    // This allows users to run a local report on the server
    $('#fileupload').attr("accept", ".rpx");
    $('#fileupload').on('change', function () { $('#fileupload').off('change'); /*ShowReportView($('#fileupload').val());*/ ToastError("Open Report", "Uploading reports from your machine to the web server is not yet available."); });
    $('#fileupload').trigger('click');
}


/**
 * Each report object has a GUID to identify it for editing
 * @param {any} element
 */
function GetReportGuidFromRptObject(element) {

    if (!element)
        return null;
    var ReportObject = $(element);
    if (!ReportObject)
        return null;

    // Each report object has a guid for editing
    var sGuid = ReportObject.attr("data-guid");
    if (!sGuid)
        return null;

    return sGuid;
}

/**
 * Each report object has the pathname of the report it is in
 * Load this report and find the GUID of the object
 * @param {any} element
 */
function GetReportPathnameFromRptObject(element) {

    if (!element)
        return null;
    var ReportObject = $(element);
    if (!ReportObject)
        return null;

    // Each report object has the pathname of the report it is in
    // Load this report and find the GUID of the object
    var sPathname = ReportObject.attr("data-pathname");
    if (!sPathname)
        return null;

    return sPathname;
}


function FindReportElementObjectFromRecordId(sRecordId) {

    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv)
        return null;
    var ElementObj = ContentDiv.find("[data-guid='" + sRecordId + "']");
    if (!ElementObj)
        return null;
    return $(ElementObj);
}

function GetDesignTabReportDivBoundingClientRect() {

    // Starts with tabs at top, then actual report under the tabs
    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv)
        return null;

    var DesignTabReportDiv = ContentDiv.find("#DesignTabReportDiv");
    if (!DesignTabReportDiv || DesignTabReportDiv.length == 0)
        return null;

    var BoundingClientRect = DesignTabReportDiv[0].getBoundingClientRect();
    return BoundingClientRect;
}


function OnClickReportObject(element) {

    if (!element)
        return;

    // Each report object has a guid for editing
    var sGuid = GetReportGuidFromRptObject(element);
    if (!sGuid)
        return;

    var sPathname = GetReportPathnameFromRptObject(element);
    if (!sPathname)
        return;

    var bSelectMultiple = false;
    if (event)
        bSelectMultiple = (event.shiftKey || event.ctrlKey);
    var ParentObject = $(element).parent();
    var SelectedObjects = ParentObject.find('.clickselected');
    if (!bSelectMultiple)
        SelectedObjects.removeClass('clickselected');

    // Works, but doesn't remove class from older clicked items
    $(element).addClass('clickselected');

    // Set the selected record into hidden values
    // The server will read these values for update and display
    $('input[id="HiddenSelectedDataTypeId"]').val("rptdata.RptObject");
    $('input[id="HiddenSelectedTableId"]').val(sPathname);
    $('input[id="HiddenSelectedRecordId"]').val(sGuid);
    $('input[id="HiddenSelectedColumnId"]').val("NOCOLUMNID");
    $('input[id="HiddenSelectedGridId"]').val("");
    $('input[id="HiddenSelectedCellTableId"]').val("");
    $('input[id="HiddenSelectedCellColumnId"]').val("");

    // Resize objects with drag handles
    BuildDragHandlesForSelectedObjects();

    // Don't take over the small mobile phone screen 
    if (!bSmallSizeApp) {
        // New selected record!
        // Trigger Ajax function to update properties
        RefreshPropertyGridViewFromHiddenSelection($("#" + PropertyGridPartialViewDivId));
    }
}

function OnDoubleClickReportObject(element) {

    // Each report object has a guid for editing
    var sGuid = GetReportGuidFromRptObject(element);
    if (!sGuid)
        return;

    var sPathname = GetReportPathnameFromRptObject(element);
    if (!sPathname)
        return;

    var ObjectDataType = "rptdata.RptObject";
    var ObjectTable = sPathname;
    var ObjectRecordId = sGuid;

    // Fill properties with partial view from server
    AjaxRefreshPropertyGridView($("#" + PropertyGridPartialViewDivId), "RPTOBJECT", ObjectDataType, ObjectTable, ObjectRecordId, ""/*sSelectedCellDbTable*/, ""/*sSelectedCellDbColumn*/, ""/*PropertyValuesJsonString*/);
    AddPropertiesGridToContentArray(ObjectDataType, ObjectTable, ObjectRecordId, ""/*sSelectedCellDbTable*/, ""/*sSelectedCellDbColumn*/);

    // Show the panel
    ShowPropertiesPane();
}

function OnRightClickReportObject(element) {

    // Each report object has a guid for editing
    var sGuid = GetReportGuidFromRptObject(element);
    if (!sGuid)
        return;

    var sPathname = GetReportPathnameFromRptObject(element);
    if (!sPathname)
        return;

    var ObjectDataType = "rptdata.RptObject";
    var ObjectTable = sPathname;
    var ObjectRecordId = sGuid;

    // Open content menu
    AjaxGetObjectContextMenu(event, element, ObjectDataType, ObjectTable, ObjectRecordId);
}



/**
 * Resize objects with drag handles
 * 0=No drag handles
 * 1=Top-left
 * 2=Top-middle
 * 4=Top-right
 * 8=Right-middle
 * 16=Bottom-right
 * 32=Bottom-middle
 * 64=Bottom-left
 * 128=Left-middle
 */
function BuildDragHandlesForSelectedObjects() {

    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv)
        return;

    // Remove all drag handle objects
    var DragHandleObjects = ContentDiv.find('.draghandle');
    DragHandleObjects.remove();

    // Any selected objects?
    var SelectedObjects = ContentDiv.find('.clickselected');
    if (!SelectedObjects || SelectedObjects == null || SelectedObjects.length == 0)
        return;

    // Build drag handles for each selected object
    for (i = 0; i < SelectedObjects.length; ++i) {

        // This object is selected
        var SelectedObject = $(SelectedObjects[i]);
        if (!SelectedObject || SelectedObject == null || SelectedObject.length == 0)
            continue;

        // Which drag handles does this object allow?
        var DragHandleBits = SelectedObject.attr('data-draghandles')
        if (!DragHandleBits)
            continue;

        // Create a handle for each bit
        for (nBit = 1; nBit < 1025; nBit = nBit * 2) {
            if (DragHandleBits & nBit) {
                BuildDragHandle(SelectedObject, nBit);
            }
        }
    }
}

function BuildDragHandle(SelectedObject, nDragHandleBit) {

    var SelectedObjectId = SelectedObject.attr('data-guid');
    var SelectedObjectPathname = SelectedObject.attr('data-pathname');
    var DragHandleId = SelectedObjectId + "-" + nDragHandleBit;
    var ParentObject = SelectedObject.parent();

    var nDragHandleWidth = 0.075;
    var nDragHandleHeight = 0.075;
    var NewChildDragHandleDiv = $('<div>', {
        class: 'draghandle',
    });

    // Get the selected object postion, so the drag object can be created over it
    var Position = SelectedObject.css('position');
    var nSelectedObjectTop = SelectedObject[0].style.top;
    var nSelectedObjectLeft = SelectedObject[0].style.left;
    var nSelectedObjectWidth = SelectedObject[0].style.width;
    var nSelectedObjectHeight = SelectedObject[0].style.height;
    nSelectedObjectTop = Number(nSelectedObjectTop.replace('in', ''));
    nSelectedObjectLeft = Number(nSelectedObjectLeft.replace('in', ''));
    nSelectedObjectWidth = Number(nSelectedObjectWidth.replace('in', ''));
    nSelectedObjectHeight = Number(nSelectedObjectHeight.replace('in', ''));

    var nDragHandleTop = nSelectedObjectTop;
    var nDragHandleLeft = nSelectedObjectLeft;

    switch (nDragHandleBit) {
        case 1: {
            nDragHandleTop = nSelectedObjectTop - (nDragHandleHeight * 0.75);
            nDragHandleLeft = nSelectedObjectLeft - (nDragHandleWidth * 0.75);
            NewChildDragHandleDiv.draggable({ axis: "x, y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 2: {
            nDragHandleTop = nSelectedObjectTop - (nDragHandleHeight * 0.75);
            nDragHandleLeft = nSelectedObjectLeft + (nSelectedObjectWidth / 2 - nDragHandleWidth / 2);
            NewChildDragHandleDiv.draggable({ axis: "y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 4: {
            nDragHandleTop = nSelectedObjectTop - (nDragHandleHeight * 0.75);
            nDragHandleLeft = nSelectedObjectLeft + nSelectedObjectWidth - (nDragHandleHeight * 0.25);
            NewChildDragHandleDiv.draggable({ axis: "x, y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 8: {
            nDragHandleTop = nSelectedObjectTop + (nSelectedObjectHeight / 2 - nDragHandleHeight / 2);
            nDragHandleLeft = nSelectedObjectLeft + nSelectedObjectWidth - (nDragHandleHeight * 0.25);
            NewChildDragHandleDiv.draggable({ axis: "x", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 16: {
            nDragHandleTop = nSelectedObjectTop + nSelectedObjectHeight - (nDragHandleHeight * 0.25);
            nDragHandleLeft = nSelectedObjectLeft + nSelectedObjectWidth - (nDragHandleHeight * 0.25);
            NewChildDragHandleDiv.draggable({ axis: "x, y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 32: {
            nDragHandleTop = nSelectedObjectTop + nSelectedObjectHeight - (nDragHandleHeight * 0.25);
            nDragHandleLeft = nSelectedObjectLeft + (nSelectedObjectWidth / 2 - nDragHandleWidth / 2);
            NewChildDragHandleDiv.draggable({ axis: "y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 64: {
            nDragHandleTop = nSelectedObjectTop + nSelectedObjectHeight - (nDragHandleHeight * 0.25);
            nDragHandleLeft = nSelectedObjectLeft - (nDragHandleWidth * 0.75);
            NewChildDragHandleDiv.draggable({ axis: "x, y", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
        case 128: {
            nDragHandleTop = nSelectedObjectTop + (nSelectedObjectHeight / 2 - nDragHandleHeight / 2);
            nDragHandleLeft = nSelectedObjectLeft - (nDragHandleWidth * 0.75);
            NewChildDragHandleDiv.draggable({ axis: "x", start: function (event, ui) { OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, drag: function (event, ui) { OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); }, stop: function (event, ui) { OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit); } });
            break;
        }
    }

    // Set location and append
    NewChildDragHandleDiv.css({ top: nDragHandleTop + 'in', left: nDragHandleLeft + 'in', width: nDragHandleWidth + 'in', height: nDragHandleHeight + 'in', position: Position });
    NewChildDragHandleDiv.attr('data-guid', SelectedObjectId);
    NewChildDragHandleDiv.attr('data-pathname', SelectedObjectPathname);
    NewChildDragHandleDiv.attr('draggable', 'true');
    NewChildDragHandleDiv.attr('draghandlebit', nDragHandleBit);
    ParentObject.append(NewChildDragHandleDiv);
}





var DragSelectedObjectByHandlePosition = { top: 0, left: 0, width: 0, height: 0 }


function OnStartDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit) {

    if (SelectedObject == null || SelectedObject.length == 0)
        return;

    var SelectedObjectId = SelectedObject.attr('data-guid');
    var SelectedObjectPathname = SelectedObject.attr('data-pathname');

    var nSelectedObjectTop = SelectedObject[0].style.top;
    var nSelectedObjectLeft = SelectedObject[0].style.left;
    var nSelectedObjectWidth = SelectedObject[0].style.width;
    var nSelectedObjectHeight = SelectedObject[0].style.height;
    nSelectedObjectTop = Number(nSelectedObjectTop.replace('in', ''));
    nSelectedObjectLeft = Number(nSelectedObjectLeft.replace('in', ''));
    nSelectedObjectWidth = Number(nSelectedObjectWidth.replace('in', ''));
    nSelectedObjectHeight = Number(nSelectedObjectHeight.replace('in', ''));

    DragSelectedObjectByHandlePosition = { top: nSelectedObjectTop, left: nSelectedObjectLeft, width: nSelectedObjectWidth, height: nSelectedObjectHeight }
}

/**
 * Called while dragging handles of the selected object
 * @param {any} event
 * @param {any} ui
 * @param {any} SelectedObject
 * @param {any} nDragHandleBit
 * @returns
 */
function OnDragReportObjectHandle(event, ui, SelectedObject, nDragHandleBit) {

    if (SelectedObject == null || SelectedObject.length == 0)
        return;

    var SelectedObjectId = SelectedObject.attr('data-guid');
    var SelectedObjectPathname = SelectedObject.attr('data-pathname');
    //console.log("OnDragReportObjectHandle: " + SelectedObjectId + ", " + nDragHandleBit);

    var AddReportObjectDragPositionInches = GetObjectDragPositionInchesFromHandle(event, ui, SelectedObject, nDragHandleBit);

    var nSelectedObjectTop = SelectedObject[0].style.top;
    var nSelectedObjectLeft = SelectedObject[0].style.left;
    var nSelectedObjectWidth = SelectedObject[0].style.width;
    var nSelectedObjectHeight = SelectedObject[0].style.height;
    nSelectedObjectTop = Number(nSelectedObjectTop.replace('in', ''));
    nSelectedObjectLeft = Number(nSelectedObjectLeft.replace('in', ''));
    nSelectedObjectWidth = Number(nSelectedObjectWidth.replace('in', ''));
    nSelectedObjectHeight = Number(nSelectedObjectHeight.replace('in', ''));

    // New postion for selected object
    // The use original position plus the recent offset from dragging
    var NewYPos = DragSelectedObjectByHandlePosition.top + AddReportObjectDragPositionInches.AddYPosInches;
    var NewXPos = DragSelectedObjectByHandlePosition.left + AddReportObjectDragPositionInches.AddXPosInches;
    var NewWidth = DragSelectedObjectByHandlePosition.width + AddReportObjectDragPositionInches.AddWidthInches;
    var NewHeight = DragSelectedObjectByHandlePosition.height + AddReportObjectDragPositionInches.AddHeightInches;

    // Resize the selected object
    SelectedObject.css({ top: NewYPos + 'in', left: NewXPos + 'in', width: NewWidth + 'in', height: NewHeight + 'in' });
}

/**
 * Resize objects with drag handles
 * OnMouseUp
 * 0=No drag handles
 * 1=Top-left
 * 2=Top-middle
 * 4=Top-right
 * 8=Right-middle
 * 16=Bottom-right
 * 32=Bottom-middle
 * 64=Bottom-left
 * 128=Left-middle
 */
function OnStopDragDropReportObjectHandle(event, ui, SelectedObject, nDragHandleBit) {

    if (SelectedObject == null || SelectedObject.length == 0)
        return;

    var SelectedObjectId = SelectedObject.attr('data-guid');
    var SelectedObjectPathname = SelectedObject.attr('data-pathname');

    //ToastError("Drag handles", "\r\n" + "GUID: " + SelectedObjectId + "\r\nHandle: " + nDragHandleBit);

    // Get the new position based on the drag handle
    var AddReportObjectDragPositionInches = GetObjectDragPositionInchesFromHandle(event, ui, SelectedObject, nDragHandleBit);

    var ContentType = GetSelectedContentType();
    var sPathname = GetSelectedReportPathname();
    AjaxResizeRecordPosition(ContentType, sPathname, SelectedObjectId, AddReportObjectDragPositionInches.AddXPosInches, AddReportObjectDragPositionInches.AddYPosInches, AddReportObjectDragPositionInches.AddWidthInches, AddReportObjectDragPositionInches.AddHeightInches);
}

function GetObjectDragPositionInchesFromHandle(event, ui, SelectedObject, nDragHandleBit) {

    if (SelectedObject == null || SelectedObject.length == 0)
        return null;

    var dpi = GetContentDPI();

    var SelectedObjectId = SelectedObject.attr('data-guid');
    var SelectedObjectPathname = SelectedObject.attr('data-pathname');

    var Position = SelectedObject.css('position');
    var nSelectedObjectTop = SelectedObject[0].style.top;
    var nSelectedObjectLeft = SelectedObject[0].style.left;
    var nSelectedObjectWidth = SelectedObject[0].style.width;
    var nSelectedObjectHeight = SelectedObject[0].style.height;
    nSelectedObjectTop = Number(nSelectedObjectTop.replace('in', ''));
    nSelectedObjectLeft = Number(nSelectedObjectLeft.replace('in', ''));
    nSelectedObjectWidth = Number(nSelectedObjectWidth.replace('in', ''));
    nSelectedObjectHeight = Number(nSelectedObjectHeight.replace('in', ''));

    var AddReportObjectDragPositionInches = { AddXPosInches: 0, AddYPosInches: 0, AddWidthInches: 0, AddHeightInches: 0 };
    var OffsetTop = ui.position.top - ui.originalPosition.top;
    var OffsetLeft = ui.position.left - ui.originalPosition.left;
    var OffsetTopInches = OffsetTop / dpi;
    var OffsetLeftInches = OffsetLeft / dpi;

    var AddXPosInches = 0;
    var AddYPosInches = 0;
    var AddWidthInches = 0;
    var AddHeightInches = 0;

    switch (nDragHandleBit) {
        case 1: {
            // 1=Top-left
            AddXPosInches += OffsetLeftInches;
            AddYPosInches += OffsetTopInches;
            AddWidthInches += (-OffsetLeftInches);
            AddHeightInches += (-OffsetTopInches);
            break;
        }
        case 2: {
            // 2=Top-middle
            AddYPosInches += OffsetTopInches;
            AddHeightInches += (-OffsetTopInches);
            break;
        }
        case 4: {
            // 4=Top-right
            AddYPosInches += OffsetTopInches;
            AddWidthInches += OffsetLeftInches;
            AddHeightInches += (-OffsetTopInches);
            break;
        }
        case 8: {
            // 8=Right-middle
            AddWidthInches += OffsetLeftInches;
            break;
        }
        case 16: {
            // 16=Bottom-right
            AddWidthInches += OffsetLeftInches;
            AddHeightInches += OffsetTopInches;
            break;
        }
        case 32: {
            // 32=Bottom-middle
            AddHeightInches += OffsetTopInches;
            break;
        }
        case 64: {
            // 64=Bottom-left
            AddXPosInches += OffsetLeftInches;
            AddWidthInches += (-OffsetLeftInches);
            AddHeightInches += OffsetTopInches;
            break;
        }
        case 128: {
            // 128 = Left - middle
            AddXPosInches += OffsetLeftInches;
            AddWidthInches += (-OffsetLeftInches);
            break;
        }
    }

    AddReportObjectDragPositionInches = { AddXPosInches: AddXPosInches, AddYPosInches: AddYPosInches, AddWidthInches: AddWidthInches, AddHeightInches: AddHeightInches };
    return AddReportObjectDragPositionInches;
}



function GetContentDPI() {

    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv)
        return 96;

    // Create a new 1-inch div, then get the offsetWidth in pixels
    var NewChildOneInchDiv = $('<div>', {
        left: "0in",
        top: "0in",
        width: "1in",
        height: "1in",
        visibility: "hidden",
    });

    ContentDiv.append(NewChildOneInchDiv);
    const dpi = NewChildOneInchDiv.width(); // This will be the DPI (pixels per inch)
    NewChildOneInchDiv.remove();
    var nDpi = Math.ceil(dpi);
    if (nDpi < 20)
        nDpi = 96;
    return nDpi;

//    const div = document.createElement('div');
//    div.style.width = '1in';
//    div.style.height = '1in';
//    div.style.visibility = 'hidden';
//    document.body.appendChild(div);
//    const dpi = div.offsetWidth; // This will be the DPI (pixels per inch)
//    document.body.removeChild(div);
//    return dpi;
}








function AjaxSaveReport(sNewTitle, sSaveAs) {

    var params = {
        "Pathname": SaveReportPathname,
        "NewTitle": sNewTitle,
        "SaveAs": sSaveAs
    };

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

                // Pathname changed? (Saved in a new location or into database)
                if (response.NewReportPathname) {
                    // ValueString is the report pathname
                    SetSelectedContentPaneValueString(response.NewReportPathname)
                }

                // Refill the entire reports div
                SetupReportFilesInReportFilesDiv();

                // Something to display?
                if (response.PromptTitle && response.PromptMessage)
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);

                ToastMessage("Success!");
            }
            else {
                ToastError("Save report", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxSaveReport", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


function AjaxRenameReport(sPathname) {

    var params = {
        "Pathname": sPathname,
        "NewTitle": "",
        "GetPrompt": "true"
    };

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

                if (response.PromptForValue) {
                    var proceedcallback = AjaxRenameReportWithPrompt;
                    var proceedobject = sPathname;
                    RenameReportPathname = sPathname;
                    PopupPromptForValueBox(response.PromptTitle, response.PromptMessage, response.PromptValue, proceedcallback, proceedobject);
                }
                else {
                    // Should never come here
                    ToastError("Rename report", "Hmm, something went wrong");
                }
            }
            else {
                ToastError("Rename report", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxRenameReport", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxRenameReportWithPrompt(prompt) {

    var params = {
        "Pathname": RenameReportPathname,
        "NewTitle": prompt.sValue,
        "GetPrompt": "false"
    };

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

                // Pathname changed? (Saved in a new location or into database)
                if (response.NewReportPathname) {
                    // ValueString is the report pathname
                    SetSelectedContentPaneValueString(response.NewReportPathname)
                }

                // Refill the entire reports div
                SetupReportFilesInReportFilesDiv();

                RefreshPropertyEditorPartialView();
                RefreshSelectedContent();

                // Something to display?
                if (response.PromptTitle && response.PromptMessage)
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);

                ToastMessage("Success!");
            }
            else {
                ToastError("Rename report", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxRenameReportWithPrompt", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxDeleteReport() {

    var params = {
        "Pathname": DeleteReportPathname,
    };

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

                // Deleted?
                // Close this report tab
                if (response.ReportDeleted) {
                    CloseContentPaneByValueString(DeleteReportPathname);
                    ToastMessage("Success!");
                }

                // Refill the entire reports div
                SetupReportFilesInReportFilesDiv();

                // Something to display?
                if (response.PromptTitle && response.PromptMessage)
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);

                // Temp var
                DeleteReportPathname = "";
            }
            else {
                ToastError("Delete report", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxDeleteReport", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Called when a report view is rebuilt                                                                                                                                                 //
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function ReportViewAfterRebuild(element) {

    // Special attribute holding report info
    if (!element)
        return;
    var ReportPathname = $(element).attr("data-reportpathname");
    if (!ReportPathname)
        return;

    // Show properties
    if (SelectRecordIdAfterRebuild) {

        var ElementObject = FindReportElementObjectFromRecordId(SelectRecordIdAfterRebuild);
        OnClickReportObject(ElementObject);

        // Clear, don't come back here
        SelectTableIdAfterRebuild = "";
        SelectRecordIdAfterRebuild = "";
    }

    // Only open if the "Design" tab is selected
    CheckOpenReportDesignTools();
}


/**
 * Called when report tab is clicked
 * Save the active tab for this report so it can be retrieved on the next refresh
 * */
function OnSetReportViewActiveTab(ReportPathname, event, ui) {

    // Tab "activate" event
    // https://api.jqueryui.com/tabs/

    var ActiveTab = ui.newTab.index();
    ActiveTab = "" + ActiveTab;
    SaveReportActiveTabToCookie(ReportPathname, ActiveTab);

    // Design tab? Open "Design Tools" modeless dialog
    if (ActiveTab == 0)
        OpenReportDesignTools();
    else
        CloseReportDesignTools();
}

/**
 * Called when report view is refreshed
 * Return the active tab index (0=Design, 1=Preview)
 * This allows the active tab to survive repeated refreshes
 * */
function OnGetReportViewActiveTab(ReportPathname) {
    var ActiveTab = LoadReportActiveTabToCookie(ReportPathname);
    ActiveTab = parseInt(ActiveTab, 10);
    return ActiveTab;
}

function IsReportDesignTabSelected() {

    var sPathname = GetSelectedReportPathname();
    var ActiveTab = OnGetReportViewActiveTab(sPathname);
    return (ActiveTab == 0);
}


function GetSelectedReportPathname() {

    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();

    // Still nothing? Yuck, find a report element with the report pathname attribute
    if (!sPathname) {
        var ContentDiv = GetSelectedContentInformationDiv();
        if (ContentDiv) {
            var ReportObject = $(ContentDiv).find(`[data-pathname]`);
            if (ReportObject && ReportObject.length > 0)
                sPathname = ReportObject.attr("data-pathname");
        }
    }

    return sPathname;
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function SaveReport()
{
    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();
    if (!sPathname) {
        ToastError("Save", "Select a report to save, the try again!");
    }
    SaveReportPathname = sPathname;

    AjaxSaveReport(""/*NewTitle*/, "0"/*sSaveAs*/);
}

var SaveReportPathname = "";
function SaveReportAs()
{
    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();
    if (!sPathname) {
        ToastError("Save As", "Select a report to save, the try again!");
    }
    SaveReportPathname = sPathname;

    // Prompt for a new report title
    var proceedcallback = SaveReportWithPrompt;
    var proceedobject = sPathname;
    PopupPromptForValueBox("Save As", "New report title", ""/*PromptValue*/, proceedcallback, proceedobject);
}

function SaveReportWithPrompt(prompt) {
    AjaxSaveReport(prompt.sValue/*NewTitle*/, "1"/*sSaveAs*/);
}



var RenameReportPathname = "";
function RenameReport() {
    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();
    if (!sPathname) {
        ToastError("Rename", "Select a report to rename, the try again!");
    }

    AjaxRenameReport(sPathname);
}

var DeleteReportPathname = "";
function DeleteReport() {
    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();
    if (!sPathname) {
        ToastError("Delete", "Select a report to delete, then try again!");
    }
    DeleteReportPathname = sPathname;

    // Prompt to delete report
    var proceedcallback = AjaxDeleteReport;
    var proceedobject = sPathname;
    PopupYesNoWithDoubleVerification("Delete Report", "Are you sure you wish to delete the report?", proceedcallback, proceedobject)
}



function OnImportCustomReport() {

    FileOpenAndUploadForImport("RPX-REPORT", ".rpx");
}



/**
 * Download an RPX file
 */
function DownloadReportRpxFile() {

    var sPathname = GetSelectedContentPaneValueString();
    if (!sPathname)
        sPathname = $('input[id="HiddenSelectedTableId"]').val();
    if (!sPathname) {
        ToastError("Download", "Select a report to download, then try again!");
    }

    ToastMessage("Download Report RPX File", "Starting now!");
    AjaxGetReportRpxFile(sPathname);
}



function AjaxGetReportRpxFile(sPathname) {

    if (!sPathname)
        return;

    var params = {
        "Pathname": sPathname
    };

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

                if (response.ReportBase64String) {
                    var blob = Base64StringToBlob(response.ReportBase64String);
                    download(blob, response.ReportFilename, response.ReportFileExt);
                }
            }
            else {
                ToastError("View", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nPathname: " + sPathname;
            ToastError("AjaxGetReportRpxFile", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var DraggedObject = null;
var DraggedBoundingClientRect = null;
var DraggedPageCoordinates = null;
var DroppedBoundingClientRect = null;
var DroppedPageCoordinates = null;
var StartDragClientX = 0;
var StartDragClientY = 0;
var StartDragXPosInches = 0;
var StartDragYPosInches = 0;

// Drag and drop report actions
var DRAGACTIONMOVEREPORTOBJECT = "MOVE-REPORT-OBJECT-BY-ID";
var DRAGACTIONINSERTREPORTOBJECT = "INSERT-REPORT-OBJECT-BY-VALUE";

function OnDragStartMoveReportObject(event) {

    var DraggedElement = event.target;
    if (!DraggedElement)
        return;
    DraggedObject = $(DraggedElement);
    if (!DraggedObject || !DraggedObject.length)
        return;

    // Get ID of object being dragged
    var ReportObjectId = DraggedObject.attr('data-guid');
    if (!ReportObjectId)
        return;

    ReportObjectId = ReportObjectId.trim();

    // RptObject guid
    event.dataTransfer.clearData();
    event.dataTransfer.setData("text/plain", DRAGACTIONMOVEREPORTOBJECT + " " + ReportObjectId);
    event.dataTransfer.effectAllowed = "move";
    event.dataTransfer.dropEffect = "move";
    //ToastError("Drag Report Object GUID", ReportObjectId);

    // Remember these for use in drop()
    DraggedBoundingClientRect = event.target.getBoundingClientRect();
    DraggedPageCoordinates = [event.pageX - DraggedBoundingClientRect.left, event.pageY - DraggedBoundingClientRect.top];
    StartDragClientX = event.clientX;
    StartDragClientY = event.clientY;
    StartDragXPosInches = DraggedElement.style.left;
    StartDragYPosInches = DraggedElement.style.top;
    StartDragXPosInches = StartDragXPosInches.replace("in", "");
    StartDragYPosInches = StartDragYPosInches.replace("in", "");
}




function OnDragOverReportObject(event) {
    event.preventDefault();
}





function OnDragDropReportObject(event) {
    event.preventDefault();

    // dataTransfer contains the action is being performed
    var DragData = event.dataTransfer.getData("text/plain");
    if (!DragData) {
        ToastError("Drag Report Object", "Hmm, no dataTransfer info\r\nMust call event.dataTransfer.setData() in 'ondragstart'");
        return;
    }

    // Action tags embedded in dataTransfer value
    var bMoveRptObjectById = (DragData.indexOf(DRAGACTIONMOVEREPORTOBJECT) != -1);
    var bInsertRptObjectByValue = (DragData.indexOf(DRAGACTIONINSERTREPORTOBJECT) != -1);

    // Delete all the action tags, recorded above
    DragData = DragData.replace(DRAGACTIONMOVEREPORTOBJECT, "");
    DragData = DragData.replace(DRAGACTIONINSERTREPORTOBJECT, "");
    DragData = DragData.trim();

    // The only thing left of the drag data is GUID or Name
    var ReportObjectValue = DragData;
    if (!ReportObjectValue)
        return;

    var dpi = GetContentDPI();

    // Dragging an existing report object?
    if (bMoveRptObjectById) {
        DroppedBoundingClientRect = event.target.getBoundingClientRect();
        DroppedPageCoordinates = [event.pageX - DroppedBoundingClientRect.left, event.pageY - DroppedBoundingClientRect.top];
        var DropDistanceClientX = event.clientX - StartDragClientX;
        var DropDistanceClientY = event.clientY - StartDragClientY;
        var DropAddDistanceXInches = DropDistanceClientX / dpi;
        var DropAddDistanceYInches = DropDistanceClientY / dpi;

        var ContentType = GetSelectedContentType();
        var sPathname = GetSelectedReportPathname();
        AjaxMoveRecordPosition(ContentType, sPathname, ReportObjectValue, DropAddDistanceXInches, DropAddDistanceYInches);

        //ToastError("Drag Report Object", "X: " + DropAddDistanceXInches + "\rY: " + DropAddDistanceYInches);
        return;
    }

    // Inserting a new report field?
    if (bInsertRptObjectByValue) {
        var ReportBoundingClientRect = GetDesignTabReportDivBoundingClientRect();
        var DropReportClientX = event.clientX - ReportBoundingClientRect.x;
        var DropReportClientY = event.clientY - ReportBoundingClientRect.y;
        var DropReportXInches = DropReportClientX / dpi;
        var DropReportYInches = DropReportClientY / dpi;

        // Convert Json string to JavaScript object
        // Get ObjectSystemType and ObjectValue
        // These are used to recreate object by System.Type
        var ReportObject = JSON.parse(ReportObjectValue);
        var ReportObjectSystemType = ReportObject.ObjectSystemType;
        ReportObjectValue = ReportObject.ObjectValue;

        var ContentType = GetSelectedContentType();
        var sPathname = GetSelectedReportPathname();
        AjaxInsertNewContentRecordByValue(ContentType, sPathname, ReportObjectSystemType, ReportObjectValue, DropReportXInches, DropReportYInches);
    }
}






//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//




function AjaxMoveRecordPosition(ContentType, TableName, RecordId, AddXPosInches, AddYPosInches) {

    var FilterJsonString = GetSelectedContentPaneFilterJsonString();

    var params = {
        "ContentType": ContentType,
        "TableName": TableName,
        "RecordId": RecordId,
        "AddXPosInches": AddXPosInches,
        "AddYPosInches": AddYPosInches,
        "FilterJsonString": FilterJsonString,
    };

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

                // Reselect and show new properties after the move
                SelectTableIdAfterRebuild = TableName;
                SelectRecordIdAfterRebuild = RecordId;
                RefreshSelectedContent();
            }
            else {
                ToastError("Move", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxMoveRecordPosition", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxResizeRecordPosition(ContentType, TableName, RecordId, AddXPosInches, AddYPosInches, AddWidthInches, AddHeightInches) {

    var FilterJsonString = GetSelectedContentPaneFilterJsonString();

    var params = {
        "ContentType": ContentType,
        "TableName": TableName,
        "RecordId": RecordId,
        "AddXPosInches": AddXPosInches,
        "AddYPosInches": AddYPosInches,
        "AddWidthInches": AddWidthInches,
        "AddHeightInches": AddHeightInches,
        "FilterJsonString": FilterJsonString,
    };

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

                // Reselect and show new properties after the move
                SelectTableIdAfterRebuild = TableName;
                SelectRecordIdAfterRebuild = RecordId;
                RefreshSelectedContent();
            }
            else {
                ToastError("Move", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxMoveRecordPosition", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



function AjaxInsertNewContentRecordByValue(ContentType, TableName, RecordSystemType, RecordValue, XPosInches, YPosInches) {

    var FilterJsonString = GetSelectedContentPaneFilterJsonString();

    var params = {
        "ContentType": ContentType,
        "TableName": TableName,
        "RecordSystemType": RecordSystemType,
        "RecordValue": RecordValue,
        "XPosInches": XPosInches,
        "YPosInches": YPosInches,
        "FilterJsonString": FilterJsonString,
    };

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

                // Reselect and show new properties after the insert
                SelectTableIdAfterRebuild = TableName;
                SelectRecordIdAfterRebuild = response.NewRecordId;
                RefreshSelectedContent();
            }
            else {
                ToastError("Report Object", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxInsertNewContentRecordByValue", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//




