@using PantheonRA.BackOffice.Models
@using PantheonRA.WebApi.Contracts.Enums
@using PantheonRA.BackOffice.Enums
@using PAW.Contracts.Enums
@model WholesaleCreateFormData

@{
    ViewBag.Title = Loc.Invoicing;
    var isInFiscalPrinterLocalization = Localization.IsInFiscalPrinterLocalization(PantheonRA.BackOffice.CurrentUser.DatabaseLocalization, PantheonRA.BackOffice.CurrentUser.IsInServerFiscalization);
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_WholesalesTabNavigation")
        <div class="tab-content">
            <form method="post" id="WholesaleForm" enctype="multipart/form-data" class="custom-dirty-checker">
                @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.IsObligDept)
                @Html.HiddenFor(model => model.UserDepartment)
                @Html.HiddenFor(model => model.RoundTSetting)
                @Html.HiddenFor(model => model.RoundValueSetting)
                @Html.HiddenFor(model => model.RoundT)
                @Html.HiddenFor(model => model.RoundValue)
                @Html.HiddenFor(model => model.RoundPrice)
                @Html.HiddenFor(model => model.RoundTfc)
                @Html.HiddenFor(model => model.RoundValueOc)
                @Html.HiddenFor(model => model.VatBase)
                @Html.HiddenFor(model => model.CurrencyFxRateType)
                @Html.HiddenFor(model => model.CompanyCurrency)
                @Html.HiddenFor(model => model.AdvancePaymentMsgType)
                @Html.HiddenFor(model => model.FillDeptFromCostDrv)
                @Html.HiddenFor(model => model.FilterDeptForCostDrv)
                @Html.Hidden("IsObligCostDrv", false)
                @Html.HiddenFor(model => model.FxRateCalcOperation)
                @Html.HiddenFor(model => model.MoveNonMatOpenDate)
                @Html.HiddenFor(model => model.DocumentTabActive)
                @Html.Hidden("DefaultReport", string.Empty)
                @Html.HiddenFor(model => model.OurCompIsName2)
                @Html.HiddenFor(model => model.FillRefFromSubj)
                @Html.HiddenFor(model => model.FillDeptFromPersonResp)
                @Html.HiddenFor(model => model.Qid)
                @Html.HiddenFor(model => model.CalcInvoOutFallDue)
                @Html.HiddenFor(model => model.FiscalizeTip)
                @Html.Hidden("DocTypeTipFiscalization", string.Empty)
                @Html.Hidden("MoveType", AuthorType.Wholesale)

                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
               {
                   ShowCloseBtn = false,
                   BackUrl = Url.Action("Index", "Wholesale"),
                   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.Wholesale,
                   PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                            Model.ReportTreeViewModel,
                            "onClickSave('" + InvoiceSaveType.SaveAndPrint + "', '{0}', '{1}', {2})",
                            "onClickSave('" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                        ),
                   IsWizardDisabled = string.IsNullOrEmpty(Model.AcKey) ? true : false,
                   IsWizardVisible = true,
                   WizardButtonGroup = new FormButtonGroup
                   {
                       Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.AdvancePayments, Icon = "", OnClick = "moveAdvancePaymentLinks()" },
                                new FormButton { Text = Loc.CancelInvoice, Icon = "", OnClick = "openPartialCancelInvoice()" },
                                new FormButton { Text = Loc.CreateCommission, Icon = "", OnClick = "onCreateCommission()" },
                                new FormButton { Text = Loc.CreateCashRegReceipt, Icon = "", OnClick = "beforeShowCashRegPayments()" },
                                new FormButton { Text = Loc.CreatePriceChange, Icon = "", OnClick = "onCreatePriceChange()", 
                                    HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR && PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS && PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.BA },
                                new FormButton { Text = Loc.ConnectDocumentWizard, Icon = "", OnClick = "startConnectDocWizardModal()" },
                                new FormButton { Text = Loc.FiscalizeUnconfirmedDocument, Icon = "", OnClick = "openUnconfirmedBills()", IsHidden = PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS },
                                new FormButton { Text = Loc.CorrectFiscalInvoice, Icon = "", OnClick = "openInvoiceErrorCorrectiveModal()", HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.ME },
                                new FormButton { Text = Loc.CEInvoice, Icon = "", OnClick = "openCEInvoiceModal()", HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                new FormButton { Text = Loc.TipFiscalization, Icon = "", OnClick = "openMoveTipFiscalizationModal(" + Model.Qid + ")", HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR && Model.FiscalizeTip != true },
                                //new FormButton { Text = Loc.MovePosting, Icon = "", OnClick = "movePosting('" + Model.AcKey + "')" }
                            }
                   }
               })

                    <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>

                    <button id="invoiceDuplicate" type="button" onclick="duplicateInvoice()" title="@Loc.DuplicateRecord"
                            class="btn btn-primary btn-outline pull-right collapsable-form-button @(string.IsNullOrEmpty(Model.AcKey) ? " hidden" : string.Empty)">
                        <i class="fa fa-files-o m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.Duplicate</span>
                    </button>

                    <a title="@Loc.New" id="newInvoiceButton" onclick="createNewInvoice('@Url.Action("Create", "Wholesale")', '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-up"><span class="placeholder-text">@Loc.WholesalePlaceholder</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, new { @class = "custom-dirty-checker-ignore" })
                                    @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-fiscAll="@item.FiscAll"
                                                    data-warehouse="@item.Warehouse"
                                                    data-payMethod="@item.PayMethod"
                                                    data-defaultNote="@item.DefaultNote"
                                                    data-doc1="@item.Doc1"
                                                    data-doc2="@item.Doc2"
                                                    data-department="@item.Department"
                                                    data-isObligDept="@item.ISObligDept"
                                                    data-isInternal="@item.IsInternal"
                                                    data-isObligCostDrv="@item.IsObligCostDrv"
                                                    data-allowZeroTotal="@item.AllowZeroTotal"
                                                    data-checkPosPriceQty="@item.CheckPositionPriceQty"
                                                    data-isInitialized="@item.IsInitialized"
                                                    data-fiscalWorkplaceId="@item.FiscalWorkplaceId"
                                                    data-cashReg="@item.DocTypeCashReg"
                                                    data-docTypeCancel="@item.DocTypeCancel"
                                                    data-pinUrlLPFR="@item.PinUrlLPFR"
                                                    data-attentionUrlPfr="@item.AttentionUrlPFR"
                                                    data-fiscTraining="@item.FiscTraining"
                                                    data-typeOfDoc="@item.TypeOfDoc"
                                                    data-docTypeDms="@item.DocTypeDms"
                                                    data-classification="@item.Classification"
                                                    data-eInvoiceExportType2="@item.EInvoiceExportType2"
                                                    data-checkIdentDpl="@item.CheckIdentDpl"
                                                    data-roundT="@item.RoundT"
                                                    data-roundValue="@item.RoundValue"
                                                    data-roundPrice="@item.RoundPrice"
                                                    data-roundTfc="@item.RoundTfc"
                                                    data-roundValueOc="@item.RoundValueOc"
                                                    data-autoInvoSerialNo="@item.AutoInvoSerialNo"
                                                    data-docTypeTipFiscalization="@item.DocTypeTipFiscalization"
                                                    data-displayProtocol="@item.DisplayProtocol"
                                                    data-receiver="@item.Receiver"
                                                    @(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">
                                    <input id="SavedReceiverId" value="@Model.ReceiverId" hidden />
                                    @Html.LabelFor(model => model.Receiver, Loc.Buyer + " / " + Loc.Payer, new { @class = "control-label", @title = Loc.Buyer + " / " + Loc.Payer })
                                    @Html.ValidationMessageFor(model => model.ReceiverId, "", new { @class = "text-danger m-l-xs", @id = "ReceiverId-validation" })
                                    @Html.HiddenFor(model => model.ReceiverId)
                                    @Html.HiddenFor(model => model.ReceiverName)
                                    <input id="ReceiverSuppSaleMet" hidden />
                                    <input id="ReceiverPriceRate" hidden />
                                    <input id="ReceiverRebate" hidden />
                                    @Html.TextBoxFor(model => model.Receiver,
                                    HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_large addable-input", "Receiver", false, Loc.Buyer + " / " + Loc.Payer, true, new { @title = Model.Receiver }))
                                    <div class="addable-button">
                                        <button type="button" title="@Loc.AddingNewPartner"
                                                id="NewPartner" class="btn createNewButton" onclick="openSubjectModal('Receiver')">
                                            <i class="fas fa-building"></i>
                                        </button>
                                    </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" title="@Model.PaymentMethod">
                                        <option></option>
                                        @foreach (var item in ViewBag.PaymentTypes)
                                        {
                                            <option value="@item.PaymentMethod"
                                                    data-setOf="@item.SetOf"
                                                    data-fiscalize="@(PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.ME ? item.FiscalGroupMn : 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, true, new { @title = Model.StatusDisplay }))
                                    @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)
                                    @Html.HiddenFor(model => model.AcKeyDisplay)
                                    <h4 class="control-label" id="AcKeyDisplayContainer">
                                        @{
                                            Html.RenderPartial("~/Views/Shared/Components/_PrevNextKeyDisplay.cshtml",
                                            new PrevNextKeyDisplayViewModel
                                            {
                                                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("Edit", "Wholesale", 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("Edit", "Wholesale", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action("Index", "Wholesale", new { acKey = Model.AcKey, date = Model.Date.Value.ToString("o") })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>

                        <div id="wholesaleFormDocumentBody" class="document-body table-has-fiscal-data">
                            <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,
                                        Author = AuthorType.Wholesale
                                    })
                                </div>
                            </div>

                            @Html.Partial("_InvoiceIdentsTable", new IdentsTableViewModel
                            {
                            IsVATObligee = Model.IsVATObligee,
                            Author = AuthorType.Wholesale,
                            TableGridName = "wholesale-invoice-idents"
                            })
                        </div>

                        <div class="row fiscalizeData">
                            <div class="col-xs-12">
                                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS)
                                {
                                    <div class="addable-button">
                                        @Html.HiddenFor(model => model.FiscalNumber)
                                        @Html.HiddenFor(model => model.FiscalCode)
                                        <label>@Loc.SDCShort:</label> <span>@Model.FiscalCode</span>
                                    </div>
                                }
                                else
                                {
                                    <div class="addable-button">
                                        @Html.HiddenFor(model => model.FiscalNumber)
                                        <label>@Loc.FiscalNumberShort:</label> <span>@Model.FiscalNumber</span>
                                    </div>
                                    <div class="addable-button">
                                        @Html.HiddenFor(model => model.FiscalCode)
                                        <label>@Loc.FiscalizationCodeShort:</label> <span>@Model.FiscalCode</span>
                                    </div>
                                }
                            </div>
                        </div>

                        <div class="row document-footer">
                            <div class="col-md-1 col-sm-6">
                                <div class="form-group text-center text-left-xs @(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-3 col-sm-6" id="statementsContainer">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Statement, Loc.TextMessage, 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.TextMessage, 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-6 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" data-round="@Model.RoundValue" value="@Model.Price" class="form-control text-right numberInput roundValue" disabled />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-6">
                                <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-6">
                                <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-6 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" data-round="@Model.RoundValue" class="form-control text-right numberInput roundValue" disabled />
                                </div>
                            </div>
                            @if (Model.IsVATObligee)
                            {
                                <div class="col-md-1 col-sm-6 document-head-disabled-input">
                                    <div class="form-group text-right">
                                        <label>@Loc.VAT</label>
                                        <input type="text" id="TaxAmount" step="@Model.DefaultDecimalPlacesValue" data-round="@Model.RoundValue" value="@Model.VAT" class="form-control text-right numberInput roundValue" disabled />
                                    </div>
                                </div>
                            }
                            <div class="col-md-1 col-sm-6 document-head-disabled-input padding-left-none" id="forPay76aContainer" hidden>
                                <div class="form-group text-right">
                                    <label title="@Loc.Article76a">@Loc.Article76a</label>
                                    <input type="text" id="ForPay76a" step="@Model.DefaultDecimalPlacesValue" value="" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="@(Model.IsVATObligee ? " col-md-3 col-sm-6" : "col-md-4  col-sm-12" ) document-head-highlight-input" id="toPayContainer">
                                <div class="form-group text-right">
                                    <label>@Loc.ToPay</label>
                                    <div>
                                        <span id="ToPayAmount" class="ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span id="ToPayCurrency" class="ToPayCurrency">@Model.Currency</span>
                                    </div>
                                </div>
                            </div>
                            <div class="@(Model.IsVATObligee ? " col-md-3 col-sm-6" : "col-md-4  col-sm-12" ) document-head-highlight-input" id="toPayNewCurrencyContainer" hidden>
                                <div class="row">
                                    <div class="col-md-5">
                                        <div class="form-group">
                                            <label>@Loc.ToPay</label>
                                        </div>
                                    </div>
                                    <div class="col-md-7 text-right padding-left-none">
                                        <span class="font-sm ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span id="ToPayCurrency" class="font-sm ToPayCurrency">@Model.Currency</span>
                                    </div>
                                    <div class="col-md-offset-5 col-md-7 text-right padding-left-none line-height-18">
                                        <span id="ToPayAmountOurCurrency" class="font-sm">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span class="font-sm">@Model.CompanyCurrency</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-3"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</a></li>
                                <li class="divided-tab-3">
                                    <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.LinkedDocuments != null ?
                                                (Model.OrderConnections != null ? Model.OrderConnections.Count() : 0) +
                                                (Model.LinkedDocuments != null ? Model.LinkedDocuments.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>
                                <li class="divided-tab-3">
                                    <a data-toggle="tab" href="#documents" class="local-tab">
                                        @Loc.Documents <span class="badge" id="documentsCount">@(Model.Files == null ? 0 : Model.Files.Count)</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">
                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.BG)
                                    {
                                        <div class="form-group protocolContainer">
                                            @Html.LabelFor(model => model.Protocol, Loc.ProtocolNumber, new { @class = "col-md-4 control-label" })
                                            <div class="col-md-8">
                                                @Html.TextBoxFor(model => model.Protocol,
                                             HtmlAttributesHelper.CreateInputAttributes("form-control", "Protocol", false, Loc.ProtocolNumber))
                                                @Html.ValidationMessageFor(model => model.Protocol, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                    }
                                    <div class="form-group hidden">
                                        @Html.LabelFor(model => model.ReceiverAddress, Loc.Address, new { @class = "col-md-3 control-label" })
                                        <div class="col-md-9">
                                            <div class="input-detail-indicator">
                                                @Html.HiddenFor(model => model.ReceiverAddress)
                                                <p class="control-label" id="SupplierAddressContainer" title="@Model.ReceiverAddress">
                                                    @Model.ReceiverAddress
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-12 col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.Date, Loc.OrderFormDate, new
                                                {
                                                @class = "col-md-4 control-label",
                                                @title = Loc.TakeoverDate
                                                })
                                                <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.TakeoverDate))
                                                    </div>
                                                    @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                                </div>
                                            </div>
                                        </div>


                                        <div class="col-md-12 col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.InvoiceDate, Loc.BillDate, 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.InvoiceDate, Model.InvoiceDate.HasValue ? Model.InvoiceDate.Value.ToString(Loc.DateFormat) : null,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "InvoiceDate", false, Loc.ReceivedBillDateShort))
                                                    </div>
                                                    @Html.ValidationMessageFor(model => model.InvoiceDate, "", new { @class = "text-danger", @id = "InvoiceDate-validation" })
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-12 col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.TaxDate, Loc.VATDate, new { @class = "col-md-4 control-label" })
                                                <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.TaxDate, Model.TaxDate.HasValue ? Model.TaxDate.Value.ToString(Loc.DateFormat) : null,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "TaxDate", false, Loc.VATDate))
                                                    </div>
                                                    @Html.ValidationMessageFor(model => model.TaxDate, "", new { @class = "text-danger", @id = "TaxDate-validation" })
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.DateDue, Loc.DateDue, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                        <div class="col-md-4 col-sm-6">
                                            <div class="input-group">
                                                @Html.TextBoxFor(model => model.DateDueDays,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "DateDueDays", false, Loc.NumOfDays))
                                                <span class="input-group-addon">@Loc.Days.ToLower()</span>
                                            </div>
                                            @Html.ValidationMessageFor(model => model.DateDueDays, "", new { @class = "text-danger" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                            <div class="input-group">
                                                <span class="input-group-addon">
                                                    <i class="far fa-calendar alt"></i>
                                                </span>
                                                @Html.TextBoxFor(model => model.DateDue, Model.DateDue.HasValue ? Model.DateDue.Value.ToString(Loc.DateFormat) : null,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DateDue", false, Loc.DateDue))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.DateDue, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.RefCode, Loc.Reference, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                        <div class="col-md-4 col-sm-6">
                                            @Html.DropDownListFor(model => model.RefCode, new SelectList(ViewBag.ReferenceCodes != null ? ViewBag.ReferenceCodes : new List<string>
                                                (), "Id", "Name", "99"),
                                                HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "RefCode", false, Loc.Reference, true))
                                            @Html.ValidationMessageFor(model => model.RefCode, "", new { @class = "text-danger" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                            @Html.TextBoxFor(model => model.RefNumber,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control", "RefNumber", false, Loc.Reference))
                                            @Html.ValidationMessageFor(model => model.RefNumber, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Currency, Loc.CurrencyAndRate, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-4">
                                            <input id="OldCurrency" value="@Model.Currency" hidden />
                                            @Html.DropDownListFor(model => model.Currency, new SelectList(ViewBag.CurrencyTypes, "Value", "Text", "EUR"), Loc.CurrencyAndRate,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Currency", false))
                                            @Html.ValidationMessageFor(model => model.Currency, "", new { @class = "text-danger" })
                                        </div>
                                        <div class="col-xs-4 padding-left-none">
                                            <div class="input-group">
                                                @Html.TextBoxFor(model => model.FxRate,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control numberInput", "FxRate", false, Loc.FxRate, false, new { step = 6 }))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.FxRate, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    @Html.HiddenFor(model => model.CorrType)
                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.ME)
                                    {
                                        <div class="form-group">
                                            @Html.LabelFor(model => model.CorrType, Loc.CorrectionType, new { @class = "col-md-4 control-label" })
                                            <div class="col-md-8">
                                                @Html.DropDownListFor(model => model.CorrType, new List<SelectListItem>
                                                {
                                                    new SelectListItem{ Text=(Model.IsCanceled == true ? Loc.CancelTypeCorrective : string.Empty), Value = (Model.IsCanceled == true ? CancelType.Corrective : string.Empty) },
                                                    new SelectListItem{ Text=Loc.CancelTypeCredit, Value = CancelType.Credit },
                                                    new SelectListItem{ Text=Loc.AdditionalDiscount, Value = CancelType.AdditionalDiscount },
                                                    new SelectListItem{ Text=Loc.Subvention, Value = CancelType.Subvention },
                                                    new SelectListItem{ Text=Loc.CorrectionInvoice, Value = CancelType.ErrorCorrective },
                                                    new SelectListItem{ Text=Loc.CancelTypeCorrectiveUncollectable, Value = CancelType.CorrectiveUncollectable },
                                                }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "CorrTypeSelect", false, Loc.CancelType, false, null, (Model.FiscalStatus == FiscalStatus.Fiscalized ? true : false)))
                                                @Html.ValidationMessageFor(model => model.CorrType, "", new { @class = "text-danger", @id = "CorrType-validation" })
                                            </div>
                                        </div>
                                    }

                                    <hr class="hr-dashed" />

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

                                    <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>

                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS)
                                    {
                                        <div id="buyerTypeLookupContainer">
                                            <div class="form-group">
                                                @Html.LabelFor(model => model.BuyerIdDef, Loc.IdBuyer, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                                <div class="col-md-2 col-sm-4">
                                                    <select id="BuyerIdDef" name="BuyerIdDef" class="form-control custom-select">
                                                        <option></option>
                                                        @foreach (var item in ViewBag.BuyerTypeLookup)
                                                        {
                                                            <option value="@item.Id" @(Model.BuyerIdDef.HasValue ? (Model.BuyerIdDef.Value.ToString() == item.Id ? "selected" : string.Empty) : string.Empty)>
                                                                @item.Name
                                                            </option>
                                                        }
                                                    </select>
                                                    @Html.ValidationMessageFor(model => model.BuyerIdDef, "", new { @class = "text-danger" })
                                                </div>
                                                <div class="col-md-6 col-sm-8 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                                    @Html.TextBoxFor(model => model.BuyerID,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control", "BuyerID", false, Loc.CostCarrierBuyer))
                                                    @Html.ValidationMessageFor(model => model.BuyerID, "", new { @class = "text-danger" })
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.BuyerCostCenterIdDef, Loc.OptionalBuyerField, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                                <div class="col-md-2 col-sm-4">
                                                    <select id="BuyerCostCenterIdDef" name="BuyerCostCenterIdDef" class="form-control custom-select">
                                                        <option></option>
                                                        @foreach (var item in ViewBag.BuyerCostCenterTypeLookup)
                                                        {
                                                            <option value="@item.Id" @(Model.BuyerCostCenterIdDef.HasValue ? (Model.BuyerCostCenterIdDef.Value.ToString() == item.Id ? "selected" : string.Empty) : string.Empty)>
                                                                @item.Name
                                                            </option>
                                                        }
                                                    </select>
                                                    @Html.ValidationMessageFor(model => model.BuyerCostCenterIdDef, "", new { @class = "text-danger" })
                                                </div>
                                                <div class="col-md-6 col-sm-8 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                                    @Html.TextBoxFor(model => model.BuyerCostCenterId,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control", "BuyerCostCenterId", false, Loc.OptionalBuyerField))
                                                    @Html.ValidationMessageFor(model => model.BuyerCostCenterId, "", new { @class = "text-danger" })
                                                </div>
                                            </div>

                                            <div class="form-group">
                                                @Html.LabelFor(model => model.SpecPayment, Loc.SpecialTraffic, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                                <div class="col-md-8 col-sm-12">
                                                    @Html.DropDownListFor(model => model.SpecPayment, new List<SelectListItem>
                                                    {
                                                        new SelectListItem{ Text="", Value = null },
                                                        new SelectListItem{ Text="N - " + Loc.TrafficFreeOfCharge, Value = "N" },
                                                        new SelectListItem{ Text="V - " + Loc.SinglePurposeVouchers, Value = "V" },
                                                    }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "SpecPayment", false, Loc.SpecialTraffic))
                                                    @Html.ValidationMessageFor(model => model.SpecPayment, "", new { @class = "text-danger" })
                                                </div>
                                            </div>
                                        </div>
                                    }

                                    <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.HiddenFor(model => model.ThirdPartyName)
                                            @Html.TextBoxFor(model => model.ThirdParty,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide addable-input-btn", "ThirdParty", false, Loc.Recipient, false,
                                            new { dataUrl = Url.Action("SearchPartners", "Wholesale"), @autocomplete = "off", @title = Model.ThirdParty }))
                                            <div class="addable-button">
                                                <button type="button" title="@Loc.AddingNewPartner"
                                                        id="NewRecipient" class="btn btn-outline btn-primary 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="ThirdPartyAddressContainer" 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">
                                        @Html.LabelFor(model => model.DeliveryType, Loc.DeliveryType, new
                                        {
                                        @class = "col-md-4 col-sm-12 control-label text-left-sm",
                                        })
                                        <div class="col-md-3 col-sm-6">
                                            <select id="DeliveryType" name="DeliveryType" class="form-control custom-select">
                                                <option></option>
                                                @foreach (var item in ViewBag.DeliveryTypes)
                                                {
                                                    <option value="@item.Id" @(Model.DeliveryType == item.Id ? "selected" : string.Empty)>
                                                        @item.Name
                                                    </option>
                                                }
                                            </select>
                                            @Html.ValidationMessageFor(model => model.DeliveryType, "", new { @class = "text-danger", @id = "DeliveryType-validation" })
                                        </div>
                                        <div class="col-md-5 col-sm-6 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                            @Html.TextBoxFor(model => model.DeliveryPlace,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_medium side-content-move-to-left", "DeliveryPlace", false, Loc.DeliveryPlace))
                                            @Html.ValidationMessageFor(model => model.DeliveryPlace, "", new { @class = "text-danger", @id = "DeliveryPlace-validation", @autocomplete = "off" })
                                        </div>
                                    </div>

                                    <div class="form-group doc1Container">
                                        @Html.LabelFor(model => model.Order, Loc.DocumentOne, new
                                        {
                                        @class = "col-md-4 col-sm-12 text-left-sm control-label",
                                        @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-sm padding-left-none-md padding-left-none-lg">
                                            <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-sm padding-left-none-md padding-left-none-lg">
                                            <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>

                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS)
                                    {
                                        <div id="referenceDocCancellationContainer" class="form-group">
                                            @Html.LabelFor(model => model.RefundRelatedDoc, Loc.ReferenceDocCancellation, new
                                            {
                                                @class = "col-md-4 col-sm-12 control-label",
                                                @title = Loc.ReferenceDocCancellation
                                            })
                                            <div class="col-md-4 col-sm-6">
                                                @Html.TextBoxFor(model => model.RefundRelatedDoc,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control", "RefundRelatedDoc", false, Loc.CancellationReferenceDocumentNumber, false,
                                                    new { @autocomplete = "off" }))
                                                @Html.ValidationMessageFor(model => model.RefundRelatedDoc, "", new { @class = "text-danger" })
                                            </div>
                                            <div class="col-md-4 col-sm-6 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                                <div class="input-group">
                                                    <span class="input-group-addon">
                                                        <i class="far fa-calendar alt"></i>
                                                    </span>
                                                    @Html.TextBoxFor(model => model.RefundRelatedDocDate, Model.RefundRelatedDocDate.HasValue ? Model.RefundRelatedDocDate.Value.ToString(Loc.DateTimeFormatFull) : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control wholesale-dt-picker", "RefundRelatedDocDate", false, Loc.DocumentDate))
                                                </div>
                                                @Html.ValidationMessageFor(model => model.RefundRelatedDocDate, "", new { @class = "text-danger", @id = "OrderFormDate-validation" })
                                            </div>
                                        </div>
                                    }

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.WayOfSale, Loc.WayOfSelling, new { @class = "col-md-4 control-label", @title = Loc.WayOfSelling })
                                        <div class="col-md-8">
                                            @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.BA)
                                            {
                                                @Html.DropDownListFor(model => model.WayOfSale, new List<SelectListItem>
                                                 {
                                                    new SelectListItem{ Text=Loc.IsTaxCommited, Value = WayOfSale.IsTaxComitted },
                                                    new SelectListItem{ Text=Loc.ExportSale, Value = WayOfSale.ExportSale },
                                                    new SelectListItem{ Text=Loc.FederationBiH, Value = WayOfSale.BiH },
                                                    new SelectListItem{ Text=Loc.SerbianRepublic, Value = WayOfSale.RS },
                                                    new SelectListItem{ Text=Loc.BrckoDistrictBiH, Value = WayOfSale.BrckoDistrictBiH },
                                                 }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "WayOfSale", false, Loc.WayOfSelling))
                                            }
                                            else if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.ME)
                                            {
                                                @Html.DropDownListFor(model => model.WayOfSale, new List<SelectListItem>
                                                 {
                                                    new SelectListItem{ Text=Loc.SubjTaxPayer, Value = WayOfSale.IsTaxComitted },
                                                    new SelectListItem{ Text=Loc.FinalBuyer, Value = WayOfSale.FinalBuyer },
                                                    new SelectListItem{ Text=Loc.ExportSale, Value = WayOfSale.ExportSale },
                                                 }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "WayOfSale", false, Loc.WayOfSelling))
                                            }
                                            else if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS
                                                || PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.MK)
                                            {
                                                @Html.DropDownListFor(model => model.WayOfSale, new List<SelectListItem>
                                                 {
                                                    new SelectListItem{ Text=Loc.IsTaxCommitedShort, Value = WayOfSale.IsTaxComitted },
                                                    new SelectListItem{ Text=Loc.ExportSale, Value = WayOfSale.ExportSale },
                                                    new SelectListItem{ Text=Loc.FinalBuyer, Value = WayOfSale.FinalBuyer },
                                                    new SelectListItem{ Text=Loc.WayOfSaleDiplomaticConsulate, Value = WayOfSale.DiplomaticConsulate },
                                                 }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "WayOfSale", false, Loc.WayOfSelling))
                                            }
                                            else if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                                            {
                                                @Html.DropDownListFor(model => model.WayOfSale, new List<SelectListItem>
                                                 {
                                                    new SelectListItem{ Text=Loc.WayOfSaleBuyerR1, Value = WayOfSale.IsTaxComitted },
                                                    new SelectListItem{ Text=Loc.ExportSale, Value = WayOfSale.ExportSale },
                                                    new SelectListItem{ Text=Loc.ExportSaleEU, Value = WayOfSale.ExportSaleEU },
                                                    new SelectListItem{ Text=Loc.FinalBuyer, Value = WayOfSale.FinalBuyer },
                                                    new SelectListItem{ Text=Loc.TaxExempt, Value = WayOfSale.Nonresident },
                                                    new SelectListItem{ Text=Loc.Other, Value = WayOfSale.Other },
                                                 }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "WayOfSale", false, Loc.WayOfSelling))
                                            }
                                            else
                                            {
                                                @Html.DropDownListFor(model => model.WayOfSale, new List<SelectListItem>
                                                 {
                                                    new SelectListItem{ Text=Loc.IsTaxCommitedShort, Value = WayOfSale.IsTaxComitted },
                                                    new SelectListItem{ Text=Loc.FinalBuyer, Value = WayOfSale.FinalBuyer },
                                                    new SelectListItem{ Text=Loc.ExportSale, Value = WayOfSale.ExportSale },
                                                    new SelectListItem{ Text=Loc.ExportSaleEU, Value = WayOfSale.ExportSaleEU }
                                                 }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "WayOfSale", false, Loc.WayOfSelling))
                                            }
                                            @Html.ValidationMessageFor(model => model.WayOfSale, "", new { @class = "text-danger", @id = "WayOfSale-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">
                                            <select id="Clerk" name="ClerkId" class="form-control custom-select">
                                                <option value="0">@Loc.Select</option>
                                                @foreach (var item in ViewBag.Users)
                                                {
                                                    <option value="@item.Id" data-dept="@item.Dept" @(Model.ClerkId.ToString() == item.Id ? "selected" : string.Empty)>
                                                        @item.Name
                                                    </option>
                                                }
                                            </select>
                                            @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="documents" class="row tab-pane fade in">
                                @Html.Partial("~/Views/Documents/_FileDisplayPartial.cshtml", Model.Files != null ? Model.Files : new List<PantheonRA.Contracts.DataContracts.FileData>(),
                                    new ViewDataDictionary(ViewData) { { "uploadFiles", true } })
                            </div>

                            <div id="connections" class="row tab-pane fade in">
                                @Html.HiddenFor(x => x.IsCanceled)
                                @if (Model.IsCanceled)
                                {
                                    <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>
                                    }
                                }
                                <input id="hasAdvancePayments" value="@(Model.AdvancePaymentConnections != null && Model.AdvancePaymentConnections.Any(conn => conn.Price < 0) ? "true" : "false")" hidden />
                                <div id="advancePaymentConnectionsContainer">
                                    @if (Model.AdvancePaymentConnections != null)
                                    {
                                        for (var i = 0; i < Model.AdvancePaymentConnections.Count(); i++)
                                        {
                                            <div class="form-group">
                                                <h4 class="form-control clickable-icon connectionContainer advPayConn" 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>
                                        }
                                    }
                                </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 docMoveConn" disabled>
                                                <a class="@Model.DocMoveConnections[i].AcKey" onclick="openDocMoveConnection('@Model.DocMoveConnections[i].AcKey', '@Model.DocMoveConnections[i].TypeOfDocument')">
                                                    @Model.DocMoveConnections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.DocMoveConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                                @if (Model.LinkedDocuments != null)
                                {
                                    for (var i = 0; i < Model.LinkedDocuments.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="openDmsDoc('@Model.LinkedDocuments[i].AcKey')">
                                                    @Model.LinkedDocuments[i].AcKeyDisplay
                                                </a>
                                            </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 noteModalBtn" 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 = true,
                                        IsSupplier = false,
                                    },
                                    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" onclick="">@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>

        @{Html.RenderPartial("~/Views/Wizard/Wizard.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceDeleteModals.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_CashRegReceiptExpenditure.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_ConnectDocumentWizardModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceErrorCorrectiveModal.cshtml");}
        @{Html.RenderPartial("~/Views/Commission/_CreateModal.cshtml", new CommissionViewModel());}
        @{Html.RenderPartial("~/Views/AdvancePayment/_MoveAdvancePaymentLinksModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceCurrencyChange.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_PartialCancelInvoice.cshtml", new PartialCancelInvoiceModalModel()
            {
                Type = InvoiceType.Wholesale,
                PartialCancelDefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
                PartialCancelDefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
                PartialCancelDefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue,
            });
        }
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceSubjectRegNoMissing.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_CEInvoiceModal.cshtml");}
        @Html.Partial("~/Views/Shared/Components/_CreateDocumentModals.cshtml")
        @{Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoIssueModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_MoveTipFiscalizationModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceIRIS1006038Modal.cshtml");}
    </div>

    <div id="taxOptions" hidden>
        @foreach (var tax in ViewBag.Taxes)
        {
            <option value="@tax.VATCode" data-vat="@tax.VAT" data-fiscalCode="@tax.FiscalCode" 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="taxExemptOptions" hidden>
        <option></option>
        <option value="VAT_CL17">@Loc.VAT_CL17</option>
        <option value="VAT_CL20">@Loc.VAT_CL20</option>
        <option value="VAT_CL26">@Loc.VAT_CL26</option>
        <option value="VAT_CL27">@Loc.VAT_CL27</option>
        <option value="VAT_CL28">@Loc.VAT_CL28</option>
        <option value="VAT_CL29">@Loc.VAT_CL29</option>
        <option value="VAT_CL30">@Loc.VAT_CL30</option>
        <option value="VAT_CL44">@Loc.VAT_CL44</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="PrintPreview" data-url="@Url.Action("WholesalePdf", "Wholesale")" 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="ConfirmLoc" value="@Loc.Confirm" />
<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")" />
<input type="hidden" id="GetFxRateCalcOperationUrl" value="@Url.Action("GetFxRateCalcOperation", "Currency")" />
<input type="hidden" id="MeLoc" value="@Localization.Code.ME" />
<input type="hidden" id="PositiveAndNegativeQuantityCannotBeOnTheSameDocumentLoc" value="@Loc.PositiveAndNegativeQuantityCannotBeOnTheSameDocument" />
<input type="hidden" id="AllTaxesNeedFiscalCodeLoc" value="@Loc.AllTaxesNeedFiscalCode" />
@Html.Hidden("UrlMoveStatus", Url.Action("MoveStatus", "Wholesale"))
@Html.Hidden("UrlMovePosting", Url.Action("MoveIssuedPosting", "Wholesale"))
@Html.Hidden("ConfirmLoc", Loc.Confirm)
@Html.Hidden("MovePostingNotConfirmed", Loc.MovePostingNotConfirmed)

@section pageScripts{
    @Scripts.Render("~/bundles/fileDisplay")
    @Scripts.Render("~/bundles/lpfr")
    @Scripts.Render("~/bundles/depositModal")
    @Scripts.Render("~/bundles/subjects")
    @Scripts.Render("~/bundles/invoiceIdent")
    @Scripts.Render("~/bundles/wizardHelper")
    @Scripts.Render("~/bundles/customSignature")
    @Scripts.Render("~/bundles/serialnumbers")

<script type="text/javascript">
        var invoiceItems = [];
        var openStatus = "";
        var paperSize = "";
        var receiverTypeaheadData;
        var thirdPartyTypeaheadData;
        var hasUnfiscalizedInvoice = false;

    $(document).ready(function () {
        if ($("#DocumentTabActive").val() === "@true")
            $('[href="#documents"]').tab('show');

        getFxRateCalcOperation("Date");
        loadInvoiceItems();
        initializeSubjectsEdit();
        initializeFileDisplay('@Model.PreviewImage', '@(Model.Files != null && Model.Files.Any() ? Model.Files[0].Id.ToString() : string.Empty)');

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

        $('.wholesale-dt-picker').datetimepicker({
            format: 'DD.MM.YYYY HH:mm:ss',
            locale: 'rs-RS'
        }).on('dp.change', function (event) {
            $(this).trigger('change');
        });

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

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

        showFiscalData();
        checkFormEditable();
        updateReportTreeDisplay($(".printMD"), $("#DocTypeSelect option:selected").attr("data-fiscalize"));

        initializeIssuedSerialNumbers({
            serialNumberQuantityIsReached: '@Loc.SerialNumberQuantityIsReached',
            numberOfSerialNumbersIsGreaterThanOnDocument: '@Loc.NumberOfSerialNumbersIsGreaterThanOnDocument',
            serialNumberValueAlreadyExist: '@Loc.SerialNumberValueAlreadyExist',
            automaticIssueOfSerialNumbersNotPossible: '@Loc.AutomaticIssueOfSerialNumbersNotPossible',
            selectedSerialNumberDoesNotExistInWarehouse: '@Loc.SelectedSerialNumberDoesNotExistInWarehouse',
            dateDueExpiredForSerialNumber: '@Loc.DateDueExpiredForSerialNumber',
            desiredQuantity: '@Loc.DesiredQuantity',
            actualQuantity: '@Loc.ActualQuantity',
            difference: '@Loc.Difference',
            errorSaving: '@Loc.ErrorSaving',
            confirm: '@Loc.Confirm',
            cancel: '@Loc.Cancel'
        },
        {
            moveUpdateSerialNoUrl: '@Url.Action("MoveUpdateSerialNo", "SerialNumbers")',
            serialNoUpdUrl: '@Url.Action("SerialNoUpd", "SerialNumbers")',
            deleteByAcKeyAndSerialNoUrl: '@Url.Action("DeleteByAcKeyAndSerialNo", "SerialNumbers")',
            deleteIssuedByAcKeyAndSerialNo: '@Url.Action("DeleteIssuedByAcKeyAndSerialNo", "SerialNumbers")',
            deleteAllIssuedByAcKey: '@Url.Action("DeleteAllIssuedByAcKey", "SerialNumbers")',
            deleteUnusedItemSerialsUrl: '@Url.Action("DeleteUnusedItemSerials", "SerialNumbers")',
            createSerialNoUrl: '@Url.Action("CreateSerialNo", "SerialNumbers")',
            moveSerialNoAddSalesUrl: '@Url.Action("MoveSerialNoAddSales", "SerialNumbers")',
            getByAcKeyAndAnNoUrl: '@Url.Action("GetByAcKeyAndAnNo", "SerialNumbers")',
            serialNoAutoEditionUrl: '@Url.Action("SerialNoAutoEdition", "SerialNumbers")',
            getFreeSerialNumbers: '@Url.Action("GetFreeSerialNumbers", "SerialNumbers")',
            refreshStockSerialNoOnDay: '@Url.Action("RefreshStockSerialNoOnDay", "SerialNumbers")'
        }, "IssuerId");

        if ($(".advPayConn").length > 0) {
            $("#DateDueDays").addClass("custom-dirty-checker-ignore");
            $("#DateDue").addClass("custom-dirty-checker-ignore");
            $("#Order").addClass("custom-dirty-checker-ignore");
            $("#OrderDate").addClass("custom-dirty-checker-ignore");
            $("#OrderForm").addClass("custom-dirty-checker-ignore");
            $("#OrderFormDate").addClass("custom-dirty-checker-ignore");
        }

        $("#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'
                    }
                ]
            });
        });

        $("#PaymentMethodId").on('change', function () {
            checkDeposit();
            $("#PaymentMethodId").prop("title", $("#PaymentMethodId option:selected").text());
            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");
        });

        $("#DocTypeSelect").on('change', async function () {
            $("#DocType").val($("#DocTypeSelect").val());
            $("#DocTypeTipFiscalization").val($("#DocTypeSelect option:selected").attr("data-docTypeTipFiscalization"));
            $("#DocTypeSelect").prop("title", $("#DocTypeSelect option:selected").text());
            setDocTypeRounding("#DocTypeSelect");
            updateReportTreeDisplay($(".printMD"), $("#DocTypeSelect option:selected").attr("data-fiscalize"));

            if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True") {
                $("#CanFiscalize").val(true);
                $("#wholesaleFormDocumentBody").addClass("table-has-fiscal-data");
                $("#buyerTypeLookupContainer").removeClass("hidden");
            } else {
                $("#CanFiscalize").val(false);
                $("#wholesaleFormDocumentBody").removeClass("table-has-fiscal-data");
                $("#BuyerCostCenterId").val("");
                $("#BuyerCostCenterIdDef").val(null);
                $("#BuyerIdDef").val(null);
                $("#BuyerID").val("");
                $("#buyerTypeLookupContainer").addClass("hidden");
            }

            if ($("#AcKey").val() && $("#IssuerIdSelect option:selected").val() !== $("#IssuerId").val()) {
                $("#IssuerIdSelect").append(new Option($("#IssuerId").val(), $("#IssuerId").val(), true, true));
                $("#IssuerIdSelect").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 ($("#DocTypeSelect option:selected").attr("data-displayProtocol") === "True") {
                $(".protocolContainer").prop("hidden", false);
            } else {
                $(".protocolContainer").prop("hidden", true);
            }

            if (!$("#AcKey").val()) {
                getDocTexts($("#DocTextsUrl").val(), $("#Statement"), $("#Statements"), $("#DocType").val());
                $("#IsObligDept").val($("#DocTypeSelect option:selected").attr("data-isObligDept"));
                $("#IsObligCostDrv").val($("#DocTypeSelect option:selected").attr("data-isObligCostDrv"));

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

                if ($("#DocTypeSelect option:selected").attr("data-warehouse")) {
                    var warehouse = $("#DocTypeSelect option:selected").attr("data-warehouse");
                    $("#IssuerIdSelect").val(warehouse);

                    if ($("#IssuerIdSelect option:selected").val() !== warehouse) {
                        $("#IssuerIdSelect").append(new Option(warehouse, warehouse, true, true));
                    }
                } else {
                    $("#IssuerIdSelect").val("");
                }
                $("#IssuerIdSelect").trigger("change");

                if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS") {
                    if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True") {
                        $("option[data-fiscalcode='']").attr("hidden", true);
                    } else {
                        $("option[data-fiscalcode='']").attr("hidden", false);
                    }
                }

                if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True") {
                    hasUnfiscalizedInvoices();
                }

                $("#Receiver").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                $("#ReceiverId").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                $("#Receiver").trigger("change");
            }

            showFiscalData();
            if (!$("#AcKey").val()) {
                $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
                $("#Note").val($("#DocTypeSelect option:selected").attr("data-defaultNote"));
                setNoteIcon();
            }

            updatePrintDisplay();
            updatePrintMenuDisplay($("#DocTypeSelect option:selected").attr("data-isInternal") === "@true");
            $("#PaymentMethodId").trigger("change");

            if ('@(PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS)' == '@Boolean.TrueString' && $("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" && !$("#AcKey").val()) {
                swapLoadingIcon(true, "saveButton", "fa fa-save");
                swapLoadingIcon(true, "printButton", "far fa-print");
                $("#identSearchTable input").prop('disabled', true);

                var unfiscalizedAcKey = await CheckLastInvoice('@Url.Action("CheckLastInvoice", "Move")', $("#DocType").val());
                hasUnfiscalizedInvoice = unfiscalizedAcKey != undefined && unfiscalizedAcKey != null && unfiscalizedAcKey != '';

                swapLoadingIcon(false, "saveButton", "fa fa-save");
                swapLoadingIcon(false, "printButton", "far fa-print");
                $("#identSearchTable input").prop('disabled', false);
                checkLpfr($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True");
            }
            else {
                hasUnfiscalizedInvoice = false
                checkLpfr($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True");
            }

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

        $("#IssuerIdSelect").on('change', function () {
            $("#IssuerId").val($("#IssuerIdSelect").val());
        });

        $("#CorrTypeSelect").on('change', function () {
            $("#CorrType").val($("#CorrTypeSelect option:selected").val());

            if ($("#AcKey").val() && $("#IsCanceled").val() !== "True" && $("#CorrTypeSelect option:selected").val() !== "@CancelType.Subvention") {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.DoYouWantToOpenConnectDocumentWizard",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.Abandon',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Confirm',
                            action: function () {
                                startConnectDocWizardModal();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        });

        $("#Status").on('change', function () {
            $("#Status").prop("title", $("#Status option:selected").text());
        });

        initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#Receiver'), $("#ReceiverId"), function (item) {
            receiverTypeaheadData = 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 {
                        changeReceiverData();
                    }
                });
            } else
                changeReceiverData();
        });

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

        initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#ThirdParty'), $("#ThirdPartyId"), function (item) {
            thirdPartyTypeaheadData = item;
            $("#ThirdPartyName").val(item.value);
            $("#ThirdParty").prop("title", $("#ThirdParty").val());
            $("#ThirdPartyAddressContainer").text(item.completeAddress);
            $("#ThirdPartyAddressContainer").prop('title', item.completeAddress);
        });

        initializeDeliveryPlaceTypeahead('@Url.Action("SearchPosts", "Post")', $('#DeliveryPlace'), $("#DeliveryPlace"), function (item) {
            $("#DeliveryPlace").text(item.value);
        });

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

        $("#InvoiceDate, #OrderDate, #OrderFormDate, #Date, #TaxDate").on('change', function () {
            if (this.id === "InvoiceDate" && invoiceItems && invoiceItems.length > 0) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "question",
                    text: "@Loc.DateChangedSearchForNewPrices",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.Abandon',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            action: async function () {
                                setIdentPrices();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }

            var start = getStartDate($("#CalcInvoOutFallDue").val());
            var newDate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + Number($("#DateDueDays").val()));

            $("#Currency").trigger("customSelectChange");
            $("#DateDue").datepicker('setDate', newDate);
        });

        $("#DateDueDays").on('change', function () {
            var start = getStartDate($("#CalcInvoOutFallDue").val());
            var newDate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + Number($("#DateDueDays").val()));
            $("#DateDue").datepicker('setDate', newDate);
        });

        $("#DateDue").on('change', function () {
            var start = getStartDate($("#CalcInvoOutFallDue").val());
            var end = $("#DateDue").datepicker('getDate');

            var endDate = +new Date(end.getFullYear(), end.getMonth(), end.getDate());
            var startDate = +new Date(start.getFullYear(), start.getMonth(), start.getDate());

            var days = (endDate - startDate) / 1000 / 60 / 60 / 24;
            $("#DateDueDays").val(days.toFixed(0));
        });

        function getStartDate(dateType) {
            var start = new Date();
            if (dateType === "@CalcDueDateType.DateDoc1" && $("#OrderDate").datepicker('getDate') != null)
                start = $("#OrderDate").datepicker('getDate');
            else if (dateType === "@CalcDueDateType.DateDoc2" && $("#OrderFormDate").datepicker('getDate') != null)
                start = $("#OrderFormDate").datepicker('getDate');
            else if (dateType === "@CalcDueDateType.Date" && $("#Date").datepicker('getDate') != null)
                start = $("#Date").datepicker('getDate');
            else if (dateType === "@CalcDueDateType.TaxDate" && $("#TaxDate").datepicker('getDate') != null)
                start = $("#TaxDate").datepicker('getDate');
            else
                start = $("#InvoiceDate").datepicker('getDate');

            return start;
        }

        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");
        $("#IssuerIdSelect").trigger("change");

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

        $("#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();
        });

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

        $("#Currency").on("customSelectChange", function () {
            var date = getStartDate($("#CurrencyFxRateType").val());

            $.get('@Url.Action("GetFxRate", "Currency")', { Currency: $("#Currency").val(), Date: new Date(date).toISOString() })
                .done(function (response) {
                    var isCurrChange = true;
                    if ($("#ToPayCurrency").text() === $("#Currency").val())
                        isCurrChange = false;

                    $(".ToPayCurrency").text($("#Currency").val());
                    $("#FxRate").val(response);
                    formatNumberInput($("#FxRate"));
                    toPayDisplay();

                    if (isInitCurrencyChange === true) {
                        isInitCurrencyChange = false;
                        return;
                    }

                    save("@InvoiceSaveType.SaveAndChangeFxRate");
                    if (invoiceItems.length > 0 && isCurrChange === true)
                        $("#invoiceCurrencyChangeWarningModal").modal("show");
                });
        });

        if (!$("#AcKey").val()) {
            var isInitCurrencyChange = true;
            $("#Currency").trigger("customSelectChange");
        }

        $("#FxRate").on("change", function () {
            save("@InvoiceSaveType.SaveAndChangeFxRate");
        });

        $("#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'
                        }
                    ]
                });
        });

        toPayDisplay();

        $('#IdentSearch').on("focus-custom-typeahead", function () {
            checkDeposit();
            @*if (!$("#IssuerId").val())
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.WarehouseIsRequired",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            action: async function () {
                                $("#IssuerIdSelect").focus();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });*@

            var errMsg;
            var $focusNext;

            if (!$("#IssuerId").val()) {
                errMsg = "@Loc.WarehouseIsRequired";
                $focusNext = $("#IssuerIdSelect");
            }

            if ($("#DocTypeSelect option:selected").attr("data-isObligDept") === "True" && !$("#Department").val()) {
                if (!$focusNext)
                    $focusNext = $("#Department");

                errMsg = errMsg ? errMsg + " <br /> " + "@Loc.DepartmentIsRequired" : "@Loc.DepartmentIsRequired";
            }

            if (errMsg)
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: errMsg,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            action: async function () {
                                $focusNext.focus();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
        });

        dropifyUploadAttachments();

        $("#SpecPayment").on("change", function () {
            if ($("#SpecPayment option:selected").val() === "N" && $('#PaymentMethodId option:selected').attr("data-fiscalize") !== "0") {
                $('#PaymentMethodId option[data-fiscalize="0"]').first().prop('selected', true);
            }
        });

        $("#Clerk").on("change", function () {
            if ($("#FillDeptFromPersonResp").val() === "True")
                $("#Department").val($("#Clerk option:selected").attr("data-dept"));
        });

        $("#WayOfSale").on('change', function () {
            changeWayOfSale();
        });
    });


    function dropifyUploadAttachments() {
        var error = $("#GeneralErrorMessage").val();
        var remove = $("#Remove").val();
        var dragOrClick = $("#AddAttachment").val();
        var dragOrClickToReplace = $("#AddAttachment").val();
        var fileSizeMessage = $("#FileSizeMessage").val();
        var fileNotAllowedMessage = $("#FileNotAllowedMessage").val();

        var dr = $('.dropify').dropify({
            messages: {
                'default': dragOrClick,
                'replace': dragOrClickToReplace,
                'remove': remove,
                'error': error
            },
            error: {
                'fileSize': fileSizeMessage,
                'fileExtension': fileNotAllowedMessage
            }
        });


        $('.dropify').on('change', function () {
            if ($("#DocTypeSelect option:selected").attr("data-docTypeDms") !== "" && $("#DocTypeSelect option:selected").attr("data-classification") !== "") {
                swapLoadingIcon(true, "saveButton");
                swapLoadingIcon(true, "printButton", "fa-print");

                $("#Statement").val($("#Statements").val() ? $("#Statements").val().toString() : "");
                $("#ItemsJsonString").val(JSON.stringify(invoiceItems));
                $("#Note").val(encodeURIComponent($("#Note").val()));

                $("#WholesaleForm").submit();
            } else {
                $("#createDocumentIrisMessage").text(stringFormat("@Loc.IncorrectDocTypeSettings", $("#DocType").val()));
                $("#openDocTypeSettings").attr("onclick", "window.open('@Url.Action("Edit", "DocumentType")?id=" + $("#DocType").val() + "', '_self')");
                $("#createDocumentErrorModal").modal("show");
                $('.dropify-clear').click();
            }
        });
    }

    async function checkLpfr(canFiscalize) {
        if (!canFiscalize) {
            saveLastDocumentType($("#DocType").val());
            return;
        }

        let pinUrlLpfr = $("#DocTypeSelect option:selected").attr("data-pinUrlLpfr");
        let attentionUrl = $("#DocTypeSelect option:selected").attr("data-attentionUrlPfr") ?
            $("#DocTypeSelect option:selected").attr("data-attentionUrlPfr") : '@Url.Action("CheckFiscConnection", "DocumentType")' + '?docType=' + $("#DocType").val();

        if (isNewDocumentType($("#DocType").val())) {
            if (pinUrlLpfr) {
                openLpfrPinModal(pinUrlLpfr, '@Loc.EnterPin', '@Loc.OK', '@Loc.Cancel',
                    async function () {
                        $('#Receiver').focus();

                        let lpfrConnectionSuccess = await checkLpfrConnectionWithToast(
                            attentionUrl,
                            '@Loc.PinCorrectCommunicationWithLpfrSuccessful' + ' (' + $("#DocTypeSelect option:selected").text()?.trim() + ')',
                            '@Loc.ErrorCommunicationWithPfr' + ' (' + $("#DocTypeSelect option:selected").text()?.trim() + ')'
                        );

                        if (lpfrConnectionSuccess) saveLastDocumentType($("#DocType").val());
                    },
                    function (error) {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: false,
                            type: "alert",
                            text: error,
                            closeOtherModals: false,
                            buttons: [
                                {
                                    text: '@Loc.OK',
                                    icon: 'fa fa-check',
                                    closeOnAction: true,
                                    action: function () {
                                        $("#lpfrPinModal input").focus();
                                    },
                                    type: 'primary'
                                },
                            ]
                        });
                    },
                    undefined,
                    {
                        2100: '@Loc.lpfrError2100',
                        2110: '@Loc.lpfrError2110',
                        1300: '@Loc.lpfrError1300',
                        2220: '@Loc.lpfrError2220',
                        2400: '@Loc.lpfrError2400',
                        communicationModalTitle: '@Loc.CommunicationWithLpfr',
                        communicationModalErrorMessage: '@Loc.ErrorCommunicationWithLpfr',
                        communicationButtonTitle: '@Loc.ErrorCommunicationWithLpfr',
                        communicationButtonActionText: '@Loc.ClickToCorrectAction',
                        manualButtonTitle: '@Loc.LpfrCommunicationInstruction',
                        manualButtonActionText: '@Loc.LpfrCommunicationErrorInstruction',
                        lpfrCommunicationHelp: '@SiteHelpAttributeHelper.GetHelpUrl(PantheonRA.BackOffice.Enums.HelpIds.LpfrCommunicationError)'
                    }
                );
            }
            else {
                let lpfrConnectionSuccess = true;
                if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && '@isInFiscalPrinterLocalization' == '@Boolean.FalseString') {
                    lpfrConnectionSuccess = await checkLpfrConnectionWithToast(
                        attentionUrl,
                        '@Loc.CommunicationWithPfrSuccessful' + ' (' + $("#DocTypeSelect option:selected").text()?.trim() + ')',
                        '@Loc.ErrorCommunicationWithPfr' + ' (' + $("#DocTypeSelect option:selected").text()?.trim() + ')'
                    );
                }

                if (lpfrConnectionSuccess) saveLastDocumentType($("#DocType").val());
            }
        }
    }

    function toPayDisplay() {
        if ($("#CompanyCurrency").val() !== $("#Currency").val()) {
            $("#toPayContainer").attr("hidden", true);
            $("#toPayNewCurrencyContainer").attr("hidden", false);
        } else {
            $("#toPayNewCurrencyContainer").attr("hidden", true);
            $("#toPayContainer").attr("hidden", false);
        }
    }

    function changeReceiverData() {
        var item = receiverTypeaheadData;
        if ($("#SavedReceiverId").val() === item.value) {
            return;
        }

        $("#SavedReceiverId").val(item.value);
        $("#ReceiverName").val(item.value);
        $("#Receiver").prop("title", $("#Receiver").val());
        $("#ReceiverAddressContainer").text(item.completeAddress);
        $("#ReceiverAddressContainer").prop('title', item.completeAddress);
        if ($("#FillRefFromSubj").val() === "True") {
            $("#Clerk").val(item.clerk);
            $("#Clerk").trigger("change");
        }
        $("#RefCode").val(item.bankAccountRefCode);
        $("#WayOfSale").val(item.wayOfSale);
        $("#ReceiverPriceRate").val(item.priceRate);
        $("#ReceiverRebate").val(item.rebate);
        $("#ReceiverSuppSaleMet").val(item.paymentMethodIdSupplier);
        if (item.paymentMethodId != null && item.paymentMethodId != "") {
            $("#PaymentMethodId").val(item.paymentMethodId);
        } else {
            $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
        }
        $("#DateDueDays").val(item.daysForPayment);
        $('#DateDueDays').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());
        $("#DeliveryPlace").val(item.parityPost);

        if ($("#Currency").val() !== item.currency) {
            $("#Currency").val(item.currency);
            $("#OldCurrency").val(item.currency);
            $("#Currency").trigger("customSelectChange");
        }

        if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && item.wayOfSale === "@WayOfSale.IsTaxComitted") {
            $("#BuyerID").val(item.vat);
            $("#BuyerIdDef").val("10");
        } else {
            $("#BuyerID").val("");
            $("#BuyerIdDef").val("");
        }

        if ($("#ThirdPartyId").val())
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: "@Loc.InvoiceSubjectChanged",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        action: function () {
                            getNewPricesForSubject();
                        },
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: function () {
                            changeThirdPartyToReceiver(item)
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        else
            changeThirdPartyToReceiver(item);
    }

    function changeThirdPartyToReceiver(item) {
        $("#ThirdPartyId").val(item.id);
        $("#ThirdParty").val(item.value);
        $("#ThirdPartyName").val(item.value);
        $("#ThirdParty").prop("title", $("#ThirdParty").val());
        $("#ThirdPartyAddressContainer").text(item.completeAddress);
        $("#ThirdPartyAddressContainer").prop('title', item.completeAddress);
        thirdPartyTypeaheadData = item;
        getNewPricesForSubject();
    }

    function getNewPricesForSubject() {
        if (invoiceItems.length > 0) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: "@Loc.BuyerChangedGetIdentPrices",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        action: function () {
                            if ($("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.OnSubjectChange" && $(".advPayConn").length === 0)
                                moveAdvancePaymentLinks(true);
                        },
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: function () {
                            checkClosedVATPeriod();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        getDeliveryFillType();
        checkPaymentValidation();
    }

    function checkClosedVATPeriod() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({ Date: new Date($("#Date").datepicker("getDate")).toISOString() }),
            url: '@Url.Action("TestClosedVATPeriod", "Move")',
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.Result == "@ActiveStatus.Inactive") {
                setIdentPrices();
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: "@Loc.TaxPeriodIsClosed",
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: '@Loc.OK',
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }
        });
    }

    function changeIdentTax(anNo) {
        var vatPercent = toNumber($("#vat-" + anNo + " option:selected").attr("data-vat"));
        $("#vatPercent-" + anNo).val(vatPercent);
        changeIdentData(anNo);
    }

    function changePriceRebate(anNo) {
        var rebate = 100 - (toNumber($("#priceRebate-" + anNo).val()) / toNumber($("#price-" + anNo).val()) * 100);
        $("#rabate-" + anNo).val(rebate);
        changeIdentData(anNo);
    }

    function calculatePriceWithDiscount() {
        var value = toNumber($("#TotalAmount").val()) - toNumber($("#DiscountAmount").val());
        $("#Value").val(value);
        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 appendIdentToTable(data, isNewIdent = false) {
        if ((!data.Department || data.Department === "") && $("#DocTypeSelect option:selected").attr("data-isObligDept") === "True")
            data.Department = $("#Department option:selected").val();

        let newRow = createIdentsTableRows($("#invoice"), data, SaleType.Wholesale, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#IsVATObligee").val(), setRounding(), $("#RoundPrice").val(), "@PantheonRA.BackOffice.CurrentUser.Localization");
        initializeNumberInputs();
        if (isNewIdent) {
            reorderColumns(true, newRow);

            if ($("#DocTypeSelect option:selected").attr("data-checkIdentDpl") === "True") {
                var dplAnNo;
                for (var i = 0; i < invoiceItems.length; i++) {
                    if (invoiceItems[i].Ident === data.Ident && invoiceItems[i].AnNo !== data.AnNo) {
                        dplAnNo = dplAnNo ? dplAnNo + ", " + invoiceItems[i].AnNo : " " + invoiceItems[i].AnNo;
                    }
                }

                if (dplAnNo) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: stringFormat(dplAnNo && dplAnNo.includes(",") ? "@Loc.IdentAlreadyExistOnPositions" : "@Loc.IdentAlreadyExistOnPosition", data.Ident) + dplAnNo,
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            }
        }
    }

    function addPosition(selectedInvoiceItemData) {
        if (hasUnfiscalizedInvoice) {
            hasUnfiscalizedInvoiceErrorDisplay();
            return;
        }

        if ($("#IssuerId").val() === "") {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "issuerIdReqErrorModal",
                type: "alert",
                text: "@Loc.WarehouseIsRequired",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        action: async function () {
                            $("#IssuerIdSelect").focus();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
            return;
        }
        if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS"
            && checkIdentQuantity(invoiceItems, $("#SelectedItemQuantity"), true) === false)
            return;

        var totalPrice = toNumber($("#SelectedItemQuantity").val()) * toNumber(selectedInvoiceItemData.price);
        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,
                RTPrice: 0,
                PriceRebate: selectedInvoiceItemData.price - (selectedInvoiceItemData.price * (selectedInvoiceItemData.rabate <= 0 ? 1 : selectedInvoiceItemData.rabate) / 100),
                Rabate: selectedInvoiceItemData.rabate,
                VAT: $("#WayOfSale").val() === "@WayOfSale.ExportSale" || $("#WayOfSale").val() === "@WayOfSale.ExportSaleEU" ? 0 : selectedInvoiceItemData.vat,
                VATCode: $("#WayOfSale").val() === "@WayOfSale.ExportSale" || $("#WayOfSale").val() === "@WayOfSale.ExportSaleEU" ? "NN" : selectedInvoiceItemData.vatCode,
                VATFiscalCode: selectedInvoiceItemData.vatFiscalCode,
                TotalPrice: excise.discountedPriceWithExcise,
                Note: "",
                MeasurementUnit: selectedInvoiceItemData.measurementUnit,
                TaxPrice: excise.vat,
                BasisForTax: totalPrice - discount,
                PriceForValue: 0,
                Excise: (excise.discountedPriceWithExcise - (totalPrice - discount) - vat) / selectedInvoiceItemData.quantity,
                IncBase: selectedInvoiceItemData.incBase,
                NotIncBase: selectedInvoiceItemData.notIncBase,
                IncBaseP: selectedInvoiceItemData.incBaseP,
                NotIncBaseP: selectedInvoiceItemData.notIncBaseP,
                PricesForSelect: selectedInvoiceItemData.pricesForSelect,
                CostDrv: selectedInvoiceItemData.costDrv ? selectedInvoiceItemData.costDrv : "",
                Department: dept,
                ExemptFromVATSType: "",
                SalePrice: selectedInvoiceItemData.retailPrice,
                SerialNo: selectedInvoiceItemData.serialNo,
                DateDue: selectedInvoiceItemData.dateDue
            }

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

            var saveType = invoiceItem.SerialNo && invoiceItem.SerialNo !== "N" ? '@InvoiceSaveType.SaveAndCheckForSerials' : '@InvoiceSaveType.SaveAndAddIdent';
            if ($("#DocTypeSelect option:selected").attr("data-checkPosPriceQty") === "@true" && (invoiceItem.Quantity === 0 || invoiceItem.Price === 0)) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: stringFormat("@Loc.InoicePositionQuantityOrPrice0Warning", invoiceItem.AnNo),
                    onClose: function () { onClickSave(saveType) },
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else if (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True"
                || $("#CanFiscalize").val() === "True")
                && $("#IsCanceled").val() === "False"
                && $("#FiscalStatus").val() !== "@FiscalStatus.Fiscalized"
                && toNumber(selectedInvoiceItemData.quantity) < 0
                && ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.ME" || "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.SI")) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.InvoiceIdentNegativeQuantityWarning",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            action: async function () {
                                onClickSave(saveType);
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                onClickSave(saveType);
            }
        }
    }

    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) {
            $("#IssuerIdSelect").attr("disabled", false);
            $("#sh-dropdown-menu").remove();

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

    function changeIdentQuantity(anNo) {
        if (canChangeIdentQuantity(anNo) === false)
            return;

        if("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS")
            checkIdentQuantity(invoiceItems, $("#quantity-" + anNo));

        if (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True"
            || $("#CanFiscalize").val() === "True")
            && $("#IsCanceled").val() === "False"
            && $("#FiscalStatus").val() !== "@FiscalStatus.Fiscalized"
            && toNumber($("#quantity-" + anNo).val()) < 0
            && ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.ME" || "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.SI")) {

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

        changeIdentData(anNo);
        if (toNumber($("#quantity-" + anNo).val()) < 0)
            checkIdentSerialNo(anNo, "M");
        else
            checkIdentSerialNoIssue(anNo, "M");
    }

    function canChangeIdentQuantity(anNo, showModal = true) {
        let ident = invoiceItems[getInvoiceItemIndex(anNo)];

        if (($('#identSerialNoGridIssue tbody tr').length > 0 || $('#identSerialNoGrid > tbody > tr').length > 0) && $("#serialNo-" + anNo).val() !== "N" &&
            ((ident.Quantity > 0 && toNumber($("#quantity-" + anNo).val()) < 0) || (ident.Quantity < 0 && toNumber($("#quantity-" + anNo).val()) > 0))) {

            if (showModal) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.CannotChangeSignReleaseSerialsFirst",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            action: function () {
                                $("#quantity-" + anNo).focus();
                            },
                            type: 'primary'
                        }
                    ]
                });
            }
            return false;
        }
        return true;
    }

    function changeIdentData(anNo) {
        if (canChangeIdentQuantity(anNo, false) === false)
            return;

        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($("#vatPercent-" + anNo).val());

        let item = invoiceItems[getInvoiceItemIndex(anNo)];

        var vatChanged = false;
        if (item.VATCode !== $("#vat-" + anNo + " option:selected").val() && $("#IsVATObligee").val() === "True")
            vatChanged = true;

        item.AcKey = $("#acKey-" + anNo).val();
        item.Quantity = toNumber($("#quantity-" + anNo).val());
        item.Price = toNumber($("#price-" + anNo).val());
        item.Rabate = toNumber($("#rabate-" + anNo).val());
        item.Note = $("#note-" + anNo).val();
        item.VAT = toNumber($("#vatPercent-" + anNo).val());
        item.VATFiscalCode = $("#vat-" + anNo + " option:selected").attr("data-fiscalCode");
        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 = totalPrice - discount;
        item.CostDrv = $("#costDrv-" + anNo).val();
        item.Department = $("#department-" + anNo).val();
        item.ExemptFromVATSType = $("#exemptFromVATSType-" + anNo + " option:selected").val();
        item.PriceRebate = toNumber($("#price-" + anNo).val()) - (toNumber($("#price-" + anNo).val()) * toNumber($("#rabate-" + anNo).val()) / 100);

        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.vat;
        item.TotalPrice = excise.discountedPriceWithExcise;

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

        updatePriceTable();

        if (vatChanged == true)
            onClickSave();
    }

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

    function changeIdentTotalPrice(anNo) {
        var price = toNumber($("#totalPrice-" + anNo).val()) / (1 + (toNumber($("#vatPercent-" + anNo).val()) / 100));
        var priceAddedDiscount = price / (1 - toNumber($("#rabate-" + anNo).val()) / 100);

        if (toNumber($("#quantity-" + anNo).val()) !== 0)
            priceAddedDiscount = priceAddedDiscount / toNumber($("#quantity-" + anNo).val());

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

    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);

        if ($("#FiscalStatus").val() > 1 || $("#IsTaxPeriodLocked").val() === "True") {
            saveNotePost($("#note-" + selectedItemAnNo).val(), selectedItemAnNo);
        }
    }

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

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

            totalPrice += evenRound(price * invoiceItems[i].Quantity, setRounding());
            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(), evenRound(totalPrice + taxAmount - discountSum + excise, $("#RoundValue").val()));
        var toPayAmountForPay76a = formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(totalPrice - discountSum + excise, $("#RoundValue").val()));
        var toPayAmountOurCurrency = formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(calculateWithOperation(toNumber(toPayAmount), toNumber($("#FxRate").val())), $("#RoundValueOc").val()));

        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);
        $("#ToPayAmountSub").val(toPayAmount);
        $("#DiscountPercent").val(isNaN(discountPercent) ? 0 : discountPercent);
        $("#ForPay76a").val(toPayAmountForPay76a);
        $("#ToPayAmountOurCurrency").text(toPayAmountOurCurrency);

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

        calculatePriceWithDiscount();
    }

    onClickSave = function (option, printType = null, fiscalize = false, signature = false) {
        if (signature) {
            openSignatureForm(() => { onClickSave(option, printType, fiscalize, false); });
            return;
        }

        if (option === '@InvoiceSaveType.SaveAndPrint'
            && $("#FiscalStatus").val() !== "@FiscalStatus.Fiscalized"
            && "@PantheonRA.BackOffice.CurrentUser.Localization" !== "@Localization.Code.HR"
            && new Date($("#InvoiceDate").datepicker("getDate").setHours(0, 0, 0, 0)).valueOf() < new Date().setHours(0, 0, 0, 0).valueOf()
            && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")) {

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

            return;
        }

        let isFormClean = $("#WholesaleForm").customDirtyChecker("check");
        if (isFormClean)
            save(option, printType, fiscalize);
        else if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && $(".advPayConn").length > 0) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.DocumentIsConnectedWithAdvancePaymentCannotChangeData",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.OK',
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else if (option === '@InvoiceSaveType.SaveAndPreview')
            previewPrintClick(option, printType, fiscalize);
        else if (openStatus === '@WholesaleStatus.Confirmed' && $("#FiscalStatus").val() !== "@FiscalStatus.Fiscalized") {
            $().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 () {
                            $("#WholesaleForm").customDirtyChecker();
                            await save(option, printType, fiscalize);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else
            save(option, printType, fiscalize);
    }

    function previewPrintClick(option, printType, fiscalize) {
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: "@Loc.ConfirmSaveChangesMessage",
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: '@Loc.No',
                    action: async function () {
                        printWindow = createPrintWindow(printWindow);
                        handleSaveOption(option, printType, fiscalize);
                    },
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: '@Loc.Yes',
                    action: async function () {
                        await save(option, printType, fiscalize);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }

    var printWindow;
    async function save(option, printType, fiscalize) {
        if (hasUnfiscalizedInvoice) {
            hasUnfiscalizedInvoiceErrorDisplay();
            return;
        }

        if ($('input.numberInput.error-input-item')[0]) return;

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

        if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.ME" && $("#ReceiverId").val() && $("#WayOfSale").val() !== "@WayOfSale.ExportSale") {
            var pibExists = await checkSubjectPIB($("#ReceiverId"));
            if (!pibExists) {
                swapLoadingIcon(false, "saveButton", "fa fa-save");
                swapLoadingIcon(false, "printButton", "fa fa-print");
                return;
            }
        }

        if ((option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') &&
            ("@PantheonRA.BackOffice.CurrentUser.Localization" !== "@Localization.Code.RS" ||
                ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" &&
                    (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "False" || $("#CanFiscalize").val() === "False") ||
                        (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True") &&
                            !invoiceItems.some(s => s.VATFiscalCode === "" || !s.VATFiscalCode)))))) {
            printWindow = createPrintWindow(printWindow);
        }

        if ($("#IsTaxPeriodLocked").val() === "True" ||
            ((option === '@InvoiceSaveType.SaveAndPrintOrderForm' || option === '@InvoiceSaveType.SaveAndPreview')
            && $("#AcKey").val()
            && $("#Status").val() !== '@VerifyStatus.NotConfirmed'
            && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")
            && $("#FiscalCode").val())) {
            await handleSaveOption(option, printType, fiscalize);
            return;
        } else if ((option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview')
            && $("#PaymentMethodId").val()
            && $("#AcKey").val()
            && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")
            && ($("#FiscalCode").val() || $("#FiscalNumber").val())) {

            if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS"
                && option === '@InvoiceSaveType.SaveAndPrint'
                && $("#DocTypeSelect option:selected").attr("data-fiscTraining") === "True") {

                if (printWindow) {
                    printWindow.close();
                }

                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.PrintingCopyNotAllowed",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Confirm',
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                swapLoadingIcon(false, "saveButton", "fa fa-save");
                swapLoadingIcon(false, "printButton", "fa fa-print");
                return;
            }

            if (option === '@InvoiceSaveType.SaveAndPrint' && $("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.WhenPrinting" && $(".advPayConn").length === 0) {
                moveAdvancePaymentLinks(true, option, fiscalize, printType);
            } else {
                await handleSaveOption(option, printType, fiscalize);
            }
            return;
        }

        $("#Statement").val($("#Statements").val() ? $("#Statements").val().toString() : "");
        var formData = new FormData($("#WholesaleForm")[0]);

        if ($("#FiscalNumber").val()) {
            formData.append('AcKey', $("#AcKey").val());
            formData.append('FiscalNumber', $("#FiscalNumber").val());
        }

        formData.append('InvoiceItemsJsonString', JSON.stringify(invoiceItems));
        formData.set('Note', encodeURIComponent($("#Note").val()));
        formData.set('FxRate', formatDisplay($("#FxRate").attr("step"), $("#FxRate").val(), true));


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

        await fetch(url, {
            method: "POST",
            body: formData
        }).then((response) => response.json()
        ).then(async (response) => {
            if (response.Success) {
                if (!$("#AcKey").val()) {
                    setInvoiceCreatedData(response);
                }

                if (response.data.DocMoveConnections && response.data.DocMoveConnections.length > 0) {
                    for (var i = 0; i < response.data.DocMoveConnections.length; i++) {
                        addConnection(
                            response.data.DocMoveConnections[i].AcKey,
                            response.data.DocMoveConnections[i].Price,
                            response.data.DocMoveConnections[i].TypeOfDocument,
                            response.data.DocMoveConnections[i].AcKeyDisplay
                        );
                    }
                }


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

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

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

                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 () {
                                    await handleSaveOption(option, printType, fiscalize);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else if (errorText !== '') {
                    if (printWindow) {
                        printWindow.close();
                    }

                    $("#errorModalMessage").text(errorText);
                    $("#errorModal").modal('show');
                } else {
                    if (option === '@InvoiceSaveType.SaveAndPrint' && $("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.WhenPrinting" && $("#hasAdvancePayments").val() === "false")
                        moveAdvancePaymentLinks(true, option, fiscalize, printType);
                    else {
                        await handleSaveOption(option, printType, fiscalize);
                    }
                }
            } else {
                if (printWindow) {
                    printWindow.close();
                }

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

                if (option === '@InvoiceSaveType.SaveAndCheckForSerials' && invoiceItems.length > 0) {
                    $("#quantity-" + invoiceItems[invoiceItems.length - 1].AnNo).val(0);
                    formatNumberInput($("#quantity-" + invoiceItems[invoiceItems.length - 1].AnNo));
                }

                if (option === '@InvoiceSaveType.SaveAndPrint' && !$("#PaymentMethodId").val())
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.PaymentMethodIsRequired",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });

                clearValidationErrors();
                displayErrors(response);

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

    async function handleSaveOption(option, printType, fiscalizeFormReport) {
        if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR"
            && $("#WayOfSale").val() === "Z"
            && $("#PaymentMethodId option:selected").attr("data-fiscalize") === "G"
            && toNumber($("#ToPayAmountOurCurrency").text()) > 700
            && !$("#FiscalCode").val()) {

            if (printWindow)
                printWindow.close();
            $("#changePaymentTypeIrisModal").attr('onclick', 'focusElement("#PaymentMethodId")');
            $("#iris1006038Modal").modal("show");
            setIdentsPriceForValue();

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

            return;
        }

        var fiscalize = false;
        if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True") {
            fiscalize = true;
        }

        if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR") {
            if ($("#PaymentMethodId option:selected").attr("data-fiscalize") === "T")
                fiscalize = false;
            if ($("#DocTypeSelect option:selected").attr("data-fiscAll") === "True")
                fiscalize = true;
        }

        if (option === '@InvoiceSaveType.SaveAndPreview') {
            fiscalize = false;
        }

        if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
            if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.ME"
                && invoiceItems.find(ident => ident.MeasurementUnit === "") !== undefined) {
                var ident = invoiceItems.find(ident => ident.MeasurementUnit === "");

                if (printWindow) {
                    printWindow.close();
                }

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.FiscalizationFailedIdentWithoutMeasUnit",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            action: function () {
                                $("#measurementUnit-" + ident.AnNo).focus().select();
                            },
                            type: 'primary'
                        }
                    ]
                });

                if (printWindow) printWindow.close();

                return;
            }
            if (printType === '@PaperSizeType.mm58' || printType === '@PaperSizeType.mm80') {
                printWindow.location = $('#PrintPreview').data('url') + "?id=" + $("#AcKey").val() + "&paperSize=" + paperSize + "&fiscalize=" + fiscalize
                    + "&ignoreCopy=" + (!($("#FiscalNumber").val() && $("#FiscalCode").val()) ? true : false);
                printWindow.focus();

                $(printWindow).ready(function () {
                    location.reload();
                });
            } else {
                if (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True") &&
                    "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && invoiceItems.some(s => s.VATFiscalCode === "" || !s.VATFiscalCode)) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: "@Loc.AllTaxesNeedFiscalCode",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                    return;
                }

                if (printWindow && printWindow.closed)
                    printWindow = createPrintWindow(printWindow);

                let pinUrlLpfr = $("#DocTypeSelect option:selected").attr("data-pinUrlLpfr");
                await printPAAS((printType ? printType : $("#DefaultReport").val()), (fiscalize && fiscalizeFormReport), option === '@InvoiceSaveType.SaveAndPreview', undefined, undefined, undefined, undefined, clientSignature,
                    '@Url.Action("LPFRUpdateInvoice", "Move")', pinUrlLpfr && $("#FiscalStatus").val() === "4" ? "@Url.Action("GetLpfrFiscalizationData", "Move")" + "?acKey=" + $("#AcKey").val() : undefined);
            }
        } else if (option === '@InvoiceSaveType.SaveAndNew') {
            window.location.href = '@Url.Action("Create", "Wholesale")';
        } else if (option === '@InvoiceSaveType.SaveAndClose') {
            window.location.href = '@Url.Action("Index", "Wholesale")';
        } else if (option === '@InvoiceSaveType.SaveAndPrintOrderForm') {
            let printWindow = window.open('');
            printWindow.location = $('#PrintOrderFormUrl').data('url') + "?id=" + $("#AcKey").val() + "&paperSize=" + paperSize;
            printWindow.focus();

            $(printWindow).ready(function () {
                location.reload();
            });
        } else if (option === '@InvoiceSaveType.SaveAndChangeCurrency') {
            changeMoveCurrency();
        } else if (option === '@InvoiceSaveType.SaveAndChangeFxRate') {
            changeFxRate();
        } else if (option === '@InvoiceSaveType.SaveAndAddIdent' || option === '@InvoiceSaveType.SaveAndCheckForSerials') {
            if ($("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.OnSubjectChange" && invoiceItems.length === 1 && $(".advPayConn").length === 0)
                moveAdvancePaymentLinks(true);

            setIdentsPriceForValue(true);
        } else if (option === '@InvoiceSaveType.SaveAndCreateDocument') {
            $("#uploadFiles").click();
        } else {
            setIdentsPriceForValue();
        }
    }

    function setInvoiceCreatedData(response) {
        $("#Qid").val(response.data.Qid);
        $("#AcKey").val(response.data.AcKey);
        $("#AcKeyDisplay").val(response.data.AcKeyDisplay);
        refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
        $("#Protocol").val(response.data.Protocol);
        $("#Reference").val(response.data.Reference);
        $("#OrderForm").val(response.data.OrderForm);
        $("#invoiceDelete").removeClass("hidden");
        $("#cancelInvoice").removeClass("hidden");
        //$(".sendXmlOption").removeClass("hidden"); TODO: Hidden until we have E-Invoices
        $("#newInvoiceButton").removeClass("hidden");
        $("#invoiceDuplicate").removeClass("hidden");
        $("#Referent").val(response.data.Referent);
        $("#DocTypeSelect").attr("disabled", true);
        window.history.pushState({}, null, '@Url.Action("Edit", "Wholesale")?id=' + response.data.AcKey);
        clearValidationErrors();
        $(".preview-btn").closest("li").removeClass("hidden");
        $("#additionalFuncButton").removeClass("hidden");
        $("#additionalFuncButton + button").removeClass("hidden");
        $("#wizardButton").attr("disabled", false);
        $("#wizardButton + button").attr("disabled", false);
        enableUploadFiles();
    }

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

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

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

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

                $("#invoice").customDirtyChecker();
                $(".document-footer").customDirtyChecker();
            }, "json");
    }

    var subjectType;
    function openSubjectModal(subject) {
        clearValidationErrors();
        $('#subjectModal form')[0].reset();
        subjectType = subject;

        var id;
        if (subject === "Receiver") {
            id = $("#Receiver").val();
        } else
            id = $("#ThirdParty").val();

        setSearchSubjectData(id);
        $("#subjectModal").modal('show');
    }

    function saveSubject() {
        var formData = $("#subjectForm").serializeArray();
        formData.push({ name: 'SubjectEditData.BankAccountsJsonString', value: JSON.stringify(subjectBankAccounts) });

        $.post('@Url.Action("CreateFromPartial", "Subjects")', formData)
            .done(function (response) {
                if (response.Success) {
                    createSubjectSetValues("Receiver", response.subject.Id);
                    createSubjectSetValues("ThirdParty", 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 showFiscalData() {
        let fiscalNumber = $("#FiscalNumber").val();
        let fiscalCode = $("#FiscalCode").val();
        let canFiscalize = $("#CanFiscalize").val() === "True" || $("#CanFiscalize").val() === "true";

        if (canFiscalize && (fiscalNumber.length > 0 || fiscalCode.length > 0)) {
            $(".fiscalizeData").removeClass("hidden");
        } else {
            $(".fiscalizeData").addClass("hidden");
        }
    }

    function checkFormEditable() {
        if ($("#FiscalStatus").val() > 1 || $("#IsTaxPeriodLocked").val() === "True") {
            $("#WholesaleForm :input").prop("disabled", true);
            $("#WholesaleForm :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);
            $("#invoiceDuplicate").prop("disabled", false);
            $("#wizardButton").prop("disabled", false);
            $("#wizardButton + button").prop("disabled", false);
            $("#additionalFuncButton").prop("disabled", false);
            $("#additionalFuncButton + button").prop("disabled", false);
            $(".identNote").prop("disabled", false);
            $(".noteModalBtn").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");
                }
            }
            disableCreateNewButtons();
        }

        if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True") {
            $("#CanFiscalize").val(true);
            $("#wholesaleFormDocumentBody").addClass("table-has-fiscal-data");
        } else {
            $("#CanFiscalize").val(false);
            $("#wholesaleFormDocumentBody").removeClass("table-has-fiscal-data");
        }

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

        if ($("#AcKey").val() && $("#IsCanceled").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");
                }

                if ($("#FiscalStatus").val() === "1")
                    numberInputs[i].disabled = false;
            }
        }
    }

    function enableForm() {
        $("#WholesaleForm :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.Cancel',
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: '@Loc.CancelInvoice',
                    action: async function () {
                        location.href = '@Url.Action("Cancel", "Wholesale")?acKey=' + $("#AcKey").val();
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }

    function setIdentsPriceForValue(checkForSerials = false) {
        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++) {
                $("#priceForValue-" + data[i].AnNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].PriceForValue));
                $("#retailPrice-" + data[i].AnNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].RTPrice));

                if (formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].TotalPrice) !== $("#totalPrice-" + data[i].AnNo).val())
                    $("#totalPrice-" + data[i].AnNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].TotalPrice));
            }

            swapLoadingIcon(false, "add-position", "fa fa-plus");
            if (checkForSerials === true && data && data.length > 0)
                checkIdentSerialNoIssue(data[data.length - 1].AnNo, "M", data[data.length - 1].SerialNo, data[data.length - 1].Quantity);
            checkIfTaxReverseItemsExist();
        }, "json");
    }

    function checkIfTaxReverseItemsExist() {
        swapLoadingIcon(true, "add-position", "fa fa-plus");
        $.post('@Url.Action("CheckForMoveTaxReverseItems", "Wholesale")', {
            AcKey: $("#AcKey").val(),
            DocType: $("#DocType").val(),
            Currency: $("#Currency").val(),
            InvoiceCurrency: $("#Currency").val(),
            RoundItem: $("#RoundTSetting").val(),
            RoundValue: $("#RoundValueSetting").val(),
        }).done(function (response) {
            if (response && (response.Error == "" || !response.Error)) {
                $("#ForPay76a").val(response.ForPay76aOnly);
                formatNumberInput($("#ForPay76a"));
                showForPay76a(true);
            } else {
                showForPay76a(false);
            }
            swapLoadingIcon(false, "add-position", "fa fa-plus");
            checkFormEditable();
        }).fail(function () {
            showForPay76a(false);
            swapLoadingIcon(false, "add-position", "fa fa-plus");
            checkFormEditable();
        });
    }

    function sendXML() {
        swapLoadingIcon(true, "printButton", "fa fa-plus");
        swapLoadingIcon(true, "saveButton", "fa fa-plus");

        $.get('@Url.Action("CreateInvoiceXML", "Wholesale")?acKey=' + $("#AcKey").val() + "&docType=" + $("#DocType").val(), function (response) {
            if (!response.AcKey || response.AcKey === "")
                $("#errorModalMessage").text('@Loc.ErrorSendingEInvoice');
            else
                $("#errorModalMessage").text('@Loc.SuccessSendingEInvoice');

            $("#errorModal").modal('show');

            swapLoadingIcon(false, "printButton", "fa fa-plus");
            swapLoadingIcon(false, "saveButton", "fa fa-plus");
        }, "json");
    }

    function onClickPreview() {
        location.href = '@(Url.Action("PrintPreview", "Wholesale") + "?returnUrl=" + Url.Encode(Url.Action("Edit", "Wholesale", new { id = Model.AcKey })))&id=' + $("#AcKey").val();
    }

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

    function openDmsDoc(ackey) {
        location.href = '@Url.Action("Edit", "Documents")?id=' + ackey;
    }

    function openDocMoveConnection(ackey, moveType = null) {
        if (moveType && moveType === "@InvoiceType.POS")
            location.href = '@Url.Action("Index", "CashRegister")?acKey=' + ackey;
        else
            location.href = '@Url.Action("Edit", "Wholesale")?id=' + ackey;
    }

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

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

        setNoteIcon();

        if ($("#FiscalStatus").val() > 1 || $("#IsTaxPeriodLocked").val() === "True") {
            saveNotePost($("#Note").val(), null);
        }
    }

    function saveNotePost(note, anNo) {
        $().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 () {
                        $.post('@Url.Action("SaveNote", "Move")', {
                            AcKey: $("#AcKey").val(),
                            Note: note,
                            AnNo: anNo
                        }).done(function (response) {
                            if (response && response !== true) {
                                $().customModal({
                                    destroyOnClose: true,
                                    showCloseButton: true,
                                    type: "alert",
                                    text: "@Loc.GeneralError",
                                    buttons: [
                                        {
                                            icon: 'fa fa-check',
                                            text: "@Loc.Confirm",
                                            closeOnAction: true,
                                            type: 'primary'
                                        }
                                    ]
                                });
                            }
                        });
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }


    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,
                        id: "docTypeNoFiscPaymentMethodCashWarningModal",
                        type: "alert",
                        text: "@Loc.DocTypeNoFiscPaymentMethodCashError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                action: function () {
                                    resetPaymentMethod();
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
        }
    }

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

    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("EditReceivingAdvancePayment", "AdvancePayment")" + "?id=" + acKey;
    }

        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
                removeWholesale();
        });
    }

    function removeWholesale() {
        $.get("@Url.Action("Remove", "Wholesale")" + "?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("Index", "Wholesale")";
        });
    }

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

    function openCashDocumentWarningHelp() {
        window.open('@Loc.CashReceiptOrExpenditureHelpUrl', '_blank');
    }

    function continueDelete() {
        if (canDeleteResponse && canDeleteResponse.HasConnectedCredit != true) {
            if (canDeleteResponse.IsLastDoc == false) {
                showDeleteNotLastDocModal();
            } else if (canDeleteResponse.HasConnectedSummaryDocument == true) {
                $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                $("#deleteInternalDocWarningModal").modal('show');
                $("#continueDeleteInternalDoc").attr("onclick", "deleteWithInternalDoc()");
                $("#cancelDeleteInternalDocument").attr("onclick", "");
            } else
                removeWholesale();
        } 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
            removeWholesale();
    }

    function deleteWithInternalDoc() {
        removeWholesale();
    }

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

    function onCreateCashDocument() {
        var payMethodFiscGroup = $("#PaymentMethodId option:selected").attr("data-setOf");

        if ((payMethodFiscGroup !== "@PaymentType.Cash"
            && "@PantheonRA.BackOffice.CurrentUser.Localization" !== "@Localization.Code.HR") ||
            ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR"
                && payMethodFiscGroup !== "@PaymentType.Cash"
                && $("#ReceiverSuppSaleMet").val() === "@WayOfSale.R2")) {
            $("#cashRegReceiptExpenditureWarningModal").modal('show');
        } else {
            openCreateCashDocumentModal();
        }
    }

    function continueCreateCashDocument() {
        openCreateCashDocumentModal();
    }

    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 openCreateCashDocumentModal() {
        $("#createCashDocumentPay").attr("step", $("#DefaultDecimalPlacesPrice").val());
        $("#createCashDocAlreadyPaid").attr("step", $("#DefaultDecimalPlacesPrice").val());
        $("#createCashDocCashRegister").attr("step", $("#DefaultDecimalPlacesPrice").val());
        $("#createCashDocLeftToPay").attr("step", $("#DefaultDecimalPlacesPrice").val());
        $("#CreateCashDocumentDocType").val($("#DocTypeSelect option:selected").attr("data-cashReg"));
        $("#CreateCashDocumentCurrency").val($("#Currency").val());

        $("#createCashDocumentModal").modal('show');
        $.get("@Url.Action("CashRegCalcPayed", "Wholesale")" + "?acKey=" + $("#AcKey").val(), function (response) {
            if (response != null) {
                var leftToPay = response.ForPay - response.PaidAndCredited - response.PaidCashReg - response.PaidAvans - response.CreditedAvans;
                $("#createCashDocumentPay").val(leftToPay > 0 ? formatElementText(leftToPay) : 0);
                $("#createCashDocForPay").text(formatDisplay($("#DefaultDecimalPlacesPrice").val(), response.ForPay) + " @Model.Currency.ToUpper()");
                $("#createCashDocAlreadyPaid").val(response.PaidAndCredited + response.PaidCashReg);
                $("#createCashDocCashRegister").val(response.PaidCashReg);
                $("#createCashDocLeftToPay").val(leftToPay);
                formatNumberInput($("#createCashDocumentPay"));
                formatNumberInput($("#createCashDocAlreadyPaid"));
                formatNumberInput($("#createCashDocCashRegister"));
                formatNumberInput($("#createCashDocLeftToPay"));
            }
        });
    }

    function createCashRegDocument() {
        var model = {
            AcKey: $("#AcKey").val(),
            DocTypeCR: $("#CreateCashDocumentDocType").val(),
            Type: "@CashRegCalcDocType.Wholesale",
            PaymentType: $("#PaymentMethodId").val(),
            Name: $("#DocTypeSelect option:selected").text().trim(),
            CurrencyCashReg: $("#CreateCashDocumentCurrency").val(),
            Date: $("#CreateCashDocumentDate").val(),
            PaymentType: $("#PaymentMethodId").val(),
            LeftToPay: toNumber($("#createCashDocForPay").text()),
            ToPay: toNumber($("#createCashDocumentPay").val())
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("CashRegCreFromMove", "Wholesale")',
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.AcKey) {
                showCashRegPayments();
            }
        });
    }

    function showCashRegPayments() {
        $.post('@Url.Action("CashRegPaymentsList", "CashRegister")', {
            id: $("#AcKey").val()
        }).done(function (items) {
            if (!$("#PaymentMethodId").val() || $("#PaymentMethodId").val() === "") {
                showPaymentMethodRequiredModal();
            } else if (!items || items.length === 0) {
                onCreateCashDocument();
            } else {
                $cashDocDataTable = $('#cashDocumentsGrid');
                if ($.fn.dataTable.isDataTable('#cashDocumentsGrid'))
                    $cashDocDataTable.DataTable().destroy();

                $cashDocDataTable.DataTable({
                    serverSide: false,
                    ajax: undefined,
                    scroller: false,
                    responsive: false,
                    paging: false,
                    info: false,
                    data: items,
                    columns: [
                        {
                            data: "AcKeyDisplay", render: function (data, type, full) {
                                return "<a href='@Url.Action("Index", "CashTransactions")??type=P&acKey=" + full.AcKey + "' target='_blank'>" + data + "</a>";
                            }
                        },
                        { data: "AnNo", render: $.fn.dataTable.render.link("Receiver") },
                        { data: "Name" },
                        { data: "PayMethod" },
                        { data: "Acct" },
                        { data: "Amount", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
                        { data: "Currency" }
                    ]
                });

                $("#cashDocumentListModal").modal('show');
            }
        });
    }

    async function beforeShowCashRegPayments() {
        var hasOpenAdvPayments = await hasOpenAdvancePayments();

        if ($("#hasAdvancePayments").val() === "false" && hasOpenAdvPayments === true)
            moveAdvancePaymentLinks(true, null, null, null, "showCashRegPayments()");
        else
            showCashRegPayments();
    }

    function onCreateCommission() {
        $("#createCommissionModal").modal('show');
    }

    initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#CommissionSupplier'), $("#CommissionSupplier"));

    function browseCommissions() {
        var showError = false;
        var errorMsg = "";
        var $focusElement;

        if (!$("#CommissionCreateDate").val()) {
            showError = true;
            errorMsg = "@Loc.CommissionCreateDateRequired";
            $focusElement = $("#CommissionCreateDate");
        } else if (!$("#CommissionDateFrom").val() || !$("#CommissionDateTo").val()) {
            showError = true;
            errorMsg = "@Loc.CommissionDateFromToRequired";
            if (!$("#CommissionDateFrom").val())
                $focusElement = $("#CommissionDateFrom");
            else
                $focusElement = $("#CommissionDateTo");
        } else if (!$("#CommissionSaleDocTypes").val()) {
            showError = true;
            errorMsg = "@Loc.CommissionDocTypeSaleRequired";
            $focusElement = $("#CommissionSaleDocTypes");
        }

        if (showError === true) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                id: "commissionDocTypeAndDateRequiredModal",
                type: "alert",
                text: errorMsg,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        action: function () { $focusElement.focus(); },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            var model = {
                SupplierId: $("#CommissionSupplier").val(),
                SaleDocTypes: $("#CommissionSaleDocTypes").val() != null ? $("#CommissionSaleDocTypes").val().toString() : "",
                DateFrom: $("#CommissionDateFrom").val(),
                DateTo: $("#CommissionDateTo").val(),
                CreateDate: $("#CommissionDateTo").val(),
                CreateDocType: $("#CommissionCreateDocType").val()
            };

            $.ajax({
                type: "POST",
                data: JSON.stringify(model),
                url: '@Url.Action("CommissionCheckPrepareData", "Wholesale")',
                contentType: "application/json"
            }).done(function (response) {
                if (response && response.Success) {
                    refreshCommissionTable(response.Commissions);
                    $("#commissionTableContainer").removeClass("invisible");
                }
            });
        }
    }

    function refreshCommissionTable(commissionItems) {
        $commissionDataTable = $('#commissionsGrid');
        if ($.fn.dataTable.isDataTable('#commissionsGrid'))
            $commissionDataTable.DataTable().destroy();

        $commissionDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            data: commissionItems,
            columns: [
                { data: "Supplier" },
                { data: "AcKeyView" },
                { data: "Ident" },
                { data: "Name" },
                { data: "Quantity", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
                { data: "MeasUnit" }
            ]
        });

        if (commissionItems.length > 0) {
            $("#createCommissionBtn").prop("disabled", false);
            $("#placeholderCommissions").addClass("hidden");
        }
    }

    function createCommissionDocument() {
        var model = {
            SupplierId: $("#CommissionSupplier").val(),
            SaleDocTypes: $("#CommissionSaleDocTypes").val() != null ? $("#CommissionSaleDocTypes").val().toString() : "",
            DateFrom: $("#CommissionDateFrom").val(),
            DateTo: $("#CommissionDateTo").val(),
            CreateDate: $("#CommissionDateTo").val(),
            CreateDocType: $("#CommissionCreateDocType").val()
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("CreateCommission", "Wholesale")',
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.Success) {
                if (response.AcKey)
                    window.location.href = "@Url.Action("Edit", "Wholesale")?id=" + response.AcKey;
                else
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "errorCreateCommissionModal",
                        type: "alert",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            }
        });
    }

    function getDeliveryFillType() {
        $.get("@Url.Action("Get", "SetFillSales")", function (response) {
            var deliveryType = response.AcDelivery.toString();

            if (response && deliveryType) {
                if (deliveryType === "@DeliveryFillType.FirstPerson") {
                    if (receiverTypeaheadData && receiverTypeaheadData.delivery)
                        $("#DeliveryType").val(receiverTypeaheadData.delivery);
                    else
                        getSubjectDeliveryType($("#ReceiverId").val());
                } else if (deliveryType === "@DeliveryFillType.ThirdPerson") {
                    if (thirdPartyTypeaheadData && thirdPartyTypeaheadData.delivery)
                        $("#DeliveryType").val(thirdPartyTypeaheadData.delivery);
                    else
                        getSubjectDeliveryType($("#ThirdPartyId").val());
                }
            }
        });
    }

    function getSubjectDeliveryType(id) {
        $.get("@Url.Action("GetSubjectById", "Subjects")?subjectId=" + id, function (response) {
            if (response && response.Delivery)
                $("#DeliveryType").val(response.Delivery);
        });
    }

    async function hasOpenAdvancePayments() {
        var model = {
            Subject: $("#ReceiverId").val(),
            DocType: $("#DocType").val(),
            AcKey: $("#AcKey").val(),
            Date: new Date($("#Date").datepicker("getDate")).toISOString(),
            VAT: "",
            Type: "O",
            InvoiceType: '@AdvancePaymentMoveLinksType.Wholesale'
        };

        return new Promise((resolve, reject) => {
            $.ajax({
                type: "POST",
                data: JSON.stringify(model),
                url: '@Url.Action("MoveAdvancePaymentLinks", "AdvancePayment")',
                contentType: "application/json"
            }).done(function (response) {
                if (response && response.length > 0)
                    resolve(true);
                else
                    resolve(false);
            });
        });
    }

    function moveAdvancePaymentLinks(showModal, option, fiscalize, printType, continueFunction) {
        var model = {
            Subject: $("#ReceiverId").val(),
            DocType: $("#DocType").val(),
            AcKey: $("#AcKey").val(),
            Date: new Date($("#Date").datepicker("getDate")).toISOString(),
            VAT: "",
            Type: "O",
            InvoiceType: '@AdvancePaymentMoveLinksType.Wholesale'
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("MoveAdvancePaymentLinks", "AdvancePayment")',
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0 && (!option || response.some(x => x.Marked === "@ActiveStatus.Inactive"))) {
                $("#MoveAdvancePaymentLinksType").val('@AdvancePaymentMoveLinksType.Wholesale');
                $("#MoveAdvancePaymentLinksSubject").val($("#ReceiverId").val());
                $("#MoveAdvancePaymentLinksInvoiceDate").val($("#Date").val());
                $("#subjectHasOpenAdvancePaymentsMsg").text("@Loc.BuyerHasOpenAdvancePayments");
                $("#subjectOnOpenMsg").text("@Loc.BuyerOnDocumentHasOpenAdvancePayments");
                refreshMoveAdvancePaymentLinksTable(response);

                $('#advancePaymentCreatedContinueOpenOrPrint').removeAttr('onclick');
                if (option)
                    $('#advancePaymentCreatedContinueOpenOrPrint, #advancePaymentContinueOpenOrPrint').on('click', function () {
                        if (($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True") &&
                            "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && invoiceItems.some(s => s.VATFiscalCode === "" || !s.VATFiscalCode)) {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "alert",
                                text: "@Loc.AllTaxesNeedFiscalCode",
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Confirm",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                            return;
                        }
                        printWindow = createPrintWindow(printWindow);
                        handleSaveOption(option, printType, fiscalize);
                    });

                if (showModal) {
                    if (continueFunction)
                        $('#advancePaymentContinueOpenOrPrint').attr('onClick', continueFunction);

                    $("#moveAdvancePaymentLinksOpenWarningModal").modal('show');
                } else
                    $("#moveAdvancePaymentLinksModal").modal('show');

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

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

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

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

    var currencyCalcType;
    function recalculateMovePrices(type) {
        currencyCalcType = type;
        save("@InvoiceSaveType.SaveAndChangeCurrency");
    }

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

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

        var model = {
            AcKey: $("#AcKey").val(),
            Currency: $("#Currency").val(),
            OldCurrency: $("#OldCurrency").val(),
            Type: currencyCalcType,
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("MoveCurrencyChange", "Currency")',
            contentType: "application/json"
        }).done(function (response) {
            if (response) {
                swapLoadingIcon(true, "add-position", "fa fa-plus");
                $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val()
                    + "&subject=" + $("#ReceiverId").val()
                    + "&subjectType=" + $("#WayOfSale").val()
                    + "&saleType=P",
                    function (data) {
                        $("#OldCurrency").val($("#Currency").val());
                        invoiceItems = [];

                        for (var i = 0; i < data.length; i++) {
                            setRounding(data[i].AnNo);

                            data[i].TaxPrice = data[i].VATPrice;
                            invoiceItems.push(data[i]);

                            $("#price-" + data[i].AnNo).val(data[i].Price);
                            formatNumberInput($("#price-" + data[i].AnNo));
                            changeIdentData(data[i].AnNo);
                        }

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

    function setRounding(anNo) {
        if (anNo) {
            if ($("#CompanyCurrency").val() !== $("#Currency").val()) {
                $("#totalPrice-" + anNo).attr("data-round", $("#RoundTfc").val());
                $("#basisForTax-" + anNo).attr("data-round", $("#RoundTfc").val());
                $("#taxPrice-" + anNo).attr("data-round", $("#RoundTfc").val());
                return $("#RoundTfc").val();
            } else {
                $("#totalPrice-" + anNo).attr("data-round", $("#RoundT").val());
                $("#basisForTax-" + anNo).attr("data-round", $("#RoundT").val());
                $("#taxPrice-" + anNo).attr("data-round", $("#RoundT").val());
                return $("#RoundT").val();
            }
        } else
            if ($("#CompanyCurrency").val() !== $("#Currency").val())
                return $("#RoundTfc").val();
            else
                return $("#RoundT").val();
    }

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

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

        var model = {
            AcKey: $("#AcKey").val(),
            FxRate: $("#FxRate").val(),
            Date: new Date($("#Date").datepicker("getDate")).toISOString(),
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("ChangeInvoiceFxRate", "Currency")',
            contentType: "application/json"
        }).done(function (response) {
            if (response) {
                $(".ToPayAmount").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(response.ForPay, $("#RoundValue").val())));
                $("#ToPayAmountOurCurrency").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(response.ValueInOurCurrency, $("#RoundValueOc").val())));
                swapLoadingIcon(false, "saveButton", "fa fa-save");
                swapLoadingIcon(false, "printButton", "far fa-print");
            }
        });
    }

    function openUnconfirmedBills() {
    window.location.href = "@Url.Action("IssuedBillsBilling", "Wholesale")?showUnconfirmedBills=" + true + "&docType=" + $("#DocType").val() + "&acKey=" + $("#AcKey").val();
    }

    function checkDeposit() {
        if ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" && $("#DocTypeSelect option:selected").attr("data-isInitialized") === "False" &&
            ($("#PaymentMethodId").val() === "1" || $("#PaymentMethodId  option:selected").attr("data-fiscalize") === '@PantheonRA.WebApi.Contracts.Enums.FiscalGroupMnType.Banknote')) {
            openDepositModal("I", $("#DocTypeSelect option:selected").attr("data-fiscalWorkplaceId"),
                '@Model.Currency', '@Loc.DepositInput', '@Loc.Value', '@Url.Action("Register", "Deposit")', '@Loc.Error', '@Loc.OK', '@Loc.Cancel',
                () => {
                    $("#DocTypeSelect option:selected").attr("data-isInitialized", "True");
                });
        }
    }

    function startConnectDocWizardModal() {
        $("#MoveConnectionType").val('@DtType.Wholesale');
        $("#MoveConnectAcKey").val($("#AcKey").val());
        $("#MoveConnectAcKeyDisplay").val($("#KeyDisplayValue").text());
        $("#MoveConnectSubject").val($("#ReceiverId").val());
        $("#MoveConnectThirdParty").val($("#ThirdPartyId").val());
        openConnectDocWizardModal();
    }

    let clientSignature;
    function openSignatureForm(onAfterSigned) {
        openCustomSignature('@Loc.Signature',
            '@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.SignatureWizard)',
            { signAgain: '@Loc.SignAgain', cancel: '@Loc.Cancel', confirm: '@Loc.Confirm' },
            (signature) => { clientSignature = signature; onAfterSigned(); }
        );
        }

    function movePosting(acKey) {
        $.ajax({
            url: $("#UrlMoveStatus").val(),
            dataType: 'json',
            data: { acKey: acKey },
            method: "GET",
            success: function (data) {
                if (data.Status) {
                    startMovePosting(acKey);
                }
                else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: $("#MovePostingNotConfirmed").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            },
            fail: function (error) {
                swal(error);
            }
        });
        }

    function startMovePosting(acKey) {
        $.ajax({
            cache: false,
            type: "GET",
            url: $("#UrlMovePosting").val(),
            data: {
                moveAcKey: acKey
            },
            success: function (data) {
                serveMovePostingResponse(data);
            },
            error: function (error) {
                swal($("#GeneralErrorMessage").val() + error);
            }
        });
    }

    function serveMovePostingResponse(data) {
        if (data.IsSuccess) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "success",
                    text: '@Loc.MovePostingSuccess' + '<br><br>' + data.AcKeyView,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        else if (data.IsNonConfirmed) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: $("#MovePostingNotConfirmed").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        else if (data.HasErrors) {
                let errors = '@Loc.MovePostingFailed' + '<br><br>';

                for (let i = 0; i < data.Errors.length; i++) {
                    errors += (data.Errors[i].Ident + ': ' + data.Errors[i].Error + '<br><br>');
                }

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: errors,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#ConfirmLoc").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        }

        function hasUnfiscalizedInvoiceErrorDisplay() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.CannotCreateInvoiceIfUnfiscalizedExists",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.OK',
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function duplicateInvoice() {
            $.ajax({
                url: "@Url.Action("DuplicateInvoice", "Move")",
                dataType: 'json',
                data: { acKey: $("#AcKey").val() },
                method: "GET",
                success: function (data) {
                    if (data.Success && data.AcKey) {
                        window.location.href = "@Url.Action("Edit", "Wholesale")?id=" + data.AcKey;
                    } else {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: data.Error ? data.Error : "@Loc.GeneralError",
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#ConfirmLoc").val(),
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }
                },
                fail: function (error) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
        }

        function setIdentPrices() {
            var model = {
                AcKey: $("#AcKey").val(),
                Type: "I",
                Subject: $("#ReceiverId").val(),
                PriceRate: $("#ReceiverPriceRate").val(),
                Warehouse: $("#IssuerId").val(),
                Currency: $("#Currency").val(),
                Date: new Date($("#Date").datepicker("getDate")).toISOString(),
                DateInv: new Date($("#InvoiceDate").datepicker("getDate")).toISOString(),
            };

            $.ajax({
                method: "POST",
                url: "@Url.Action("MoveChaPriceClass", "Move")",
                data: JSON.stringify(model),
                contentType: "application/json",
                success: function (data) {
                    if (data.IsPriceUpdated === true) {
                        if (data.Idents != null && data.Idents.length > 0) {
                            data.Idents.forEach(function (ident) {
                                if (ident.PriceOld !== ident.PriceNew) {
                                    $("#price-" + ident.AnNo).val(ident.PriceNew);
                                    formatNumberInput($("#price-" + ident.AnNo));
                                    changeIdentData(ident.AnNo);
                                    priceChanged = true;
                                }
                            });
                        }
                    }

                    updateInvoiceItemsDiscount(toNumber($("#ReceiverRebate").val()));

                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "success",
                        text: "@Loc.OperationFinished",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                },
                fail: function (error) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
        }

    function hasUnfiscalizedInvoices() {
        var data = {
            DateFrom: "@DateTime.Now.Date.AddDays(-2)",
            DateTo: "@DateTime.Now.Date",
            DocType: $("#DocType").val(),
        };

        $.post("@Url.Action("IssuedBillsUnconfirmedGetAllIds", "Reports")", { filter: data })
            .done(function (response) {
                if (response !== null && response.length > 0) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: stringFormat("@Loc.FiscErrorsForLast48Hours", response.length),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });
    }


    function changeWayOfSale() {
        swapLoadingIcon(true, "saveButton", "fa fa-save");
        swapLoadingIcon(true, "printButton", "far fa-print");
        swapLoadingIcon(true, "add-position", "fa fa-plus");

        var model = {
            AcKey: $("#AcKey").val(),
            Type: "I",
            WayOfSale: $("#WayOfSale").val(),
            Author: $("#AuthorType").val(),
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(model),
            url: '@Url.Action("MoveItemChgWayOfSale", "MoveItem")',
            contentType: "application/json"
        }).done(function (response) {
            swapLoadingIcon(false, "saveButton", "fa fa-save");
            swapLoadingIcon(false, "printButton", "far fa-print");
            swapLoadingIcon(false, "add-position", "fa fa-plus");

            if (response) {
                refreshMoveItems();
            }
        });
    }

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

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

        swapLoadingIcon(true, "add-position", "fa fa-plus");
        $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val()
            + "&subject=" + $("#ReceiverId").val()
            + "&subjectType=" + $("#WayOfSale").val()
            + "&saleType=P",
            function (data) {
                invoiceItems = [];

                for (var i = 0; i < data.length; i++) {
                    setRounding(data[i].AnNo);

                    data[i].TaxPrice = data[i].VATPrice;
                    invoiceItems.push(data[i]);

                    $("#price-" + data[i].AnNo).val(data[i].Price);
                    $("#vat-" + data[i].AnNo).val(data[i].VATCode);
                    $("#priceForValue-" + data[i].AnNo).val(data[i].PriceForValue);
                    $("#basisForTax-" + data[i].AnNo).val(data[i].BasisForTax);
                    $("#taxPrice-" + data[i].AnNo).val(data[i].TaxPrice);
                    $("#totalPrice-" + data[i].AnNo).val(data[i].TotalPrice);
                    $("#retailPrice-" + data[i].AnNo).val(data[i].RTPrice);
                    var priceRebate = data[i].Price - (data[i].Price * data[i].Rabate / 100);
                    $("#priceRebate-" + data[i].AnNo).val(priceRebate);

                    initializeNumberInputs();
                }

                updatePriceTable();
                swapLoadingIcon(false, "saveButton", "fa fa-save");
                swapLoadingIcon(false, "printButton", "far fa-print");
                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }, "json");
    }

    function addConnection(acKey, price, moveType, acKeyDisplay) {
        var connExists = $("#connections .docMoveConn a").hasClass(acKey);
        if (connExists)
            return;

        var conn =
            '<div class="form-group">' +
                '<h4 class="form-control clickable-icon connectionContainer docMoveConn" disabled>' +
                '<a class="' + acKey + '" onclick="openDocMoveConnection(\'' + acKey + '\', \'' + moveType + '\')">' +
                        acKeyDisplay +
                    '</a>' +
                    '<span class="pull-right">' + formatDisplay($("#DefaultDecimalPlacesValue").val(), price) + ' ' + $("#Currency").val() + '</span>' +
                '</h4>' +
            '</div>';

        $("#connections").append(conn);
        $("#connectionsCount").text(toNumber($("#connectionsCount").text()) + 1);
    }
</script>
}
