
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// QuickBooks Online functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function ConnectToQuickBooksOnline() {

    ToastMessage("QuickBooks", "Preparing to connect");
    AjaxConnectToQuickBooksOnline();
}

function SilentRefreshQuickBooksConnection() {

    AjaxRefreshQuickBooksConnection(RefreshSelectedContent);
}

function DisconnectFromQuickBooksOnline() {

    ToastMessage("QuickBooks", "Disconnecting");
    AjaxDisconnectFromQuickBooksOnline();
}








function AjaxConnectToQuickBooksOnline() {

    var params = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxConnectToQuickBooksOnline",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.AuthorizeUrl) {
                    // Redirect to QuickBooks auth url
                    //console.log('AjaxConnectToQuickBooksOnline URL: ' + response.AuthorizeUrl);
                    window.location.replace(response.AuthorizeUrl);
                }
            }
            else {
                ToastError("AjaxConnectToQuickBooksOnline", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxConnectToQuickBooksOnline", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxDisconnectFromQuickBooksOnline() {

    var params = {
    };

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

                // Refresh the page to see the QuickBooks connection info
                // Redirecting clears the browser address bar of all the junk from QB OAuth
                if (response.RedirectUrl)
                    window.location.replace(response.RedirectUrl);
                else
                    RefreshSelectedContent();

                // Show the "disconnected" page, required by Intuit QuickBooks
                // Geez, I'm confused. Now they tell me not to launch this page
                //LaunchUrl("https://www.strdtime.com/quickbooksintegrationdisconnected");
            }
            else {
                ToastError("AjaxDisconnectFromQuickBooksOnline", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxConnectToQuickBooksOnline", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxRefreshQuickBooksConnection(successcallback, failedcallback) {

    // Modeless dialog for lengthly operations
    OpenPleaseWaitDialog("QuickBooks");

    var params = {
    };

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

                // Refresh the page to see the QuickBooks connection info
                //RefreshSelectedContent();
                if (response.Connected) {
                    if (successcallback)
                        successcallback();
                }
            }
            else {
                ToastError("AjaxRefreshQuickBooksConnection", response.ErrorResults);
            }

            ClosePleaseWaitDialog();
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxRefreshQuickBooksConnection", errormsg);
            console.log('AJAX: ' + errormsg);
            ClosePleaseWaitDialog();
        }
    });
}






function ImportQuickBooksCustomers() {

    ToastError("QuickBooks", "Still in the early stages. Please bear with us!");

    //OpenQbImportCustomersDialog();

    // QuickBooks connection must be "refreshed" every hour since the last API call
    // QuickBooks access tokens must be refreshed if they expire, which happens an hour after the last API call
    // This ensures that the connection is fresh and ready to use
    AjaxRefreshQuickBooksConnection(OpenQbImportCustomersDialog, FailedQuickBooksRefreshConnection);
}

function FailedQuickBooksRefreshConnection() {
    ToastError("QuickBooks", "Something went wrong. Try connecting to QuickBooks again.");
}

function ExportTimelogsToQuickBooks() {

    OpenQbExportsDialog("QBEXPORTTIME");
}

function ExportExpensesToQuickBooks() {

    OpenQbExportsDialog("QBEXPORTEXPENSES");
}

function CreateQuickBookInvoice(element) {

    if (!element)
        return;
    var ClickedId = $(element).attr('id');
    var ClickedObject = $("#" + ClickedId);
    OnAddInvoicesByPopupMenu(ClickedObject);
}





//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// QB Import Customers



function OpenQbImportCustomersDialog() {

    AjaxRefreshPropertyGridView($("#igDialogQbCustomerQueryPropertiesDiv"), "OBJECT", "QBCUSTOMERQUERY", "QUICKBOOKS", "NORECORDID");

    // Clear dialg controls (from last time)
    $("#igDialogQbCustomerResultsLabel").html("");
    $("#igDialogQbCustomerProgressLabel1").html("");
    $("#igDialogQbCustomerProgressLabel2").html("");
    $("#igDialogQbCustomerProgressBar").hide();

    var nDlgWidth = 500;
    var nDlgHeight = 450;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.98;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogImportQbCustomers").igDialog({ modal: true, headerText: "Import QuickBooks Customers", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade", stateChanged: function (event, ui) { OnQbImportCustomersStateChanged(event, ui); }/*, openAnimation: "fade"*/ });
    $("#igDialogImportQbCustomers").igDialog("open");

    CenterDialog("igDialogImportQbCustomers");

    // Set up controls
    bQbImportCustomersDialogIsOpen = true;

    // OK button click
    $("#igDialogQBImportCustomersOKButton").unbind().click(function () {
        // Begin import now
        if (!bQbCustomerImportInProgress) {
            bQbCustomerImportInProgress = true;
            AjaxImportNextQBCustomer();
        }
    });

    // Close button click
    $("#igDialogQBImportCustomersCancelButton").unbind().click(function () {
        AjaxEndQbCustomerImport();
        CloseQbImportCustomersDialog();
    });

    // Query number of customers
    AjaxQueryQbCustomerCount("QBCUSTOMERQUERY");
}

function OnQbImportCustomersStateChanged(event, ui) {

    if (!ui)
        return;
    if (!ui.action)
        return;

    // Close event
    if (ui.action == 'close') {

        // Closed dialog without saving the newly created record, so delete it
        var bCloseButton = (ui.button == 'close');

        AjaxEndQbCustomerImport();
    }
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the Qb Import Customers dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bQbImportCustomersDialogIsOpen = false;

function CloseQbImportCustomersDialog() {
    $("#igDialogImportQbCustomers").igDialog("close");
    bQbImportCustomersDialogIsOpen = false;

    AjaxEndQbCustomerImport();
}

function IsQbImportCustomersDialogOpen() {
    return bQbImportCustomersDialogIsOpen;
}



var bQbCustomerImportInProgress = false;

function AjaxQueryQbCustomerCount(ContentType) {

    var params = {
        "ContentType": ContentType,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxQueryQbCustomerCount",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.Results)
                    $("#igDialogQbCustomerResultsLabel").html(response.Results);
                $("#igDialogQbCustomerProgressLabel1").html("");
                $("#igDialogQbCustomerProgressLabel2").html("");
                $("#igDialogQbCustomerProgressBar").hide();
            }
            else {
                ToastError("AjaxQueryQbCustomerCount", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxQueryQbCustomerCount", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


function AjaxImportNextQBCustomer() {

    if (!bQbCustomerImportInProgress)
        return;

    var params = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxImportNextQBCustomer",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.Results)
                    $("#igDialogQbCustomerProgressLabel1").html(response.Results);
                if (response.RecordNum)
                    $("#igDialogQbCustomerProgressLabel2").html(response.RecordNum);
                if (response.Record || response.TotalRecords) {
                    $("#igDialogQbCustomerProgressBar").attr('max', response.TotalRecords);
                    $("#igDialogQbCustomerProgressBar").val(response.Record);
                    $("#igDialogQbCustomerProgressBar").show();
                }

                // Done?
                if (response.Complete) {
                    $("#igDialogQbCustomerProgressBar").hide();
                    AjaxEndQbCustomerImport();
                    return;
                }

                // Do the next import
                setTimeout(function () { AjaxImportNextQBCustomer(); }, 50);
            }
            else {
                ToastError("AjaxImportNextQBCustomer", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxImportNextQBCustomer", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



function AjaxEndQbCustomerImport() {

    bQbCustomerImportInProgress = false;

    var params = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxEndQbCustomerImport",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
            }
            else {
                ToastError("AjaxEndQbCustomerImport", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxEndQbCustomerImport", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Export Time and Expenses


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// QB Import Customers



function OpenQbExportsDialog(ObjectDataType) {

    AjaxRefreshPropertyGridView($("#igDialogQbExportRecordsPropertiesDiv"), "OBJECT", ObjectDataType, "QUICKBOOKS", "NORECORDID");

    // Clear dialg controls (from last time)
    $("#igDialogQbRecordsResultsLabel").html("");
    $("#igDialogQbRecordsProgressLabel1").html("");
    $("#igDialogQbRecordsProgressLabel2").html("");
    $("#igDialogQbRecordsProgressBar").hide();

    var nDlgWidth = 500;
    var nDlgHeight = 500;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.98;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogExportQbRecords").igDialog({ modal: true, headerText: "Export To QuickBooks", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade", stateChanged: function (event, ui) { OnQbExportRecordsStateChanged(event, ui); }/*, openAnimation: "fade"*/ });
    $("#igDialogExportQbRecords").igDialog("open");

    CenterDialog("igDialogExportQbRecords");

    // Set up controls
    bQbExportRecordsDialogIsOpen = true;

    // OK button click
    $("#igDialogQBImportRecordsOKButton").unbind().click(function () {
        // Begin import now
        if (!bQbExportRecordsInProgress) {
            bQbExportRecordsInProgress = true;

            // Perform a new query each time "Export" is pressed
            AjaxQueryQbExportRecordCount(ObjectDataType, false/*FirstQuery*/);
            setTimeout(function () { AjaxExportNextQBRecord(); }, 250);
            //AjaxExportNextQBRecord();
        }
    });

    // Close button click
    $("#igDialogQBImportRecordsCancelButton").unbind().click(function () {
        AjaxEndQbExportRecords(ObjectDataType, false/*FirstQuery*/);
        CloseQbExportRecordsDialog();
    });

    // Query number of records to export
    AjaxQueryQbExportRecordCount(ObjectDataType, true/*FirstQuery*/);
}





function OnQbExportRecordsPreview(element) {

    // Pop up a panel to preview the queried records to be exported to QB
    if (!element)
        return;
    var ClickedId = $(element).attr('id');
    var ClickedObject = $("#" + ClickedId);

    // Hidden values used to show preview of QB query
    var ObjectDataType = $("#igDialogQbRecordsObjectDataType").val();
    var ContentType = $("#igDialogQbRecordsContentType").val();
    var DisplayName = $("#igDialogQbRecordsDisplayName").val();
    var DbTable = $("#igDialogQbRecordsDbTable").val();
    var WhereString = $("#igDialogQbRecordsWhereString").val();
    var FilterJsonString = $("#igDialogQbRecordsFilterJsonString").val();
    if (!ObjectDataType)
        return;
    if (!ContentType)
        return;

    CreatePopupForRecordsetList(ClickedObject, "PopupListDiv-ExportRecords-", DbTable, ""/*RecordId*/, "OnClickRecordForQbExport", null/*PerformMenuAction*/, OnQbExportRecordPopupListIsEmpty, FilterJsonString);
}

/**
 * User clicked an invoice in popup list
 * @param {any} evt
 * @param {any} sInvoiceName
 * @param {any} sInvoiceId
 */
function OnClickRecordForQbExport(evt, sRecordName, sRecordId) {
    // Nothing to do here
}

function OnQbExportRecordPopupListIsEmpty(ContentType, TableName, RecordId) {

    CloseLastPopup();
    ToastError("Sorry; no Items to preview");
}



/**
 * Open a new tab to show the QB records that are about to be exported
 * @returns
 */
function OnQbExportRecordsOpenNewTab() {

    // Open a new window to preview the queried records to be exported to QB

    // Hidden values used to show preview of QB query
    var ObjectDataType = $("#igDialogQbRecordsObjectDataType").val();
    var ContentType = $("#igDialogQbRecordsContentType").val();
    var DisplayName = $("#igDialogQbRecordsDisplayName").val();
    var DbTable = $("#igDialogQbRecordsDbTable").val();
    var WhereString = $("#igDialogQbRecordsWhereString").val();
    var FilterJsonString = $("#igDialogQbRecordsFilterJsonString").val();
    if (!ObjectDataType)
        return;
    if (!ContentType)
        return;

    // Ugly hack that will likely break sometime in the future
    // Save the filter to a cookie so that it can be loaded when the new tab is opened
    // The function below is called when a tab is opened, so a cookie must be ready for this function
    // Function called: var filterjsonstring = LoadSelectedPaneFilterJsonStringFromCookie();
    var UniqueId = GetUniqueId();
    var CookieName = "ST-Filter-" + ContentType + "-" + UniqueId;
    setCookie(CookieName, FilterJsonString, 1);

    //ShowStContent(ContentType, ""/*ValueString*/, DisplayName, FilterJsonString);
    var NewContentPanel = AddDocumentTab(ContentType, UniqueId, ""/*ValueString*/, DisplayName, FilterJsonString);
    ActivateDocumentTabByPane(NewContentPanel);

    // Yuck, close this dialog, which takes the user out of their context and into a new tab
    AjaxEndQbExportRecords(ObjectDataType);
    CloseQbExportRecordsDialog();
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the Qb Export Records dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bQbExportRecordsDialogIsOpen = false;
var bQbExportRecordsInProgress = false;

function CloseQbExportRecordsDialog() {
    $("#igDialogExportQbRecords").igDialog("close");
    bQbExportRecordsDialogIsOpen = false;

    AjaxEndQbCustomerImport();
}

function IsQbExportRecordsDialogOpen() {
    return bQbExportRecordsDialogIsOpen;
}

function OnQbExportRecordsStateChanged(event, ui) {

    if (!ui)
        return;
    if (!ui.action)
        return;

    // Close event
    if (ui.action == 'close') {

        // Closed dialog without saving the newly created record, so delete it
        var bCloseButton = (ui.button == 'close');

        AjaxEndQbExportRecords();
    }
}




function AjaxQueryQbExportRecordCount(ObjectDataType, bFirstQuery) {

    if (!ObjectDataType)
        return;

    var params = {
        "ObjectDataType": ObjectDataType,
        "FirstQuery": bFirstQuery,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxQueryQbExportRecordCount",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.Results) {
                    $("#igDialogQbRecordsResultsLabel").html(response.Results);

                    $("#igDialogQbRecordsObjectDataType").val(response.ObjectDataType);
                    $("#igDialogQbRecordsContentType").val(response.ContentType);
                    $("#igDialogQbRecordsDisplayName").val(response.DisplayName);
                    $("#igDialogQbRecordsDbTable").val(response.DbTable);
                    $("#igDialogQbRecordsWhereString").val(response.WhereString);
                    $("#igDialogQbRecordsFilterJsonString").val(response.FilterJsonString);
                }

                // Don't hide these because this function is called after export is complete, and they hold valuable info about export
                //$("#igDialogQbRecordsProgressLabel1").html("");
                //$("#igDialogQbRecordsProgressLabel2").html("");
                //$("#igDialogQbRecordsProgressBar").hide();
            }
            else {
                ToastError("AjaxQueryQbExportRecordCount", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\ObjectDataType: " + ObjectDataType;
            ToastError("AjaxQueryQbExportRecordCount", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



function AjaxExportNextQBRecord() {

    if (!bQbExportRecordsInProgress)
        return;

    var params = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxExportNextQBRecord",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.Results)
                    $("#igDialogQbRecordsProgressLabel1").html(response.Results);
                if (response.RecordNum)
                    $("#igDialogQbRecordsProgressLabel2").html(response.RecordNum);
                if (response.Record || response.TotalRecords) {
                    $("#igDialogQbRecordsProgressBar").attr('max', response.TotalRecords);
                    $("#igDialogQbRecordsProgressBar").val(response.Record);
                    $("#igDialogQbRecordsProgressBar").show();
                }

                // Done?
                if (response.Complete) {
                    $("#igDialogQbRecordsProgressBar").hide();

                    // Requery after all are exported because the "Billed" status has likely changed
                    var ObjectDataType = $("#igDialogQbRecordsObjectDataType").val();
                    AjaxQueryQbExportRecordCount(ObjectDataType, false/*FirstQuery*/);

                    // End
                    AjaxEndQbExportRecords();
                    return;
                }

                // Do the next import
                setTimeout(function () { AjaxExportNextQBRecord(); }, 50);
            }
            else {
                ToastError("AjaxExportNextQBRecord", response.ErrorResults);
                AjaxEndQbExportRecords();
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxExportNextQBRecord", errormsg);
            console.log('AJAX: ' + errormsg);
            AjaxEndQbExportRecords();
        }
    });
}

function AjaxEndQbExportRecords() {

    bQbExportRecordsInProgress = false;

    var params = {
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxEndQbExportRecords",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
            }
            else {
                ToastError("AjaxEndQbExportRecords", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxEndQbExportRecords", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Invoices





function OnAddInvoicesByPopupMenu(ElementObj) {

    if (!ElementObj)
        return;
    if (!ElementObj.length)
        return;

    CreatePopupForRecordsetList(ElementObj, "PopupListDiv-InvoiceItems-", "Invoices"/*sDbTable*/, ""/*RecordId*/, "OnClickInvoiceForQbExport", null/*PerformMenuAction*/, OnInvoicePopupListIsEmpty);
}

/**
 * User clicked an invoice in popup list
 * @param {any} evt
 * @param {any} sInvoiceName
 * @param {any} sInvoiceId
 */
function OnClickInvoiceForQbExport(evt, sInvoiceName, sInvoiceId) {

    AjaxExportInvoiceToQb(sInvoiceId);

    // Close the popup
    CloseLastPopup();
}

/**
 * Called when a popup list is empty. No point in popping up an empty list. Do something else instead.
 * @param {any} ContentType
 * @param {any} TableName
 * @param {any} RecordId
 */
function OnInvoicePopupListIsEmpty(ContentType, TableName, RecordId) {

    // Punt and show invoice grid so user can add a new invoice, then export it to QB
    CloseLastPopup();
    ShowInvoiceGridView();

    ToastMessage("Invoices", "Create a new invoice to export");
}



function AjaxExportInvoiceToQb(sInvoiceId) {

    var params = {
        "InvoiceId": sInvoiceId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxExportInvoiceToQb",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ErrorResults)
                    ToastError("QuickBooks", response.ErrorResults);
                if (response.Results)
                    ToastMessage("QuickBooks", response.Results);
            }
            else {
                ToastError("AjaxExportInvoiceToQb", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxExportInvoiceToQb", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}






