@using PantheonRA.BackOffice.Enums
@using PAW.Contracts.Enums

<div class="modal inmodal fade" id="moveAdvancePaymentLinksModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-full" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <input id="MoveAdvancePaymentLinksIsPos" hidden />
                <input id="MoveAdvancePaymentLinksType" hidden />
                <input id="MoveAdvancePaymentLinksSubject" hidden />
                <input id="MoveAdvancePaymentLinksInvoiceDate" hidden />
                <div class="form-horizontal form-md">
                    <div class="row">
                        <div class="col-xs-6 padding-left-none">
                            <h3>@Loc.AdvancePayments</h3>
                        </div>
                        <div class="col-xs-6 text-right">
                            <a class="btn-transparent m-r-sm" onclick="moveAdvancePaymentLinksHelp()" title="@Loc.CheckInstructions"><i class="fas fa-question clickable-icon"></i></a>
                            <i class="fa fa-times clickable-icon" data-dismiss="modal" title="@Loc.Close"></i>
                        </div>
                    </div>
                    <div class="row">

                    </div>
                    <div class="row">
                        <div id="placeholderMoveAdvancePaymentLinks" class="placeholder placeholder-modal placeholder-clipboard-coins"><span class="placeholder-text">@Loc.CommissionItemsPlaceholderText</span></div>
                        <div id="moveAdvancePaymentLinksContainer" class="project-list m-t-sm">
                            <table id="moveAdvancePaymentLinksGrid" class="table advance-payment-modal-table">
                                <thead>
                                    <tr>
                                        <th width="3%" class="dt-head-center select-all">
                                            <input id="markAll" onclick="selectAllMoveAdvancePayments(this)" type="checkbox" />
                                        </th>
                                        <th width="8%"
                                            data-url="@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")?id="
                                            data-url-1="@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=">
                                            @Loc.Document
                                        </th>
                                        <th width="9%">@Loc.Document 1</th>
                                        <th width="9%">@Loc.Document 2</th>
                                        <th width="6%" class="dt-head-center">@Loc.UseDocument1OrAndDocument2</th>
                                        <th width="11%" class="dt-head-center">@Loc.UseTaxDateForDoc1</th>
                                        <th width="6%">@Loc.Date</th>
                                        <th width="6%" class="dt-head-right">@Loc.PaidAdvancePayment</th>
                                        <th width="6%" class="dt-head-right">@Loc.PaidTax</th>
                                        <th width="6%" class="dt-head-right">@Loc.SelectedPrice</th>
                                        <th width="8%" class="dt-head-right">@Loc.BasisForTax</th>
                                        <th width="6%" class="dt-head-right">@Loc.GridTax</th>
                                        <th width="8%" class="dt-head-right">@Loc.AdvancePaymentPrice</th>
                                        <th width="4%">@Loc.Currency</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="col-xs-12 advance-payment-modal-footer">
                    <label>@Loc.GridTax:</label>
                    <label id="totalTax" class="value-label m-r-sm">0</label>
                    <label>@Loc.Payment:</label>
                    <label id="totalPayment" class="value-label">0</label>
                    <button type="button" id="confirmMoveAdvancePaymentsBtn" class="btn btn-primary m-l-sm" onclick="confirmSelectedMoveAdvancePaymentLinks()">
                        <i class="fa fa-check m-r-xs"></i>@Loc.Confirm
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal inmodal fade" id="moveAdvancePaymentLinkCreatedModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <div class="iris-title m-b-sm">
                    <div class="row">
                        <div class="col-xs-11 padding-right-none">
                            <span><strong>@Loc.CreationOfNegativeAdvancePaymentsCompletedIRIS</strong></span>
                        </div>
                        <div class="col-xs-1 pull-right">
                            <i class="fa fa-times clickable-icon m-l-xs" data-dismiss="modal"></i>
                        </div>
                    </div>
                </div>
                <span id="createdAdvancePaymentLinksMessage">@Loc.CreatedNegativeAdvancePaymentNum</span>
                <div class="well well-sm well-bg clickable-icon m-b-sm m-t-sm" data-dismiss="modal" onclick="openCreatedAdvancePaymentDocument()">
                    <input id="createdAdvancePaymentsKeys" hidden />
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-arrow-right"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.OpenAdvancePayment</strong>
                            <p class="no-margins" id="openCreatedNegativeAdvancePaymentDocumentsText">@Loc.OpenCreatedNegativeAdvancePaymentDocuments</p>
                        </div>
                    </div>
                </div>
                <div class="well well-sm well-bg clickable-icon m-b-sm" data-dismiss="modal" id="advancePaymentCreatedContinueOpenOrPrint">
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-arrow-right"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.Continue</strong>
                            <p class="no-margins">@Loc.ContinueWithWork</p>
                        </div>
                    </div>
                </div>
                <div class="well well-sm well-bg clickable-icon m-b-sm" onclick="openCreatedAdvancePaymentHelp()">
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-help icon-full-size"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.ViewInstructions</strong>
                            <p class="no-margins">@Loc.ViewInstructionsDescription</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal inmodal fade" id="moveAdvancePaymentLinksOpenWarningModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <div class="iris-title m-b-sm">
                    <div class="row">
                        <div class="col-xs-11 padding-right-none">
                            <span><strong id="subjectHasOpenAdvancePaymentsMsg">@Loc.BuyerHasOpenAdvancePayments</strong></span>
                        </div>
                        <div class="col-xs-1 pull-right">
                            <i class="fa fa-times clickable-icon m-l-xs" data-dismiss="modal"></i>
                        </div>
                    </div>
                </div>
                <span id="subjectOnOpenMsg">@Loc.BuyerOnDocumentHasOpenAdvancePayments</span>
                <div class="well well-sm well-bg clickable-icon m-b-sm m-t-sm" data-dismiss="modal" onclick="openAdvancePaymentLinks()">
                    <input id="createdAdvancePaymentsKeys" hidden />
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-arrow-right"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.OpenAdvancePayments</strong>
                            <p class="no-margins">@Loc.OpenAdvancePaymentsOnDocument</p>
                        </div>
                    </div>
                </div>
                <div class="well well-sm well-bg clickable-icon m-b-sm" data-dismiss="modal" id="advancePaymentContinueOpenOrPrint">
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-arrow-right"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.Continue</strong>
                            <p class="no-margins">@Loc.ContinueWithWorkOrPrint</p>
                        </div>
                    </div>
                </div>
                <div class="well well-sm well-bg clickable-icon m-b-sm" onclick="openAdvancePaymentForSubjectHelp()">
                    <div class="row">
                        <div class="col-xs-2">
                            <div class="icon-help icon-full-size"></div>
                        </div>
                        <div class="col-xs-10 well-text-margin">
                            <strong>@Loc.ViewInstructions</strong>
                            <p class="no-margins">@Loc.ViewInstructionsDescription</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var selectedMoveAdvancePaymentLinkItems = [];
    var allMoveAdvancePaymentItems = [];
    var selectedAdvancePayment;

    $(document).ready(function () {
        $("#totalPayment").text(formatDisplay(2, $("#totalPayment").text()));
        $("#totalTax").text(formatDisplay(2, $("#totalTax").text()));
        $('#moveAdvancePaymentLinksModal .modal-dialog').draggable();
    });

    function refreshMoveAdvancePaymentLinksTable(moveAdvancePaymentItems) {
        $moveAdvancePaymentLinksDataTable = $('#moveAdvancePaymentLinksGrid');
        if ($.fn.dataTable.isDataTable('#moveAdvancePaymentLinksGrid'))
            $moveAdvancePaymentLinksDataTable.DataTable().destroy();

        $moveAdvancePaymentLinksDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: true,
            responsive: false,
            info: false,
            data: moveAdvancePaymentItems,
            columns: [
                {
                    data: "Marked",
                    orderable: false,
                    className: 'dt-body-center',
                    render: function (data, type, full) { return '<input class="ackey-selector" id="marked-' + full.AcKey + '" name="MoveAdvancePaymentLinkAcKey" onclick=selectedMoveAdvnacePaymentLink(this)  value="' + full.AcKey + '" type="checkbox" ' + (full.Marked == "T" ? "checked" : "") + ' />' }
                },
                {
                    data: "AcKeyView",
                    render: $.fn.dataTable.render.link("AcKey", false, $("#MoveAdvancePaymentLinksType").val() === '@AdvancePaymentMoveLinksType.Wholesale' ? 0 : 1)
                },
                { data: "Doc1" },
                { data: "Doc2" },
                { data: "UseDoc1Doc2", render: $.fn.dataTable.render.checkbox(), className: 'dt-body-center' },
                { data: "UseDateVatFromInvoice", render: $.fn.dataTable.render.checkbox(), className: 'dt-body-center' },
                { data: "Date" },
                { data: "Paid", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
                { data: "PaidTax", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
                {
                    data: "Selected",
                    render: function (data, type, full) {
                        return '<input id="selected-' + full.AcKey + '" type="text" value="' + full.Selected + '" step="2" onblur="changeIdentSelected(' + full.AcKey + ')" min="0" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" />';
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "VatBase",
                    render: function(data, type, full) {
                        return '<input id="vatBase-' + full.AcKey + '" type="text" value="' + full.VatBase + '" step="2" onblur="changeIdentVatBase(' + full.AcKey + ')" min="0" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" />';
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "SelectedTax",
                    render: function (data, type, full) {
                        return '<input id="selectedTax-' + full.AcKey + '" type="text" value="' + full.SelectedTax + '" step="2" min="0" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" />';
                    },
                    className: 'dt-body-right'
                },
                { data: "Total", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
                { data: "Currency" }
            ]
        });

        allMoveAdvancePaymentItems = moveAdvancePaymentItems;
        if (moveAdvancePaymentItems && moveAdvancePaymentItems.length > 0) {
            $("#placeholderMoveAdvancePaymentLinks").addClass("hidden");
            calculateTotalPriceAndTax();
        }

        if (!moveAdvancePaymentItems.some(x => x.Marked === "@ActiveStatus.Inactive"))
            $("#confirmMoveAdvancePaymentsBtn").attr("disabled", true);

        initializeNumberInputs();
    }

    function selectedMoveAdvnacePaymentLink(cb) {
        var rowData = allMoveAdvancePaymentItems.find(x => x.AcKey == cb.value);

        if (cb.checked) {
            selectedMoveAdvancePaymentLinkItems.push(cb.value);
            rowSelectedCalculatePrices(cb.value);
            rowData.Marked = "@Status.Active";
        } else {
            rowData.Marked = "@Status.Inactive";
            var index = selectedMoveAdvancePaymentLinkItems.indexOf(cb.value);
            if (index !== -1)
                selectedMoveAdvancePaymentLinkItems.splice(index, 1);

            setDefaultPrices(cb.value);
        }
    }

    function selectAllMoveAdvancePayments(cb) {
        $('.ackey-selector').each(function (i, obj) {
            obj.checked = cb.checked;
            selectedMoveAdvnacePaymentLink(obj);
        });
    }

    function movePrePayOpen(acKey, $element, type) {
        var value = toNumber($element.val());
        if (!selectedAdvancePayment)
            return;

        $.get("@Url.Action("MovePrePayOpen", "AdvancePayment")?acKey=" + acKey, function (response) {
            if (response) {
                if ((type === @MovePrePayOpenCalcType.Selected && response < value) || (type === @MovePrePayOpenCalcType.VatBase && (response < value + selectedAdvancePayment.VAT))) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.TheAmountEnteredIsTooLarge",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.OK",
                                action: function () {
                                    $element.val(0);
                                    formatNumberInput($element);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else {
                    var rowData = allMoveAdvancePaymentItems.find(x => x.AcKey == acKey);

                    if (type === @MovePrePayOpenCalcType.Selected) {
                        var selectedTax = rowData.PaidTax * (value / rowData.Paid);
                        rowData.Selected = value;
                        rowData.SelectedTax = selectedTax;
                        rowData.VatBase = value - selectedTax;

                        $("#selectedTax-" + acKey).val(selectedTax);
                        $("#vatBase-" + acKey).val(value - selectedTax);
                        formatNumberInput($("#selectedTax-" + acKey));
                        formatNumberInput($("#vatBase-" + acKey));
                    } else if (type === @MovePrePayOpenCalcType.VatBase) {
                        if (value > 0) {
                            var factor = selectedAdvancePayment.VAT / selectedAdvancePayment.Price;
                            var selectedTax = value * factor;
                            rowData.SelectedTax = selectedTax;
                            rowData.Selected = value + selectedTax;
                            rowData.VatBase = value;

                            $("#selectedTax-" + acKey).val(selectedTax);
                            $("#selected-" + acKey).val(value + selectedTax);
                            formatNumberInput($("#selectedTax-" + acKey));
                            formatNumberInput($("#selected-" + acKey));
                        }
                    }

                    calculateTotalPriceAndTax();
                }
            }
        });
    }

    function rowSelectedCalculatePrices(acKey) {
        var rowData = allMoveAdvancePaymentItems.find(x => x.AcKey == acKey);
        var markedData = allMoveAdvancePaymentItems.filter(y => y.Marked == true || y.Marked == "T");
        var apTotalPrice = markedData.reduce((a, b) => a + (b['Selected'] || 0), 0);
        var apTotalTax = markedData.reduce((a, b) => a + (b['SelectedTax'] || 0), 0);
        var tax = toNumber($("#TaxAmount").val());
        var toPay = toNumber($("#ToPayAmount").text());

        if ($("#MoveAdvancePaymentLinksIsPos").val() === "True") {
            toPay = toNumber($("#ToPayAmount").val());
        }

        if (toPay < apTotalPrice + rowData.Paid) {
            $("#selected-" + rowData.AcKey).val(toPay - apTotalPrice);
            $("#selectedTax-" + rowData.AcKey).val(tax - apTotalTax);
            $("#vatBase-" + rowData.AcKey).val($("#selected-" + rowData.AcKey).val() - $("#selectedTax-" + rowData.AcKey).val());
        } else {
            $("#selected-" + rowData.AcKey).val(rowData.Paid);
            $("#selectedTax-" + rowData.AcKey).val(rowData.PaidTax);
            $("#vatBase-" + rowData.AcKey).val($("#selected-" + rowData.AcKey).val() - $("#selectedTax-" + rowData.AcKey).val());
        }

        rowData.Selected = toNumber($("#selected-" + rowData.AcKey).val());
        rowData.SelectedTax = toNumber($("#selectedTax-" + rowData.AcKey).val());
        rowData.VatBase = toNumber($("#vatBase-" + rowData.AcKey).val());

        formatNumberInput($("#selected-" + rowData.AcKey));
        formatNumberInput($("#selectedTax-" + rowData.AcKey));
        formatNumberInput($("#vatBase-" + rowData.AcKey));
        calculateTotalPriceAndTax();
    }

    function calculateTotalPriceAndTax() {
        var totalPrice = 0;
        var totalTax = 0;

        allMoveAdvancePaymentItems.forEach(x => {
            totalPrice += x.Selected;
            totalTax += x.SelectedTax;
        });

        $("#totalPayment").text(formatDisplay(2, totalPrice));
        $("#totalTax").text(formatDisplay(2, totalTax));
    }

    function setDefaultPrices(acKey) {
        var rowData = allMoveAdvancePaymentItems.find(x => x.AcKey == acKey);

        rowData.Selected = 0;
        rowData.SelectedTax = 0;
        rowData.VatBase = 0;
        $("#selected-" + acKey).val(0);
        $("#selectedTax-" + acKey).val(0);
        $("#vatBase-" + acKey).val(0);
        formatNumberInput($("#selected-" + acKey));
        formatNumberInput($("#selectedTax-" + acKey));
        formatNumberInput($("#vatBase-" + acKey));

        calculateTotalPriceAndTax();
    }

    async function confirmSelectedMoveAdvancePaymentLinks() {
        if (allMoveAdvancePaymentItems && !allMoveAdvancePaymentItems.some(x => x.Marked === "@ActiveStatus.Active")) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.DocumentNotCreatedSelectAdvancePaymentForClosure",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

        $("#confirmMoveAdvancePaymentsBtn i").addClass("fa-spin fa-spinner").removeClass("fa-check");

        if ((($("#FiscalNumber").val() || $("#FiscalCode").val()) && "@PantheonRA.BackOffice.CurrentUser.Localization" !== "@Localization.Code.HR")
            || ($("#FiscalCode").val() && "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR")) {
            $("#documentFiscalizedCannotDeleteWarningModal").modal("show");
            $("#confirmMoveAdvancePaymentsBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
        } else {
            var model = {
                Type: $("#MoveAdvancePaymentLinksType").val(),
                DocType: $("#DocType").val(),
                DocTypeNegAdvPay: "",
                AcKey: $("#AcKey").val(),
                Date: $("#MoveAdvancePaymentLinksInvoiceDate").val(),
                FXRate: 1,
                Error: "@Loc.SetDocumentType",
                Subject: $("#MoveAdvancePaymentLinksSubject").val(),
                RequestType: "O",
                AdvancePaymentLinkItemsJsonString: JSON.stringify(allMoveAdvancePaymentItems),
                IsPOS: $("#MoveAdvancePaymentLinksIsPos").val() && $("#MoveAdvancePaymentLinksIsPos").val() === "True"
            };

            await fetch('@Url.Action("AdvancePaymentConfirmation", "AdvancePayment")', {
                method: "POST",
                body: JSON.stringify(model),
                headers: { 'Content-Type': 'application/json' },
            }).then((response) => response.json()
            ).then(async (response) => {
                if (response) {
                    if (response.Error) {
                        $("#confirmMoveAdvancePaymentsBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "alert",
                            text: response.Error,
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                        return;
                    }

                    $("#createdAdvancePaymentLinksMessage").text("@Loc.CreatedNegativeAdvancePaymentNum " + (response.FormattedList ? response.FormattedList : ""));
                    $("#openCreatedNegativeAdvancePaymentDocumentsText").text("@Loc.OpenCreatedNegativeAdvancePaymentDocuments " + (response.FormattedList ? response.FormattedList : ""));
                    $("#createdAdvancePaymentsKeys").val(response.MinAcKey);

                    if (response.AdvancePaymentConnections) {
                        $("#advancePaymentConnectionsContainer").html("");
                        AddInvoiceDocumentConnections(response.AdvancePaymentConnections, '@TypeOfDoc.AdvancePayment');
                        let avansConnections = response.AdvancePaymentConnections.filter(paymentConnection => paymentConnection.Type === "G");
                        let avansValueSum = avansConnections.reduce((partialSum, paymentConnection) => partialSum + paymentConnection.Price, 0);
                        avansValue = avansValueSum;

                        for (const advPayCon of response.AdvancePaymentConnections) {
                            if (advPayCon.LPFR === true) {
                                await lpfrFiscalization(advPayCon.LPFRCheckServer, advPayCon.LPFRServer, '@Url.Action("LPFRUpdateInvoice", "Move")', advPayCon.LPFRJson, advPayCon.AcKey, null, function (err) {
                                    advPayCon.FiscError = "@Loc.FiscalizationError";
                                });
                            }
                        }

                        $("#moveAdvancePaymentLinksModal").modal('hide');
                        $("#confirmMoveAdvancePaymentsBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
                        $("#moveAdvancePaymentLinkCreatedModal").modal("show");

                        if (response.AdvancePaymentConnections.some(s => s.FiscError)) {
                            var fiscErrors = "";
                            for (const advPayConn of response.AdvancePaymentConnections) {
                                if (advPayConn.FiscError)
                                    fiscErrors += advPayConn.AcKey + ": " + advPayConn.FiscError + "</br></br>";
                            }

                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "alert",
                                text: fiscErrors,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Confirm",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                }
            }).catch((error) => {
                $("#confirmMoveAdvancePaymentsBtn i").removeClass("fa-spin fa-spinner").addClass("fa-check");
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.GeneralError",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            });
        }
    }

    function changeIdentSelected(acKey) {
        getAdvancePaymentData(acKey, $("#selected-" + acKey), @MovePrePayOpenCalcType.Selected);
    }

    function changeIdentVatBase(acKey) {
        getAdvancePaymentData(acKey, $("#vatBase-" + acKey), @MovePrePayOpenCalcType.VatBase);
    }

    function getAdvancePaymentData(acKey, value, type) {
        $.get("@Url.Action("GetById", "AdvancePayment")?id=" + acKey, function (response) {
            if (response) {
                selectedAdvancePayment = response;
                movePrePayOpen(acKey, value, type);
            }
        });
    }

    function openCreatedAdvancePaymentHelp() {
        window.open('@Loc.HelpUrl@HelpIds.MoveAdvancePaymentLinksCreated', '_blank');
    }

    function openCreatedAdvancePaymentDocument() {
        var ackey = $("#createdAdvancePaymentsKeys").val();
        if ($("#MoveAdvancePaymentLinksType").val() === '@AdvancePaymentMoveLinksType.Wholesale')
            window.open('@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")?id=' + ackey, '_blank');
        else
            window.open('@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=' + ackey, '_blank');
    }

    function openAdvancePaymentLinks() {
        $("#moveAdvancePaymentLinksModal").modal('show');
    }
</script>