@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@using PantheonRA.WebApi.Contracts.Enums
@model AdvancePaymentCreateData

@{
    ViewBag.Title = Loc.AdvancePayments;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("~/Views/ReceivedBills/_IssuedAdvancePaymentsTabNavigation.cshtml")
        <div class="tab-content">
            <form method="post" id="AdvancePaymentForm">
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                @Html.HiddenFor(model => model.IsVATObligee)
                @Html.HiddenFor(model => model.IsTaxPeriodLocked)
                @Html.HiddenFor(model => model.TaxPeriodError)
                @Html.HiddenFor(model => model.FiscalStatus)
                @Html.HiddenFor(model => model.SelectedCountry)
                @Html.HiddenFor(model => model.AdvancePaymentType)
                @Html.HiddenFor(model => model.UserDepartment)
                @Html.HiddenFor(model => model.FillDeptFromCostDrv)
                @Html.HiddenFor(model => model.FilterDeptForCostDrv)
                @Html.HiddenFor(model => model.CalcFxRateDateType)

                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        ShowCloseBtn = false,
                        BackUrl = Url.Action("ReceivingAdvancePayments", "AdvancePayment"),
                        SaveButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Save, Icon = "far fa-print fa-lg", OnClick = "onClickSave()", Class = "hidden" },
                                new FormButton { Text = Loc.SaveAndNew, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndNew + "')" },
                                new FormButton { Text = Loc.SaveAndPrint, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndPrint + "')" },
                                new FormButton { Text = Loc.SaveAndClose, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndClose + "')" }
                            }
                        },
                        PrintSettings = Model.PrintSettings,
                        PrintType = ReportFormName.AdvancePaymentIssued,
                        PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                            Model.ReportTreeViewModel,
                            "onClickSave('" + InvoiceSaveType.SaveAndPrint + "', '{0}')",
                            "onClickSave('" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                        ),
                        IsWizardDisabled = string.IsNullOrEmpty(Model.AcKey) ? true : false,
                        IsWizardVisible = true,
                        WizardButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.CloseAdvancePayment, Icon = "", OnClick = "advancePaymentCancelModal()", Class = "hidden" },
                                new FormButton { Text = Loc.CloseAdvancePayment, Icon = "", OnClick = "advancePaymentCancelModal()" },
                            }
                        }
                    })

                    <button id="invoiceDelete" type="button" onclick="deleteInvoice()" title="@Loc.Delete"
                            class="btn btn-danger btn-outline pull-right collapsable-form-button @(string.IsNullOrEmpty(Model.AcKey) ? "hidden" : string.Empty)">
                        <i class="far fa-trash-alt m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.Delete</span>
                    </button>

                    <a title="@Loc.New" id="newInvoiceButton" onclick="createNewInvoice('@Url.Action("CreateIssuedAdvancePayment", "AdvancePayment")', 'DocType')"
                       class="btn btn-primary btn-outline pull-right collapsable-form-button @(string.IsNullOrEmpty(Model.AcKey) ? "hidden" : string.Empty)">
                        <i class="fas fa-plus m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.New</span>
                    </a>
                </div>

                <div class="divided-content clearfix">
                    <div class="divided-content-main">
                        <div class="placeholder placeholder-invoice-coins-adv">
                            <span class="placeholder-text">
                                @Loc.IssuedAdvancePaymentPlaceholder
                            </span>
                        </div>
                        <div class="row document-head">
                            <div class="col-md-2 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ? string.Empty : "document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.DocType, Loc.DocType, new { @class = "control-label" })
                                    @Html.HiddenFor(model => model.CanFiscalize)
                                    @Html.HiddenFor(model => model.DocType)
                                    <select id="DocTypeSelect" name="DocTypeSelect" class="form-control custom-select" @(string.IsNullOrEmpty(Model.AcKey) ? "" : "disabled")>
                                        @foreach (var item in ViewBag.DocumentTypes)
                                        {
                                            <option value="@item.Id"
                                                    data-fiscalize="@item.CanFiscalize"
                                                    data-warehouse="@item.Warehouse"
                                                    data-payMethod="@item.PayMethod"
                                                    data-defaultNote="@item.DefaultNote"
                                                    data-department="@item.Department"
                                                    data-doc1="@item.Doc1"
                                                    data-doc2="@item.Doc2"
                                                    data-docTypeAssmbly="@item.DocTypeAssmbly"
                                                    @(Model.DocType == item.Id ? "selected" : string.Empty)>
                                                @item.Value
                                            </option>
                                        }
                                    </select>
                                    @Html.ValidationMessageFor(model => model.DocType, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="col-md-4 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Issuer, Loc.Supplier, new { @class = "control-label", @title = Loc.Supplier })
                                    @Html.ValidationMessageFor(model => model.IssuerId, "", new { @class = "text-danger m-l-xs", @id = "IssuerId-validation" })
                                    <div>
                                        <input id="ValidSupplierId" value="@Model.IssuerId" hidden />
                                        @Html.HiddenFor(model => model.IssuerId)
                                        @Html.TextBoxFor(model => model.Issuer,
                                          HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_large addable-input", "Issuer", false, Loc.Supplier, true,
                                          new { dataUrl = Url.Action("SearchSuppliers", "ReceivedBills"), @title = Model.Issuer }))
                                        <div class="addable-button">
                                            <button type="button" title="@Loc.AddingNewPartner"
                                                    id="NewPartner" class="btn createNewButton" onclick="openSubjectModal('Issuer')">
                                                <i class="fas fa-building"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-2 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.PaymentMethod, Loc.PaymentMethod, new { @class = "control-label" })
                                    <select id="PaymentMethodId" name="PaymentMethodId" class="form-control custom-select">
                                        <option></option>
                                        @foreach (var item in ViewBag.PaymentTypes)
                                        {
                                            <option value="@item.PaymentMethod" data-fiscalize="@item.FiscalGroup" @(Model.PaymentMethodId == item.PaymentMethod ? "selected" : string.Empty)>
                                                @(item.PaymentMethod) - @(item.Name)
                                            </option>
                                        }
                                    </select>
                                    @Html.ValidationMessageFor(model => model.PaymentMethodId, "", new { @class = "text-danger", @id = "PaymentMethodId-validation" })
                                </div>
                            </div>

                            <div class="col-md-2 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Status, Loc.Status, new { @class = "control-label" })
                                    @Html.DropDownListFor(model => model.Status,
                                        new SelectList(ViewBag.DocumentStatuses != null ? ViewBag.DocumentStatuses : new List<string>(), "Status", "Name"), Loc.Select,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Status", false, Loc.Status))
                                    @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="col-md-2 col-sm-12 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Loc.Number, new { @class = "control-label m-t-xs" })
                                    @Html.HiddenFor(model => model.AcKey)
                                    <h4 class="control-label" id="AcKeyDisplayContainer">
                                        @{
                                            Html.RenderPartial("~/Views/Shared/Components/_PrevNextKeyDisplay.cshtml",
                                            new PrevNextKeyDisplayViewModel
                                            {
                                                KeyDisplayHint = Loc.ListOfIssuedAdvancedPayments,
                                                KeyDisplayValue = Model.AcKeyDisplay,
                                                NextNavigation = Url.Action("Next", "Move", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("EditIssuedAdvancePayment", "AdvancePayment", new { id = "{id}" })
                                                }),
                                                PrevNavigation = Url.Action("Prev", "Move", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("EditIssuedAdvancePayment", "AdvancePayment", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action("IssuedAdvancePayments", "ReceivedBills", new { acKey = Model.AcKey, date = Model.Date.Value.ToString("o") })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>

                        <div class="document-body">
                            <div class="row">
                                <div class="col-lg-8 col-md-10 col-sm-11 col-xs-12">
                                    @Html.Partial("_InvoiceIdentInput", new DecimalPlacesViewModel
                                    {
                                        DefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
                                        DefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
                                        DefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue,
                                        Price1Text = Model.Price1Text,
                                        Price2Text = Model.Price2Text,
                                        Price3Text = Model.Price3Text,
                                        Price4Text = Model.Price4Text,
                                    })
                                </div>
                            </div>

                            <div class="table-responsive document-table m-b-md">
                                <div class="dt-bootstrap" style="position:relative">
                                    <table id="invoice" data-grid-id="created-issued" data-dynamic-table="true" class="table table-bordered showhidecolumns" role="grid">
                                        <thead>
                                            <tr role="row">
                                                <th data-column-id="Position" style="width:4%" data-sortable="false">@Loc.PositionShort</th>
                                                <th data-column-id="Ident" style="width:@(Model.IsVATObligee ? "20%" : "25%")">@Loc.Ident</th>
                                                <th data-column-id="Name" style="width:@(Model.IsVATObligee ? "20%" : "25%")">@Loc.Name</th>
                                                <th data-column-id="Quantity" class="text-right" style="width:7%">@Loc.Quantity</th>
                                                <th data-column-id="Price">@Loc.Price</th>
                                                <th data-column-id="Discount" style="width:7%">@Loc.Discount %</th>
                                                @if (Model.IsVATObligee)
                                                {
                                                    <th data-column-id="VAT" style="width:6%">@Loc.VAT</th>
                                                }
                                                <th data-column-id="Value" class="text-right">@Loc.Value</th>
                                                <th data-column-id="CostCarrier" style="width:7%">@Loc.CostCarrier</th>
                                                <th data-column-id="Department" data-default-hidden="true" style="width:7%">@Loc.Department</th>
                                                <th data-column-id="CommentDelete" style="min-width:72px; width:72px;" data-sortable="false"></th>
                                            </tr>
                                        </thead>
                                        <tbody id="identRows"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="row document-footer">
                            <div class="col-md-1 col-sm-4">
                                <div class="form-group text-center @(string.IsNullOrEmpty(Model.Note) ? string.Empty : "btn-active")"
                                     onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note)
                                    <i id="noteIcon" class="fa fa-comment clickable-icon"></i>
                                    @Html.TextAreaFor(model => model.Note,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control", "Note", false, Loc.Note, false, new { @rows = 3, @maxlength = "4096", @class = "hidden" }))
                                    @Html.ValidationMessageFor(model => model.Note, "", new { @class = "text-danger", @id = "Note-validation" })
                                </div>
                            </div>
                            <div class="col-md-4 col-sm-4">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Statement, Loc.TextBottom, new { @class = "control-label m-t-sm" })
                                    @Html.HiddenFor(model => model.Statement)
                                    @Html.DropDownList("Statements", new SelectList(ViewBag.DocTexts != null ? ViewBag.DocTexts : new List<string>(), "Id", "Code"),
                                        HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Statements", false, Loc.TextBottom, true, new { @multiple = "multiple", @title = Loc.Select }))
                                    @Html.ValidationMessageFor(model => model.Statement, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 document-head-disabled-input" title="@Loc.Total">
                                <div class="form-group text-right">
                                    <label>@Loc.Total</label>
                                    <input type="text" id="TotalAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Price" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount %</label>
                                    <input type="text" id="DiscountPercent" step="@Model.DefaultDecimalPlacesValue" value="" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount</label>
                                    <input type="text" id="DiscountAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Discount" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 document-head-disabled-input" title="@Loc.Value">
                                <div class="form-group text-right">
                                    <label>@Loc.Value</label>
                                    <input type="text" id="Value" value="" step="@Model.DefaultDecimalPlacesValue" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            @if (Model.IsVATObligee)
                            {
                                <div class="col-md-1 col-sm-4 document-head-disabled-input">
                                    <div class="form-group text-right">
                                        <label>@Loc.VAT</label>
                                        <input type="text" id="TaxAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.VAT" class="form-control text-right numberInput" disabled />
                                    </div>
                                </div>
                            }
                            <div class="@(Model.IsVATObligee ? "col-md-2 col-sm-8" : "col-md-3 col-sm-12") document-head-highlight-input">
                                <div class="form-group text-right">
                                    <label>@Loc.ToPay</label>
                                    <div>
                                        <span id="ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span id="Currency">@Model.Currency</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="divided-content-side">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active divided-tab-2"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</a></li>
                                <li class="divided-tab-2">
                                    <a data-toggle="tab" href="#connections" class="local-tab">
                                        @Loc.Connected <span class="badge" id="connectionsCount">
                                            @(Model.OrderConnections != null || Model.AdvancePaymentConnections != null || Model.DocMoveConnections != null ?
                                                (Model.OrderConnections != null ? Model.OrderConnections.Count() : 0) +
                                                (Model.AdvancePaymentConnections != null ? Model.AdvancePaymentConnections.Count() : 0) +
                                                (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0) +
                                                (Model.DocMoveConnections != null ? Model.DocMoveConnections.Count() : 0)
                                                : (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0))
                                        </span>
                                    </a>
                                </li>
                            </ul>
                        </div>

                        <div class="tab-content">
                            <div id="home" class="tab-pane fade in active">
                                <div class="form-horizontal form-md form-right m-t-lg">
                                    <div class="form-group hidden">
                                        @Html.LabelFor(model => model.IssuerAddress, Loc.Address, new { @class = "col-md-3 control-label" })
                                        <div class="col-md-9">
                                            <div class="input-detail-indicator">
                                                @Html.HiddenFor(model => model.IssuerAddress)
                                                <p class="control-label" id="SupplierAddressContainer" title="@Model.IssuerAddress">
                                                    @Model.IssuerAddress
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-12 col-sm-6 col-xs-12">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.ExpectedDeliveryDate, Loc.ExpectedDelivery, new {
                                                    @class = "col-md-4 control-label",
                                                    @title = Loc.Invoice
                                                })
                                                <div class="col-md-8">
                                                    <div class="input-group">
                                                        <span class="input-group-addon">
                                                            <i class="far fa-calendar alt"></i>
                                                        </span>
                                                        @Html.TextBoxFor(model => model.ExpectedDeliveryDate, Model.ExpectedDeliveryDate.HasValue ? Model.ExpectedDeliveryDate.Value.ToString(Loc.DateFormat) : null,
                                                            HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "ExpectedDeliveryDate", false, Loc.ReceivedBillDateShort))
                                                    </div>
                                                    @Html.ValidationMessageFor(model => model.ExpectedDeliveryDate, "", new { @class = "text-danger", @id = "ExpectedDeliveryDate-validation" })
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-12 col-sm-6 col-xs-12">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.Date, Loc.Date, new {
                                                    @class = "col-md-4 control-label",
                                                    @title = Loc.Date
                                                })
                                                <div class="col-md-8">
                                                    <div class="input-group">
                                                        <span class="input-group-addon">
                                                            <i class="far fa-calendar alt"></i>
                                                        </span>
                                                        @Html.TextBoxFor(model => model.Date, Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateFormat) : null,
                                                            HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Date", false, Loc.Date))
                                                    </div>
                                                    @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Department, Loc.Department, new { @class = "col-md-4 control-label",
                                        @title = Loc.Department })
                                        <div class="col-md-8">
                                            <select id="Department" name="Department" class="form-control custom-select">
                                                <option></option>
                                                @foreach (var item in ViewBag.Departments)
                                                {
                                                    <option value="@item.Id" @(Model.Department == item.Id ? "selected" : string.Empty)>
                                                        @item.Name
                                                    </option>
                                                }
                                            </select>
                                            @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger", @id = "Department-validation" })
                                        </div>
                                    </div>

                                    @Html.HiddenFor(model => model.WayOfSale)

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ThirdParty, Loc.Recipient, new { @class = "col-md-4 control-label", @title = Loc.Driver })
                                        <div class="col-md-8">
                                            @Html.HiddenFor(model => model.ThirdPartyId)
                                            @Html.TextBoxFor(model => model.ThirdParty,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide addable-input-btn", "ThirdParty", false, Loc.Recipient, true,
                                                new { dataUrl = Url.Action("SearchPartners", "Wholesale") }))
                                            <div class="addable-button">
                                                <button type="button" title="@Loc.AddingNewPartner"
                                                        id="NewRecipient" class="btn createNewButton" onclick="openSubjectModal('ThirdParty')">
                                                    <i class="fas fa-building"></i>
                                                </button>
                                            </div>
                                            <div class="input-detail-indicator">
                                                @Html.HiddenFor(model => model.ThirdPartyAddress)
                                                <p class="control-label" id="DriverAddressContainer" title="@Model.ThirdPartyAddress">
                                                    @Model.ThirdPartyAddress
                                                </p>
                                            </div>
                                            @Html.ValidationMessageFor(model => model.ThirdPartyId, "", new { @class = "text-danger", @id = "ThirdPartyId-validation" })
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

                                    <div class="form-group doc1Container">
                                        @Html.LabelFor(model => model.Order, Loc.DocumentOne, new
                                        {
                                            @class = "col-md-4 col-sm-12 control-label text-left-sm",
                                            @id = "OrderText"
                                        })
                                        <div class="col-md-4 col-sm-6">
                                            @Html.TextBoxFor(model => model.Order,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Order", false, Loc.DocumentOne))
                                            @Html.ValidationMessageFor(model => model.Order, "", new { @class = "text-danger", @id = "Order-validation" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-lg padding-left-none-md padding-left-none-sm">
                                            <div class="input-group">
                                                <span class="input-group-addon">
                                                    <i class="far fa-calendar alt"></i>
                                                </span>
                                                @Html.TextBoxFor(model => model.OrderDate, Model.OrderDate.HasValue ? Model.OrderDate.Value.ToString("dd.MM.yyyy") : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "OrderDate", false, Loc.DocumentOneDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.OrderDate, "", new { @class = "text-danger", @id = "OrderDate-validation" })
                                        </div>
                                    </div>

                                    <div class="form-group doc2Container">
                                        @Html.LabelFor(model => model.OrderForm, Loc.DocumentTwo, new
                                        {
                                            @class = "col-md-4 col-sm-12 text-left-sm control-label",
                                            @title = Loc.OrderFormNumber,
                                            @id = "OrderFormText"
                                        })
                                        <div class="col-md-4 col-sm-6">
                                            @Html.TextBoxFor(model => model.OrderForm,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "OrderForm", false, Loc.DocumentTwo))
                                            @Html.ValidationMessageFor(model => model.OrderForm, "", new { @class = "text-danger", @id = "OrderForm-validation" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-lg padding-left-none-md padding-left-none-sm">
                                            <div class="input-group">
                                                <span class="input-group-addon">
                                                    <i class="far fa-calendar alt"></i>
                                                </span>
                                                @Html.TextBoxFor(model => model.OrderFormDate, Model.OrderFormDate.HasValue ? Model.OrderFormDate.Value.ToString("dd.MM.yyyy") : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "OrderFormDate", false, Loc.DocumentTwoDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.OrderFormDate, "", new { @class = "text-danger", @id = "OrderFormDate-validation" })
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ClerkId, Loc.ClerkShort, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            @Html.DropDownListFor(model => model.ClerkId,
                                                new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"), Loc.Select,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Clerk", false, Loc.ClerkShort))
                                            @Html.ValidationMessageFor(model => model.ClerkId, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Referent, Loc.Referent, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            @Html.TextBoxFor(model => model.Referent,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Referent", true, Loc.Referent))
                                            @Html.ValidationMessageFor(model => model.Referent, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="connections" class="row tab-pane fade in">
                                @Html.HiddenFor(x => x.CanceledInvoice)
                                @if (Model.CanceledInvoice)
                                {
                                    <div class="form-group">
                                        @if (Model.CanceledLinkAcKey.Count() > 0)
                                        {
                                            for (var x = 0; x < Model.CanceledLinkAcKey.Count(); x++)
                                            {
                                                <h4 class="form-control clickable-icon connectionContainer" id="canceledLinkAcKey" disabled>
                                                    <a class="text-danger" onclick="canceledLink('@Model.CanceledLinkAcKey[x].AcLinkKey')">
                                                        @Model.CanceledLinkAcKeyDisplay[x].AcLinkKeyDisplay
                                                    </a>
                                                    <span class="pull-right text-danger">@Model.CanceledLinkAcKeyDisplay[x].LinkValue.ToString("n2") @Model.Currency</span>
                                                </h4>
                                            }
                                        }
                                        else
                                        {
                                            for (var y = 0; y < Model.CanceledLinkAcKeyLnkDisplay.Count(); y++)
                                            {
                                                <h4 class="form-control clickable-icon connectionContainer" id="canceledLinkAcKeyLnk" disabled>
                                                    <a class="text-danger" onclick="canceledLink('@Model.CanceledLinkAcKeyLnk[y].AcKey')">
                                                        @Model.CanceledLinkAcKeyLnkDisplay[y].AcKeyDisplay
                                                    </a>
                                                    <span class="pull-right text-danger">@Model.CanceledLinkAcKeyLnkDisplay[y].Value.ToString("n2") @Model.Currency</span>
                                                </h4>
                                            }
                                        }
                                    </div>
                                }
                                @if (Model.OrderConnections != null)
                                {
                                    for (var i = 0; i < Model.OrderConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="redirectToOrderDocument('@Model.OrderConnections[i].AcLnkKey', '@Model.OrderConnections[i].OrderType')">
                                                    @Model.OrderConnections[i].AcLnkKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.OrderConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }

                                @if (Model.AdvancePaymentConnections != null)
                                {
                                    for (var i = 0; i < Model.AdvancePaymentConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="redirectToOrderDocument('@Model.AdvancePaymentConnections[i].AcKey', '@TypeOfDoc.AdvancePayment')">
                                                    @Model.AdvancePaymentConnections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.AdvancePaymentConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }

                                @if (Model.DocMoveConnections != null)
                                {
                                    for (var i = 0; i < Model.DocMoveConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a href="@Url.GenerateInvoiceUrl(Model.DocMoveConnections[i].TypeOfDocument, Model.DocMoveConnections[i].AcKey)">
                                                    @Model.DocMoveConnections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.DocMoveConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="modal inmodal fade" id="noteModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="exampleModalLabel"></h4>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="item-note" class="control-label">@Loc.Note:</label>
                                <textarea class="form-control" id="item-note" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="saveNote()" data-dismiss="modal">@Loc.Save</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal inmodal fade modal-scroller" id="subjectModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-xxl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <a class="btn-transparent m-r-xs pull-right" href="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleSubjectsNewInModal)" target="_blank"><i class="fas fa-book-reader"></i></a>
                        <h3 class="text-left container">@Loc.CreateNewSubject</h3>
                    </div>
                    <div class="">
                        @{Html.RenderPartial("~/Views/Subjects/_CreateSubjectFormPartial.cshtml",
                            new SubjectCreateViewModel()
                            {
                                SubjectEditData = new SubjectEditData()
                                {
                                    SelectedCountryId = Model.SelectedCountry,
                                    WayOfSale = Model.DefaultSubjWayOfSale,
                                    WayOfSaleSupplier = Model.DefaultSubjWayOfSaleSupplier,
                                    IsBuyer = false,
                                    IsSupplier = true,
                                },
                                Countries = ViewBag.Countries,
                                ForCountry = PantheonRA.BackOffice.CurrentUser.Localization.ToString()
                            });
                        }
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="saveSubject()"><i class="fa fa-check m-r-xs"></i>@Loc.Add</button>
                        <button type="button" data-dismiss="modal" class="btn btn-link"><i class="fa fa-times m-r-xs text-primary"></i>@Loc.Cancel</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal inmodal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <span id="errorModalMessage"></span>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-dismiss="modal">@Loc.OK</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal inmodal fade" id="invoiceNoteModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="exampleModalLabel"></h4>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="invoice-note" class="control-label">@Loc.Note:</label>
                                <textarea class="form-control" id="invoice-note" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="saveInvoiceNote()" data-dismiss="modal">@Loc.Save</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal inmodal fade" id="paymentMethodWarningModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <span id="paymentMethodWarningModalMessage"></span>
                    </div>
                    <div class="modal-footer">
                        <button type="button" data-dismiss="modal" class="btn btn-primary btn-outline" onclick="resetPaymentMethod()">
                            <i class="fa fa-times m-r-xs"></i>
                            @Loc.Confirm
                        </button>
                    </div>
                </div>
            </div>
        </div>

        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceDeleteModals.cshtml");}
        @{Html.RenderPartial("~/Views/AdvancePayment/_AdvancePaymentCancelModal.cshtml");}
    </div>

    <div id="taxOptions" hidden>
        @foreach (var tax in ViewBag.Taxes)
        {
            <option value="@tax.VATCode" data-vat="@tax.VAT" data-displaytext="@(tax.VATCode + "  " + tax.VAT + "% - " + tax.Name)">
                @tax.VATCode
            </option>
        }
    </div>

    <div id="measUnitOptions" hidden>
        @foreach (var unit in ViewBag.MeasurementUnits)
        {
            <option value="@unit.Id">
                @unit.Id
            </option>
        }
    </div>

    <div id="departmentOptions" hidden>
        <option></option>
        @foreach (var item in ViewBag.Departments)
        {
            <option value="@item.Id">
                @item.Name
            </option>
        }
    </div>
</div>

<div id="IssuedPrintPreview" data-url="@Url.Action("IssuedAdvancePaymentPdf", "AdvancePayment")" style="display:none"></div>
<div id="PrintOrderFormUrl" data-url="@Url.Action("OrderFormPdf", "Wholesale")" style="display:none"></div>
<div id="PaymentMethodRequiredError" data-value="@Loc.PaymentMethodIsRequired" style="display:none"></div>
<div id="LoadingLoc" data-text="@Loc.Loading" style="display:none" />
<div id="RabateValidationError" data-text="@Loc.RabateAmountValidation" style="display:none" />
<input id="DocTextsUrl" value="@Url.Action("GetDocTextsForDocType", "DocumentText")" type="hidden" />
<input id="CreatePriceChangeDoc" value="@Url.Action("CreatePriceChangeDoc", "PriceChange")" type="hidden" />
<input id="EditPriceChange" value="@Url.Action("Edit", "PriceChange")" type="hidden" />
<input type="hidden" id="AjpesUrl" value="@Url.Action("AjpesSearch", "Subjects")" />
<input type="hidden" id="SubjectRewriteDataLoc" value="@Loc.RewriteSubjectData" />
<input type="hidden" id="FixQuantityError" value="@Loc.FixQuantity" />
<input type="hidden" id="YesLoc" value="@Loc.Yes" />
<input type="hidden" id="NoLoc" value="@Loc.No" />
<input type="hidden" id="IdentEditUrl" value="@Url.Action("Edit", "Products")" />
<input type="hidden" id="RepeatAnimation" value="@Url.Content("~/Content/Animations/DocumentLoading.gif")" />
<input type="hidden" id="LoadingDocumentLoc" value="@Loc.LoadingDocument" />
<input type="hidden" id="PAASPrintByAcKeyAndTypeUrl" value="@Url.Action("PAASPrintByAcKeyAndType", "Move")" />
<input type="hidden" id="SearchCostDrvUrl" value="@Url.Action("SearchCostDrv", "CostDrv")" />
<input type="hidden" id="GetCostDrvUrl" value="@Url.Action("GetCostDrv", "CostDrv")" />

@section pageScripts{
    @Scripts.Render("~/bundles/subjects")
    @Scripts.Render("~/bundles/invoiceIdent")
    @Scripts.Render("~/bundles/wizardHelper")

<script type="text/javascript">
        var invoiceItems = [];
        var openStatus = "";
        var paperSize = "";
        var issuerTypeaheadData;

        $(document).ready(function () {
            loadInvoiceItems();
            initializeSubjectsEdit();

            changeSubjectRabate(toNumber('@Model.ReceiverRabate'));

            initializeInvoiceIdentInputs($('#IdentSearch'), PriceType.Wholesale, DiscountType.SellerDiscount, $("#DefaultDecimalPlacesPrice").val(), $("#ReceiverId"), undefined, undefined,
                { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock'});
            openStatus = $("#Status").val();
            setStatements($("#Statements"), $("#Statement").val());

            checkFormEditable();

            $("#invoice, #invoice-for-payment, #identSearchTable").on("numberinput-error", ".numberInput", function () {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.RabateAmountValidation",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            });

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                }).on('changeDate', function () {
                    $(this).datepicker('hide');
                });

            $("#DocTypeSelect").on('change', async function () {
                $("#DocType").val($("#DocTypeSelect").val());

                if (!$("#AcKey").val() && $("#DocTypeSelect option:selected").attr("data-warehouse")) {
                    $("#ReceiverIdSelect").val($("#DocTypeSelect option:selected").attr("data-warehouse"));
                    $("#ReceiverIdSelect").trigger("change");
                }

                if ($("#DocTypeSelect option:selected").attr("data-doc1") === "")
                    $(".doc1Container").prop("hidden", true);
                else {
                    $("#OrderText").text($("#DocTypeSelect option:selected").attr("data-doc1"));
                    $(".doc1Container").prop("hidden", false);
                }

                if ($("#DocTypeSelect option:selected").attr("data-doc2") === "")
                    $(".doc2Container").prop("hidden", true);
                else {
                    $("#OrderFormText").text($("#DocTypeSelect option:selected").attr("data-doc2"));
                    $(".doc2Container").prop("hidden", false);
                }

                if (!$("#AcKey").val()) {
                    getDocTexts($("#DocTextsUrl").val(), $("#Statement"), $("#Statements"), $("#DocType").val());
                    $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
                    $("#Note").val($("#DocTypeSelect option:selected").attr("data-defaultNote"));
                    setNoteIcon();

                    if ($("#DocTypeSelect option:selected").attr("data-department") !== "")
                        $("#Department").val($("#DocTypeSelect option:selected").attr("data-department"));
                    else
                        $("#Department").val($("#UserDepartment").val());
                }

                $("#PaymentMethodId").trigger("change");

                if (!$("#AcKey").val())
                    await setDocTypeStatusOptions($("#DocTypeSelect option:selected").val(), $("#Status"));
            });

            $("#ReceiverIdSelect").on('change', function () {
                $("#ReceiverId").val($("#ReceiverIdSelect").val());
            });

            initializePartnerTypeahead('@Url.Action("SearchSuppliers", "ReceivedBills")', $('#Issuer'), $("#IssuerId"), function (item) {
                issuerTypeaheadData = item;

                if ($("AcKey").val()) {
                    $.get("@Url.Action("CanDelete", "Wholesale")" + "?acKey=" + $("#AcKey").val(), function (response) {
                        canDeleteResponse = response;
                        if (response.HasConnectedCredit == true) {
                            showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
                            cancelDeleteInternalDoc();
                        } else if (response.HasConnectedSummaryDocument == true) {
                            $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                            $("#deleteInternalDocWarningModal").modal('show');
                            $("#continueDeleteInternalDoc").attr("onclick", "changeReceiverData()");
                            $("#cancelDeleteInternalDocument").attr("onclick", "cancelDeleteInternalDoc()");
                        } else {
                            changeIssuerData();
                        }
                    });
                } else
                    changeIssuerData();
            });

            $('#Issuer').focus();

            initializePartnerTypeahead('@Url.Action("SearchSuppliers", "ReceivedBills")', $('#ThirdParty'), $("#ThirdPartyId"), function (item) {
                $("#ThirdPartyAddressContainer").text(item.completeAddress);
                $("#ThirdPartyAddressContainer").prop('title', item.completeAddress);
            });

            $("#Title").on('change', function () {
                $("#TitleText").val($("#Title option:selected").attr("data-description"));
            });


            calculatePriceWithDiscount();
            calculateDiscountPercent();

            $("#DiscountAmount").on('change', function () {
                calculateDiscountPercent();
            });

            $("#DiscountPercent").on('change', function () {
                var percent = toNumber($("#DiscountPercent").val());
                var totalPrice = toNumber($("#TotalAmount").val());

                $("#DiscountAmount").val(totalPrice / 100 * percent);
                updateInvoiceItemsDiscount(percent);
                calculatePriceWithDiscount();
            });

            $("#DocTypeSelect").trigger("change");
            $("#ReceiverIdSelect").trigger("change");

            $("#PaymentMethodId").on('change', function () {
                if ($("#PaymentMethodId option:selected").attr("data-fiscalize") === ""
                    && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")) {

                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "fiscalGroupForPaymentNotValidModal",
                        type: "alert",
                        text: "@Loc.FiscalGroupForPaymentNotValid",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });

                    $("#printButton").attr("disabled", true);
                    $("#printButton + button").prop("disabled", true);
                    return;
                }

                checkPaymentValidation();

                $("#printButton").removeAttr("disabled");
                $("#printButton + button").removeAttr("disabled");
            });

            var addSubjectMousedown = false;
            $("#Issuer, #ThirdParty").blur(function () {
                if (addSubjectMousedown)
                {
                    openSubjectModal(this.id);
                    addSubjectMousedown = false;
                }
                else
                {
                    createNewSubjectModal($("#" + this.id + "Id"), $("#" + this.id), this.id);
                }
            });

            $("#NewPartner, #NewRecipient").mousedown(function () {
                addSubjectMousedown = true;
            });

            $("#errorModal").on('hidden.bs.modal', function () {
                if (focusElement && focusElement.AnNo)
                    $("#quantity-" + focusElement.AnNo).focus();

                focusElement = null;
            });

            $('#paymentMethodWarningModal').on('hidden.bs.modal', function () {
                resetPaymentMethod();
                $("#PaymentMethodId").focus();
            });

            $("#Department").on("change", function () {
                if (invoiceItems && invoiceItems.length > 0)
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.ChangeDepartmentOnAllIdents",
                        buttons: [
                            {
                                icon: 'fa fa-times',
                                text: '@Loc.No',
                                closeOnAction: true,
                                type: 'ghost'
                            },
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.Yes',
                                action: function () {
                                    updateInvoiceItemsDepartment($("#Department option:selected").val());
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            });
        });

        function changeIssuerData() {
            var item = issuerTypeaheadData;
            if ($("#SavedIssuerId").val() === item.value) {
                return;
            }

            $("#SavedIssuerId").val(item.value);
            $("#IssuerAddressContainer").text(item.completeAddress);
            $("#IssuerAddressContainer").prop('title', item.completeAddress);
            $("#WayOfSale").val(item.wayOfSaleSupplier);
            $("#IssuerSuppSaleMet").val(item.paymentMethodIdSupplier);
            if (item.paymentMethodIdSupplier != null && item.paymentMethodIdSupplier != "") {
                $("#PaymentMethodId").val(item.paymentMethodIdSupplier);
            } else {
                $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
            }
            $("#Days").val(item.daysForPaymentSupplier);
            $('#Days').trigger('change');
            changeSubjectRabate(item.rebate);
            $("#add-position").prop("disabled", false);

            var statement = $("#Statement").val();
            if (statement)
                statement += "," + item.statement;
            else
                statement = item.statement;

            $("#Statement").val(statement);
            setStatements($("#Statement"), $("#Statement").val());

            // Set items rabat from subject
            if (invoiceItems.length > 0) {
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "changeIdentRebate",
                    type: "question",
                    text: "@Loc.BuyerChangedChangeIdentRebate",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.No',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Yes',
                            action: function () {
                                for (var i = 0; i < invoiceItems.length; i++) {
                                    invoiceItems[i].Rabate = toNumber(item.rebate);
                                    $("#rabate-" + invoiceItems[i].AnNo).val(toNumber(item.rebate));
                                }
                                updatePriceTable();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }

            // Third party same as receiver
            $("#ThirdPartyId").val(item.value);
            $("#ThirdParty").val(item.value);
            $("#ThirdPartyAddressContainer").text(item.completeAddress);
            $("#ThirdPartyAddressContainer").prop('title', item.completeAddress);

            checkPaymentValidation();
        }

        function calculatePriceWithDiscount() {
            var value = toNumber($("#TotalAmount").val()) - toNumber($("#DiscountAmount").val());
            $("#Value").val(value);

            var toPayAmount = toNumber($("#Value").val()) + toNumber($("#TaxAmount").val());
            $("#ToPayAmount").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), toPayAmount));

            formatNumberInput($("#Value"));
        }

        function calculateDiscountPercent() {
            var discountAmount = toNumber($("#DiscountAmount").val());
            var totalPrice = toNumber($("#TotalAmount").val());

            var percent = 0;
            if (discountAmount && totalPrice > 0)
                var percent = discountAmount / totalPrice * 100;

            $("#DiscountPercent").val(percent);

            updateInvoiceItemsDiscount(percent);
            calculatePriceWithDiscount();
        }

        function updateInvoiceItemsDiscount(percent) {
            for (var i = 0; i < invoiceItems.length; i++) {
                invoiceItems[i].Rabate = percent;
                $("#rabate-" + invoiceItems[i].AnNo).val(percent);
                formatNumberInput($("#rabate-" + invoiceItems[i].AnNo));
            }

            updatePriceTable();
        }

        function onChangeIdentVat(anNo) {
            var priceWithoutDiscount = toNumber($("#totalPrice-" + anNo).val()) / (1 - toNumber($("#rabate-" + anNo).val()) / 100);
            var price = priceWithoutDiscount / toNumber($("#quantity-" + anNo).val()) / (1 + (toNumber($("#vat-" + anNo + " option:selected").attr("data-vat")) / 100));

            $("#price-" + anNo).val(price);
            changeIdentData(anNo);
        }

        function onChangeIdentTotalPrice(anNo) {
            var salePrice = toNumber($("#totalPrice-" + anNo).val());
            let quantity = toNumber($("#quantity-" + anNo).val());
            let ident = invoiceItems[getInvoiceItemIndex(anNo)];

            if ((quantity < 0 && salePrice > 0) || (quantity > 0 && salePrice < 0)) {
                salePrice = salePrice * (-1);
            }

            var priceCurrency = salePrice / (1 + (ident.VAT / 100));
            var price = priceCurrency * 1; // TODO: Exchange rate on the date  or 1

            if (quantity > 0)
                price = price / quantity;

            $("#price-" + anNo).val(price);
            changeIdentData(anNo);
        }

        function appendIdentToTable(data, isNewIdent = false) {
            let newRow = createAdvancePaymentIdentsTableRows($("#invoice"), data, SaleType.NotSale, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#IsVATObligee").val());
            initializeNumberInputs();
            if (isNewIdent) {
                reorderColumns(true, newRow);
            }
        }

        function addPosition(selectedInvoiceItemData) {
            var totalPrice = toNumber($("#SelectedItemQuantity").val()) * toNumber($("#SelectedItemPrice").val());
            var discount = totalPrice / 100 * toNumber($("#SelectedItemRebate").val());
            var vat = (totalPrice - discount) / 100 * selectedInvoiceItemData.vat;

            var excise = calculatePriceWithExcise(selectedInvoiceItemData);

            var dept = selectedInvoiceItemData.department;
            if (!dept || dept === "" && $("#Department option:selected").val())
                dept = $("#Department option:selected").val();

            if (selectedInvoiceItemData != null) {
                var invoiceItem = {
                    AcKey: "",
                    Ident: selectedInvoiceItemData.id,
                    AnNo: invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].AnNo + 1 : 1,
                    Name: selectedInvoiceItemData.name_only,
                    Quantity: selectedInvoiceItemData.quantity,
                    Price: selectedInvoiceItemData.price,
                    PriceCurrency: selectedInvoiceItemData.price,
                    Rabate: selectedInvoiceItemData.rabate,
                    VAT: selectedInvoiceItemData.vat,
                    VATCodeTR: selectedInvoiceItemData.vatCode,
                    VATCode: selectedInvoiceItemData.vatCode,
                    TotalPrice: excise.priceWithExcise,
                    Note: "",
                    MeasurementUnit: selectedInvoiceItemData.measurementUnit,
                    TaxPrice: excise.vat,
                    BasisForTax: totalPrice,
                    PriceForValue: 0,
                    Excise: (excise.priceWithExcise - totalPrice - vat) / selectedInvoiceItemData.quantity,
                    IncBase: selectedInvoiceItemData.incBase,
                    NotIncBase: selectedInvoiceItemData.notIncBase,
                    IncBaseP: selectedInvoiceItemData.incBaseP,
                    NotIncBaseP: selectedInvoiceItemData.notIncBaseP,
                    SalePrice: totalPrice + vat,
                    CostDrv: selectedInvoiceItemData.costDrv ? selectedInvoiceItemData.costDrv : "",
                    Department: dept
                }

                invoiceItems.push(invoiceItem);
                appendIdentToTable(invoiceItem, true);
                updatePriceTable();
                $("#DocTypeSelect").attr("disabled", true);
                $("#DocTypeSelect").closest("div:not(.form-group)").addClass("document-head-disabled-input");
                $("#ReceiverIdSelect").attr("disabled", true);
                onClickSave();
            }
        }

        function swapLoadingIcon(loading, buttonId, icon) {
            var $button = $("#" + buttonId);
            var $buttonIcon = $button.find("i");
            var $buttonGroupButtons = $button.parent().find("button");

            if (loading) {
                $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
                $buttonGroupButtons.attr("disabled", true);
            }
            else {
                $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
                $buttonGroupButtons.removeAttr("disabled");
            }
        }

        function removeIdentFromInvoice(anNo) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "removeIdentAlertModal",
                type: "question",
                text: "@Loc.ConfirmDeleteItemMessage",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: async function () {
                            if ($("#AcKey").val() && $("#AcKey").val() !== "") {
                                $.get("@Url.Action("CanDelete", "Wholesale")" + "?acKey=" + $("#AcKey").val(), function (response) {
                                    canDeleteResponse = response;
                                    if (response.HasConnectedCredit == true) {
                                        showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
                                    } else if (response.HasConnectedSummaryDocument == true) {
                                        $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                                        $("#deleteInternalDocWarningModal").modal('show');
                                        $("#continueDeleteInternalDoc").attr("onclick", "deleteInvoiceItem(" + anNo + ")");
                                        $("#cancelDeleteInternalDocument").attr("onclick", "");
                                    } else {
                                        deleteInvoiceItem(anNo);
                                    }
                                });
                            } else
                                deleteInvoiceItem(anNo);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function deleteInvoiceItem(anNo) {
            invoiceItems.splice(getInvoiceItemIndex(anNo), 1);
            $("#position-" + anNo).remove();
            updatePriceTable();
            if (invoiceItems.length < 1) {
                $("#ReceiverIdSelect").attr("disabled", false);
                $("#sh-dropdown-menu").remove();

                if ((!$("#AcKey").val() || $("#AcKey").val() === ""))
                    $("#DocTypeSelect").attr("disabled", false);
            }
        }

        function changeIdentData(anNo) {
            var rabate = toNumber($("#rabate-" + anNo).val());
            var totalPrice = toNumber($("#quantity-" + anNo).val()) * toNumber($("#price-" + anNo).val());
            var discount = totalPrice / 100 * toNumber(rabate);
            var vat = (totalPrice - discount) / 100 * toNumber($("#vat-" + anNo + " option:selected").attr("data-vat"));

            let item = invoiceItems[getInvoiceItemIndex(anNo)];
            if (!item)
                return;

            item.AcKey = $("#acKey-" + anNo).val();
            item.Quantity = toNumber($("#quantity-" + anNo).val());
            item.Price = toNumber($("#price-" + anNo).val());
            item.PriceCurrency = toNumber($("#price-" + anNo).val());
            item.Rabate = toNumber($("#rabate-" + anNo).val());
            item.Note = $("#note-" + anNo).val();
            item.VAT = toNumber($("#vat-" + anNo + " option:selected").attr("data-vat"));
            item.VATCodeTR = $("#vat-" + anNo + " option:selected").val();
            item.VATCode = $("#vat-" + anNo + " option:selected").val();
            item.Name = $("#name-" + anNo).val();
            item.Ident = $("#id-" + anNo).val();
            item.MeasurementUnit = $("#measurementUnit-" + anNo + " option:selected").val();
            item.TaxPrice = toNumber(vat);
            item.PriceForValue = toNumber($("#priceForValue-" + anNo).val());
            item.BasisForTax = toNumber(totalPrice);
            item.CostDrv = $("#costDrv-" + anNo).val();
            item.Department = $("#department-" + anNo).val();

            var excise = calculatePriceWithExcise({
                quantity: item.Quantity,
                price: item.Price,
                rabate: item.Rabate,
                vat: item.VAT,
                incBase: item.IncBase,
                notIncBase: item.NotIncBase,
                incBaseP: item.IncBaseP,
                notIncBaseP: item.NotIncBaseP
            });

            item.TaxPrice = excise.vatDiscount;
            item.TotalPrice = excise.priceWithExcise;
            item.SalePrice = totalPrice;

            $("#totalPrice-" + anNo).val(item.TotalPrice);
            $("#basisForTax-" + anNo).val(totalPrice);
            $("#taxPrice-" + anNo).val(item.TaxPrice);
            initializeNumberInputs();

            updatePriceTable();
        }

        function getInvoiceItemIndex(anNo) {
            for (var i = 0; i < invoiceItems.length; i++) {
                if (invoiceItems[i].AnNo === anNo) {
                    return invoiceItems.indexOf(invoiceItems[i]);
                }
            }
        }

        var selectedItemAnNo = '';
        function openNoteModal(anNo) {
            selectedItemAnNo = anNo;
            $("#item-note").val($("#note-" + anNo).val());
            $("#noteModal").modal('show');
        }

        function saveNote() {
            $("#note-" + selectedItemAnNo).val($("#item-note").val());

            $("#noteModal-" + selectedItemAnNo)
                .removeClass("btn-link btn-active")
                .addClass($("#note" + selectedItemAnNo).val() !== "" ? "btn-link btn-active" : "btn-link");

            changeIdentData(selectedItemAnNo);
        }

        function updatePriceTable() {
            var fullTotalPrice = 0;
            var totalPrice = 0;
            var discountSum = 0;
            var taxAmount = 0;
            var excise = 0;

            for (var i = 0; i < invoiceItems.length; i++) {
                var price = invoiceItems[i].Price.toString();
                if (price) {
                    toNumber(price);
                }

                totalPrice += invoiceItems[i].PriceCurrency * invoiceItems[i].Quantity;
                fullTotalPrice += toNumber($("#totalPrice-" + invoiceItems[i].AnNo).val());
                taxAmount += toNumber($("#taxPrice-" + invoiceItems[i].AnNo).val());
                var discount = ((invoiceItems[i].Price * invoiceItems[i].Rabate) / 100) * invoiceItems[i].Quantity;
                discountSum = discountSum + discount;
                excise += invoiceItems[i].Excise;
            }
            var toPayAmount = formatDisplay($("#DefaultDecimalPlacesValue").val(), fullTotalPrice);

            var discountPercent = 0;
            if (totalPrice) {
                var discountOnePercentPrice = totalPrice / 100;
                discountPercent = discountSum / discountOnePercentPrice;
            }

            $("#TotalAmount").val(isNaN(totalPrice) ? 0 : totalPrice);
            $("#DiscountAmount").val(isNaN(discountSum) ? 0 : discountSum);
            $("#TaxAmount").val(isNaN(taxAmount) ? 0 : taxAmount);
            $("#ToPayAmount").text(toPayAmount);
            $("#DiscountPercent").val(isNaN(discountPercent) ? 0 : discountPercent);

            formatNumberInput($("#TotalAmount"));
            formatNumberInput($("#DiscountAmount"));
            formatNumberInput($("#TaxAmount"));
            formatNumberInput($("#ToPayAmount"));
            formatNumberInput($("#DiscountPercent"));

            calculatePriceWithDiscount();
        }

        onClickSave = function (option, printType = null) {
            if (openStatus === '@WholesaleStatus.Confirmed') {
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "confirmedDocumentAlertModal",
                    type: "question",
                    text: "@Loc.DocumentIsAlreadyConfirmed",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.No',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Yes',
                            action: async function () {
                                save(option, printType);
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
            else
                save(option, printType);
        }

        var printWindow;
        function save(option, printType = null) {
            if ($('input.numberInput.error-input-item')[0]) return;

            swapLoadingIcon(true, "saveButton", "fa fa-save");
            swapLoadingIcon(true, "printButton", "far fa-print");

            $("#Statement").val($("#Statements").val() ? $("#Statements").val().toString() : "");

            var formData = $("#AdvancePaymentForm").serializeArray();
            formData.push({ name: 'InvoiceItemsJsonString', value: JSON.stringify(invoiceItems) });

            formData = changeFormDataValue(formData, 'Note', encodeURIComponent($("#Note").val()));

            var url;
            if ($("#AcKey").val()) {
                url = '@Url.Action("Edit", "AdvancePayment")';
            } else {
                url = '@Url.Action("Create", "AdvancePayment")';
            }

            if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
                printWindow = createPrintWindow(printWindow);
            }

            $.post(url, formData)
                .done(function (response) {
                    if (response.Success) {
                        if (!$("#AcKey").val()) {
                            setInvoiceCreatedData(response);
                        }

                        openStatus = $("#Status option:selected").val();
                        displayErrors(response);

                        if (response.data && response.data.AcKey) {
                            $("#AcKey").val(response.data.AcKey);
                        }

                        let errorText = '';
                        if (response.errors) {
                            response.errors.forEach(function (errorItem) {
                                errorText += errorItem;
                            });
                        }

                        if (response.ignoreError) {
                            $().customModal({
                                title: "",
                                destroyOnClose: true,
                                showCloseButton: true,
                                id: "ingoreErrorAlertModal",
                                type: "alert",
                                text: errorText,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: '@Loc.OK',
                                        action: async function () {
                                            handleSaveOption(option, printType);
                                        },
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        } else if (errorText !== '') {
                            $("#errorModalMessage").text(errorText);
                            $("#errorModal").modal('show');

                            if (printWindow) {
                                printWindow.close();
                            }
                        } else {
                            handleSaveOption(option, printType);
                        }
                    } else {
                        if (printWindow) {
                            printWindow.close();
                        }

                        if (response.data && response.data.AcKey && !$("#AcKey").val()) {
                            setInvoiceCreatedData(response);
                        }

                        clearValidationErrors();
                        displayErrors(response);

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }
                    swapLoadingIcon(false, "saveButton", "fa fa-save");
                    swapLoadingIcon(false, "printButton", "far fa-print");
                });
        }

        function handleSaveOption(option, printType) {
            var apType = $("#AdvancePaymentType").val();

            if (option === '@InvoiceSaveType.SaveAndPrint') {
                printPAAS(printType, false, option === '@InvoiceSaveType.SaveAndPreview');
            } else if (option === '@InvoiceSaveType.SaveAndNew') {
                window.location.href = '@Url.Action("CreateIssuedAdvancePayment", "ReceivedBills")';
            } else if (option === '@InvoiceSaveType.SaveAndClose') {
                window.location.href = '@Url.Action("IssuedAdvancePayments", "ReceivedBills")';
            } else {
                setIdentsPriceForValue();
            }
        }

        function setIdentsPriceForValue() {
            if (!$("#AcKey").val())
                return;

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                for (var i = 0; i < data.length; i++) {
                    $("#totalPrice-" + data[i].AnNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].TotalPriceForReceivedItem));
                }

                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }, "json");
        }

        function setInvoiceCreatedData(response) {
            $("#AcKey").val(response.data.AcKey);
            refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
            $("#Reference").val(response.data.Reference);
            $("#OrderForm").val(response.data.OrderForm);
            $("#invoiceDelete").removeClass("hidden");
            $("#cancelInvoice").removeClass("hidden");
            $("#newInvoiceButton").removeClass("hidden");
            $("#Referent").val(response.data.Referent);
            $("#DocTypeSelect").attr("disabled", true);
            window.history.pushState({}, null, '@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=' + response.data.AcKey);
            clearValidationErrors();
            $(".preview-btn").closest("li").removeClass("hidden");
            $("#additionalFuncButton").removeClass("hidden");
            $("#additionalFuncButton + button").removeClass("hidden");
            $("#wizardButton").prop("disabled", false);
            $("#wizardButton + button").prop("disabled", false);
        }

        function loadInvoiceItems() {
            if (!$("#AcKey").val())
                return;

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                for (var i = 0; i < data.length; i++) {
                    data[i].SalePrice = data[i].TotalPriceForReceivedItem;
                    data[i].TaxPrice = data[i].TaxPrice + data[i].Excise;
                    invoiceItems.push(data[i]);
                    appendIdentToTable(data[i]);
                }

                if (data.length > 0) {
                    $("#ReceiverIdSelect").attr("disabled", true);
                    displayShowHideDropdown();
                }

                updatePriceTable();
                checkFormEditable();
                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }, "json");
        }

        var subjectType;
        function openSubjectModal(subject) {
            subjectType = subject;
            var id = $("#" + subject).val();
            setSearchSubjectData(id);
            $("#subjectModal").modal('show');
        }

        function saveSubject() {
            var formData = $("#subjectForm").serializeArray();

            $.post('@Url.Action("CreateFromPartial", "Subjects")', formData)
                .done(function (response) {
                    if (response.Success) {
                        $("#" + subjectType + "Id").val(response.subject.Id);
                        $("#" + subjectType).val(response.subject.Id);
                        var receiverAddress = response.subject.Address + (!response.subject.ZipCode ? "" : ", " + response.subject.ZipCode) + (!response.subject.VAT ? "" : ", " + response.subject.VAT);
                        $("#" + subjectType + "AddressContainer").text(receiverAddress);

                        clearValidationErrors();
                        $("#subjectModal").modal('hide');
                    }
                    else {
                        clearValidationErrors();

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }
                });
        }

        function deleteInvoice() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "deleteWholesaleDocumentModal",
                type: "question",
                text: '@Loc.DeleteInvoiceDocument',
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.Cancel',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        action: function () {
                            canDelete();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function checkFormEditable() {
            if ($("#IsTaxPeriodLocked").val() === "True") {
                $("#AdvancePaymentForm :input").prop("disabled", true);
                $("#AdvancePaymentForm :input").closest("div:not(.form-group)").addClass("document-head-disabled-input");
                $("#invoiceDelete").prop("disabled", true);
                $("#printButton").prop("disabled", false);
                $("#printButton + button").prop("disabled", false);
                $("#copyButton").prop("disabled", false);
                $("#wizardButton").prop("disabled", false);
                $("#wizardButton + button").prop("disabled", false);
                $("#additionalFuncButton").prop("disabled", false);
                $("#additionalFuncButton + button").prop("disabled", false);

                var inputs = document.getElementsByClassName("form-control numberInput");
                for (var i = 0; i < inputs.length; i++) {
                    if (!$("#" + inputs[i].id).hasClass("dont-disable")) {
                        inputs[i].disabled = true;
                        $("#" + inputs[i].id).closest("div:not(.form-group)").addClass("document-head-disabled-input");
                    }
                }
            }

            if ($("#AcKey").val()) {
                $("#printButton").attr("disabled", false);
                $("#printButton + button").prop("disabled", false);
            }

            if ($("#AcKey").val() && $("#CanceledInvoice").val() === "True") {
                var numberInputs = Array.from(document.getElementsByClassName("form-control numberInput"));
                var editableInputs = Array.from(document.getElementsByClassName("form-control element-editable"));
                numberInputs.push(...editableInputs);

                for (var i = 0; i < numberInputs.length; i++) {
                    if (!$("#" + numberInputs[i].id).hasClass("dont-disable")) {
                        numberInputs[i].disabled = true;
                        $("#" + numberInputs[i].id).closest("div:not(.form-group)").addClass("document-head-disabled-input");
                    }
                }
            }
        }

        function enableForm() {
            $("#AdvancePaymentForm :input").prop("disabled", false);
            $("#invoiceDelete").prop("disabled", false);
            $("#printButton").prop("disabled", false);
            $("#printButton + button").prop("disabled", false);
            $("#copyButton").prop("disabled", false);

            var inputs = document.getElementsByClassName("form-control numberInput");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].disabled = false;
            }
        }

        function cancelInvoice() {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "cancelDocumentAlertModal",
                type: "question",
                text: "@Loc.CancelInvoiceConfirm",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: async function () {
                            location.href = '@Url.Action("Cancel", "Wholesale")?acKey=' + $("#AcKey").val();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function canceledLink(ackey) {
            location.href = '@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=' + ackey;
        }

        function openInvoiceNoteModal() {
            $("#invoiceNoteModal textarea").val($("#Note").val());
            $("#invoiceNoteModal").modal("show");
        }

        function saveInvoiceNote() {
            $("#invoiceNoteModal").modal("hide");
            $("#Note").val($("#invoiceNoteModal textarea").val());

            setNoteIcon();
        }

        function checkPaymentValidation() {
            if (!$("#ReceiverId").val())
                return;

            var payMethodFiscGroup = $("#PaymentMethodId option:selected").attr("data-fiscalize");

            if (payMethodFiscGroup === "@PaymentType.Cash") {
                $.get("@Url.Action("CheckDocTypePayment", "Wholesale")" + "?docType=" + $("#DocType").val(), function (data) {
                    if (data) {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "alert",
                            text: "@Loc.DocTypeNoFiscPaymentMethodCashError",
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    action: function () {
                                        resetPaymentMethod();
                                    },
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }
                });
            }
        }

        function resetPaymentMethod() {
            $("#PaymentMethodId").val("");
        }

                var canDeleteResponse;
        function canDelete() {
            $.get("@Url.Action("CanDelete", "Wholesale")" + "?acKey=" + $("#AcKey").val(), function (response) {
                canDeleteResponse = response;

                if (response.ShowError == true) {
                    if (response.HasConnectedCredit == true) {
                        showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
                    } else if (response.HasCashExpenditureOrTransfer == true) {
                        $("#deleteWarningMessage").text(stringFormat("@Loc.AssociatedCashExpenditureOrTransfer", $("#AcKey").val()));
                        $("#deleteWarningModal").modal("show");
                    } else if (response.IsLastDoc == false) {
                        showDeleteNotLastDocModal();
                    } else if (response.HasConnectedSummaryDocument == true) {
                        $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                        $("#deleteInternalDocWarningModal").modal('show');
                        $("#continueDeleteInternalDoc").attr("onclick", "deleteWithInternalDoc()");
                        $("#cancelDeleteInternalDocument").attr("onclick", "");
                    }
                } else
                    removeIssuedAdvPay();
            });
        }

        function removeIssuedAdvPay() {
            $.get("@Url.Action("Remove", "ReceivedBills")" + "?acKey=" + $("#AcKey").val(), function (response) {
                if (response.Error) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: response.Error,
                        onClose: function () { onClickSave() },
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
                else
                    location.href = "@Url.Action("IssuedAdvancePayments", "ReceivedBills")";
            });
        }

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

        function continueDelete() {
            if (canDeleteResponse && canDeleteResponse.HasConnectedCredit != true) {
                if (canDeleteResponse.IsLastDoc == false) {
                    $("#deleteNotLastDocModal").modal('show');
                } else if (canDeleteResponse.HasConnectedSummaryDocument == true) {
                    $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                    $("#deleteInternalDocWarningModal").modal('show');
                    $("#continueDeleteInternalDoc").attr("onclick", "deleteWithInternalDoc()");
                    $("#cancelDeleteInternalDocument").attr("onclick", "");
                } else
                    removeIssuedAdvPay();
            } else {
                showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
            }
        }

        function deleteNotLastDoc() {
            if (canDeleteResponse.HasConnectedSummaryDocument == true) {
                $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", canDeleteResponse.AcKey));
                $("#deleteInternalDocWarningModal").modal('show');
                $("#continueDeleteInternalDoc").attr("onclick", "deleteWithInternalDoc()");
                $("#cancelDeleteInternalDocument").attr("onclick", "");
            } else
                removeIssuedAdvPay();
        }

        function deleteWithInternalDoc() {
            removeIssuedAdvPay();
        }

        function cancelDeleteInternalDoc() {
            $("#SupplierId").val($("#ValidSupplierId").val());
            $("#Supplier").val($("#ValidSupplierId").val());
        }

        function showPaymentMethodRequiredModal() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "paymentMethodRequiredModal",
                type: "alert",
                text: "@Loc.PaymentMethodIsRequired",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function redirectToOrderDocument(acKey, orderType) {
            if (acKey && orderType === "@OrderType.Buyer.ToString()")
                window.location = "@Url.Action("EditBuyerOrder", "Order")" + "?id=" + acKey;
            else if (acKey && orderType === "@OrderType.Supplier")
                window.location = "@Url.Action("EditSupplierOrder", "Order")" + "?id=" + acKey;
            else if (acKey && orderType === "@TypeOfDoc.AdvancePayment")
                window.location = "@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")" + "?id=" + acKey;
        }
</script>
}
