@using PantheonRA.WebApi.Contracts.Enums
@using PAW.Contracts.Enums
@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@using System.Web.Script.Serialization
@model OrderCreateFormData
@{
    ViewBag.Title = Loc.Invoicing;
    var dataGridId = "create-order-" + Model.DocType;
    JavaScriptSerializer oSerializer = new JavaScriptSerializer();
    var workersJson = oSerializer.Serialize(Model.Workers);
    var isInFiscalPrinterLocalization = Localization
        .IsInFiscalPrinterLocalization(PantheonRA.BackOffice.CurrentUser.DatabaseLocalization, PantheonRA.BackOffice.CurrentUser.IsInServerFiscalization);
    var fixedAssetsJson = oSerializer.Serialize(Model.FixedAssets);
    var hasB2BGranule = PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule);
    var sideTabsClass = Model.HasOrderCalendar ? "divided-tab-3" : (hasB2BGranule ? "divided-tab-1" : "divided-tab-2");
}

@Html.Hidden("MainColors", Model.MainColors)
@Html.Hidden("WorkersData", workersJson)
@Html.Hidden("FixedAssetsData", fixedAssetsJson)
@Html.Hidden("userHasB2BGranule", hasB2BGranule)

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @if (Model.OrderType == OrderType.Buyer)
        {
            @Html.Partial("_OrderBuyersTabNavigation", new Dictionary<string, bool> { { "IsOrderCalendar", Model.HasOrderCalendar }, { "IsIndexView", false } })
        }
        else
        {
            @Html.Partial("_OrderSuppliersTabNavigation", false)
        }
        <div class="tab-content">
            <form method="post" id="PageForm">
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                @Html.HiddenFor(model => model.IsVATObligee)
                @Html.HiddenFor(model => model.SelectedCountry)
                @Html.HiddenFor(model => model.OrderType)
                @Html.HiddenFor(model => model.IsObligDept)
                @Html.HiddenFor(model => model.UserDepartment)
                @Html.HiddenFor(model => model.RoundT)
                @Html.HiddenFor(model => model.RoundValue)
                @Html.HiddenFor(model => model.RoundValueOc)
                @Html.HiddenFor(model => model.RoundPrice)
                @Html.HiddenFor(model => model.FillDeptFromCostDrv)
                @Html.HiddenFor(model => model.FilterDeptForCostDrv)
                @Html.HiddenFor(model => model.CompanyCurrency)
                @Html.HiddenFor(model => model.AcctMinProfMarginOrder)
                @Html.HiddenFor(model => model.FxRateCalcOperation)
                @Html.HiddenFor(model => model.FiscalStatus)
                @Html.HiddenFor(model => model.OurCompIsName2)
                @Html.HiddenFor(model => model.FillRefFromSubj)
                @Html.HiddenFor(model => model.FillDeptFromPersonResp)
                @Html.HiddenFor(model => model.DocumentTabActive)
                @Html.HiddenFor(model => model.CalcPackQty)
                @Html.HiddenFor(model => model.ItemMethCalcUM2Qntty)
                @Html.HiddenFor(model => model.ItemUM2QnttyRound)
                @Html.HiddenFor(model => model.RoundQntty)
                @Html.HiddenFor(model => model.IsRetailSale)
                <input id="OrderCurrency" value="@Model.Currency" hidden />

                @*BUTTONS*@
                <div class="row buttons-tabbed" id="main-buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        ShowCloseBtn = false,
                        BackUrl = Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ?
                            Url.Action("BuyerOrdersReport", "Order") : Url.Action("SupplierOrdersReport", "Order"),
                        IsWizardVisible = true,
                        IsWizardDisabled = string.IsNullOrEmpty(Model.AcKey) ? true : false,
                        SaveButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Save, Icon = "far fa-print fa-lg", OnClick = "onSaveOrPrint()", Class = "hidden" },
                                new FormButton { Text = Loc.SaveAndNew, Icon = "far fa-print fa-lg", OnClick = "onSaveOrPrint('" + InvoiceSaveType.SaveAndNew + "')" },
                                new FormButton { Text = Loc.SaveAndClose, Icon = "far fa-print fa-lg", OnClick = "onSaveOrPrint('" + InvoiceSaveType.SaveAndClose + "')" }
                            }
                        },
                        PrintSettings = Model.PrintSettings,
                        PrintType = Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? ReportFormName.OrderBuyer : ReportFormName.OrderSupplier,
                        PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                            Model.ReportTreeViewModel,
                            "onSaveOrPrint('" + InvoiceSaveType.SaveAndPrint + "', '{0}')",
                            "onSaveOrPrint('" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                        ),
                        WizardButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.CreatePriceChange, Icon = "", OnClick = "onCreatePriceChange()", HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                new FormButton { Text = Loc.CreateAdvancePayment, Icon = "", OnClick = "openCreateAdvancePayment()" },
                                new FormButton { Text = Loc.CreateDocumentFull, Icon = "", OnClick = "createNewDocumentModal()" },
                                new FormButton { Text = Loc.CancelInvoice, Icon = "", OnClick = "openPartialCancelInvoice()", HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                            }
                        },
                        IsWizardHidden = hasB2BGranule
                    })

                    <button id="invoiceDelete" type="button" onclick="deleteInvoice()"
                            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="orderDuplicate" type="button" onclick="duplicateOrder()" 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 id="newOrderButton" onclick="onClickNewOrder()" title="@Loc.New"
                       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>

                <!-- CALENDAR BUTTONS -->
                <div class="row buttons-tabbed hidden" id="calendar-buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                       ShowCloseBtn = true,
                    })
                </div>
                @*BUTONS END*@
                <div class="divided-content @(PantheonRA.BackOffice.CurrentUser.HasGranule(Granules.B2BGranule) ? "divided-content-side-closed" : string.Empty)">
                    <div class="divided-content-main" style="display: flex; flex-direction: column;">
                        <div class="placeholder @(Model.OrderType == OrderType.Buyer ? "placeholder-invoice-card" : "placeholder-packet-delivery")">
                            <span class="placeholder-text">@(Model.OrderType == OrderType.Buyer ? Loc.OrdersBuyersPlaceholder : Loc.OrdersSuppliersPlaceholder)</span>
                        </div>
                        <div class="row document-head" id="main-doc-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.ValidationMessageFor(model => model.DocType, "", new { @class = "text-danger m-l-xs", @id = "DocType-validation" })
                                    @Html.HiddenFor(model => model.DocType)
                                    @Html.HiddenFor(model => model.CanFiscalize)
                                    <select id="DocTypeSelect"
                                            name="DocType"
                                            class="form-control custom-select" @(string.IsNullOrEmpty(Model.AcKey) ? "" : "disabled")>
                                        @foreach (var item in ViewBag.DocumentTypes)
                                        {
                                            <option value="@item.Id"
                                                    data-fiscalize="@item.CanFiscalize"
                                                    data-warehouse="@item.Warehouse"
                                                    data-payMethod="@item.PayMethod"
                                                    data-receiver="@item.Receiver"
                                                    data-thirdPrsn="@item.ThirdPerson"
                                                    data-department="@item.Department"
                                                    data-doc1="@item.Doc1"
                                                    data-doc2="@item.Doc2"
                                                    data-isObligDept="@item.ISObligDept"
                                                    data-defaultNote="@item.DefaultNote"
                                                    data-pinUrlLPFR="@item.PinUrlLPFR"
                                                    data-attentionUrlPfr="@item.AttentionUrlPFR"
                                                    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-acEnterSnS="@item.AcEnterSns"
                                                    data-acEnterSnK="@item.AcEnterSnk"
                                                    data-acEnterSnP="@item.AcEnterSnp"
                                                    data-acEnterSnE="@item.AcEnterSne"
                                                    data-acEnterSnO="@item.AcEnterSno"
                                                    @(Model.DocType == item.Id ? "selected" : string.Empty)>
                                                @item.Value
                                            </option>
                                        }
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-4 col-sm-6 @(hasB2BGranule ? "document-head-disabled-input" : string.Empty)">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Consignee,
                                        (Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? Loc.Buyer : Loc.Supplier),
                                        new { @class = "control-label", @title = (Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? Loc.Buyer : Loc.Supplier) })
                                    @Html.ValidationMessageFor(model => model.ConsigneeId, "", new { @class = "text-danger m-l-xs", @id = "ConsigneeId-validation" })
                                    @Html.HiddenFor(model => model.ConsigneeId)
                                    @Html.HiddenFor(model => model.ConsigneeName)
                                    <input id="ConsigneePriceRate" hidden />
                                    <input id="ConsigneeRebate" hidden />
                                    @Html.Hidden("ConsigneeIdOld", Model.ConsigneeId)
                                    @Html.TextBoxFor(model => model.Consignee,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_large addable-input", "Consignee", false,
                                        (Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? Loc.Buyer : Loc.Supplier), true, new { @title = Model.Consignee }, hasB2BGranule))
                                    @if (!hasB2BGranule)
                                    {
                                        <div class="addable-button">
                                            <button type="button" title="@Loc.AddingNewPartner"
                                                    id="NewPartner" class="btn createNewButton" onclick="openSubjectModal('Consignee')">
                                                <i class="fas fa-building"></i>
                                            </button>
                                        </div>
                                    }
                                </div>
                            </div>

                            <div class="col-md-2 col-sm-6 @(hasB2BGranule ? "hidden" : string.Empty)">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.WarehouseId, Loc.Warehouse, new
                                    {
                                        @class = "control-label",
                                        @title = Loc.ReceivingWarehouse
                                    })
                                    @Html.DropDownListFor(model => model.WarehouseId,
                                        new SelectList(ViewBag.Warehouses != null ? ViewBag.Warehouses : new List<string>(), "Id", "Name"), Loc.Select,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", null, false, Loc.Warehouse, true, new { @title = Model.WarehouseId }))
                                    @Html.ValidationMessageFor(model => model.Warehouse, "", new { @class = "text-danger", @id = "Warehouse-validation" })
                                </div>
                            </div>

                            <div class="@(hasB2BGranule ? "col-md-4" : "col-md-2") col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Status, Loc.Status, new { @class = "control-label" })
                                    @Html.Hidden("OriginalStatus", Model.Status)
                                    @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,
                                    (Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? Loc.OrderBuyerCode : Loc.OrderSupplierCode),
                                    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
                                            {
                                                KeyDisplayHint = Model.OrderType == OrderType.Buyer ? Loc.OpenListOfBuyesOrders : Loc.OpenListOfOrders,
                                                KeyDisplayValue = Model.AcKeyDisplay,
                                                NextNavigation = Url.Action("Next", "Order", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action((Model.OrderType == OrderType.Buyer ? "EditBuyerOrder" : "EditSupplierOrder"), "Order", new { id = "{id}" })
                                                }),
                                                PrevNavigation = Url.Action("Prev", "Order", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action((Model.OrderType == OrderType.Buyer ? "EditBuyerOrder" : "EditSupplierOrder"), "Order", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action((Model.OrderType == OrderType.Buyer ? "BuyerOrdersReport" : "SupplierOrdersReport"), "Order", new { acKey = Model.AcKey, date = Model.Date.Value.ToString("o") })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>

                        <!-- CALENDAR FILTERS -->
                        <div class="row document-head hidden" id="calendar-doc-head">
                            <div class="col-md-2">
                                <div class="form-group">
                                    @Html.Label(Loc.CalendarName, new { @class = "control-label" })
                                    @Html.DropDownList("DocumentTypes",
                                         new SelectList(ViewBag.CalendarDocumentTypes != null ? ViewBag.CalendarDocumentTypes : new List<string>(), "Id", "Value"),
                                         HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker",
                                             "DocumentTypes", false, Loc.CalendarName,
                                             true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All, @onchange = "getOrdersByDate()" }))
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    @Html.Label(Loc.Display)
                                    <select id="CalendarDisplay"
                                            class="form-control selectpicker"
                                            onchange="displayCalendarTable(); filterTables();">
                                        <option value="@CalendarBy.Employees">@Loc.ByEmployees</option>
                                        <option value="@CalendarBy.Tools">@Loc.ByMeans</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    @Html.Label(Loc.Contractor + "/" + Loc.Worker, new { @class = "control-label" })
                                    @Html.DropDownList("Contractors",
                                         new SelectList(ViewBag.Workers, "Id", "Name"),
                                         HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker",
                                             "Contractors", false, Loc.Contractor + "/" + Loc.Worker,
                                             true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All, @onchange = "filterWorkers()" }))
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group cal-filters">
                                    @Html.Label(Loc.Means, new { @class = "control-label" })
                                    @Html.DropDownList("FixedAssets",
                                         new SelectList(ViewBag.FixedAssets != null ? ViewBag.FixedAssets : new List<string>(), "Id", "Name"),
                                         HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker",
                                             "FixedAssets", false, Loc.Means,
                                             true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All, @onchange = "getOrdersByDate()" }))
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group cal-filters">
                                    @Html.Label(Loc.Customer, new { @class = "control-label" })
                                    @Html.DropDownList("Customers",
                                         new SelectList(ViewBag.Customers != null ? ViewBag.Customers : new List<string>(), "Id", "Display"),
                                         HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker selectpickerAPI",
                                             "Customers", false, Loc.Customer,
                                             true, new { @multiple = "multiple", data_live_search = "true", data_api_url = "Subject/getfilteredbuyers-lookup", @title = Loc.All, @onchange = "getOrdersByDate()" }))
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group cal-filters">
                                    @Html.Label(Loc.Department, new { @class = "control-label" })
                                    @Html.DropDownList("Departments",
                                             new SelectList(ViewBag.Departments, "Id", "Name"),
                                             HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker",
                                                 "Departments", false, Loc.Department,
                                                 true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All, @onchange = "filterWorkers();" }))
                                </div>
                            </div>
                        </div>

                        <div class="document-body table-has-fiscal-data" id="main-doc-body">
                            <div class="row">
                                <div class="col-lg-10 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 = Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ? AuthorType.OrdersBuyer : AuthorType.OrdersSupplier,
                                        Workers = Model.Workers,
                                        FixedAssets = Model.FixedAssets
                                    })
                                </div>
                            </div>

                            <div class="table-responsive document-table m-b-md">
                                <div class="dt-bootstrap" style="position:relative">
                                    <table id="invoice" data-grid-id="@dataGridId" data-dynamic-table="true" class="table table-bordered showhidecolumns" role="grid">
                                        <thead>
                                            <tr role="row">
                                                <th data-column-id="Position" style="width:4%" data-sortable="false">@Loc.Position</th>
                                                <th data-column-id="Ident" style="width:12%">@Loc.Ident</th>
                                                <th data-column-id="Name" style="width:17%">@Loc.Name</th>
                                                <th data-column-id="Quantity" style="width:6%" class="text-right">@Loc.Quantity</th>
                                                <th data-column-id="MeasUnit" style="width:7%; min-width: 78px">@Loc.MeasUnit</th>
                                                <th data-column-id="Price/MeasUnit" style="width:9%" class="text-right">@Loc.Price/@Loc.MeasUnit</th>
                                                <th data-column-id="Discount" style="width:7%" class="text-right">@Loc.Discount %</th>
                                                <th data-column-id="VAT" style="width:6%; min-width: 70px">@Loc.VAT</th>
                                                <th data-column-id="Value" style="width:6%; min-width: 70px">@Loc.Value</th>
                                                <th data-column-id="WarehousePrice" class="text-right @(hasB2BGranule ? "hidden" : "")">@(hasB2BGranule ? "" : Loc.WarehousePrice)</th>
                                                <th data-column-id="TotalPrice" class="text-right">@Loc.Total</th>
                                                <th data-column-id="Shipped" class="text-right">@Loc.Shipped</th>
                                                <th data-column-id="DeliveryDeadline" style="min-width: 100px">@Loc.DeliveryDeadline</th>
                                                <th data-column-id="CostCarrier" class="@(hasB2BGranule ? "hidden" : "")" style="width:7%">@(hasB2BGranule ? "" : Loc.CostCarrier)</th>
                                                <th data-column-id="Department" class="@(hasB2BGranule ? "hidden" : "")" style="width:7%">@(hasB2BGranule ? "" : Loc.Department)</th>
                                                <th data-column-id="ColorCode" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true" style="width:7%">@(hasB2BGranule ? "" : Loc.Color)</th>
                                                <th data-column-id="Begin" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true">@(hasB2BGranule ? "" : Loc.TaBegin)</th>
                                                <th data-column-id="Duration" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true">@(hasB2BGranule ? "" : Loc.Duration)</th>
                                                <th data-column-id="End" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true">@(hasB2BGranule ? "" : Loc.TaEnd)</th>
                                                <th data-column-id="Contractor" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true">@(hasB2BGranule ? "" : Loc.Contractor)</th>
                                                <th data-column-id="Means" class="@(hasB2BGranule ? "hidden" : "")" data-default-hidden="true">@(hasB2BGranule ? "" : Loc.Means)</th>
                                                <th data-column-id="PackQty" style="width:6%" class="text-right">@Loc.PackQty</th>
                                                @if (Model.OrderType == OrderType.Buyer)
                                                {
                                                    <th data-column-id="RetailPrice" style="width:6%" class="text-right">@Loc.RetailPriceShort</th>
                                                }
                                                <th data-column-id="CommentDelete" style="min-width:92px; width:92px;" data-sortable="false"></th>
                                            </tr>
                                        </thead>
                                        <tbody id="identRows"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        @Html.Partial("_Calendar", Model)

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

                                @if (!string.IsNullOrEmpty(Model.FiscalCode))
                                {
                                    <label>@Loc.SDCShort:</label> <span>@Model.FiscalCode</span>
                                }
                            </div>
                        }

                        <div class="row document-footer" id="main-doc-footer">
                            <div class="col-md-1 col-sm-4" style="@(hasB2BGranule ? "border-right:0" : "")">
                                <div class="form-group text-center text-left-xs" onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note, new { @class = "" })
                                    <i id="noteIcon" class="fa fa-comment clickable-icon @(string.IsNullOrEmpty(Model.Note) ? string.Empty : "btn-active")"></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-4 @(hasB2BGranule ? "hidden-xs" : "")" style="@(hasB2BGranule ? "overflow: hidden;" : "")" id="statementsContainer">
                                <div class="form-group @(hasB2BGranule ? "hidden" : "")">
                                    @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 class="form-group @(!hasB2BGranule ? "hidden" : "")">
                                    <span id="NoteDisplay">@Model.Note</span>
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 document-head-disabled-input" title="@Loc.Total">
                                <div class="form-group text-right">
                                    <label>@Loc.Total</label>
                                    <input type="text" id="TotalAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Value" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 @(hasB2BGranule ? "document-head-disabled-input" : string.Empty)">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount %</label>
                                    <input type="text" id="DiscountPercent" step="@Model.DefaultDecimalPlacesValue" value="@Model.DiscountPercent" class="form-control text-right numberInput" @(hasB2BGranule ? "disabled" : string.Empty) />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 @(hasB2BGranule ? "document-head-disabled-input" : string.Empty)">
                                <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" @(hasB2BGranule ? "disabled" : string.Empty) />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-4 document-head-disabled-input" title="@Loc.Value">
                                <div class="form-group text-right">
                                    <label>@Loc.Value</label>
                                    <input type="text" id="Value" value="@Model.CalcSum" step="@Model.DefaultDecimalPlacesValue" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            @if (Model.IsVATObligee)
                            {
                                <div class="col-md-1 col-sm-4 document-head-disabled-input">
                                    <div class="form-group text-right">
                                        <label>@Loc.VAT</label>
                                        <input type="text" id="TaxAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.VAT" class="form-control text-right numberInput" disabled />
                                    </div>
                                </div>
                            }
                            <div class="col-md-1 col-sm-4 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-8" : "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.ForPay.ToString("n" + Model.DefaultDecimalPlacesValue)</span>
                                        <span id="PriceCurrency" 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.ForPay.ToString("n" + Model.DefaultDecimalPlacesValue)</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.CurrencyValue.ToString("n" + Model.DefaultDecimalPlacesValue)</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 order-sidebar-tabs">
                                <li class="@sideTabsClass active"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</a></li>
                                <li class="@sideTabsClass @(hasB2BGranule ? "hidden": string.Empty)">
                                    <a data-toggle="tab" href="#connections" class="local-tab">
                                        @Loc.Connected <span class="badge" id="connectionsCount">
                                            @(Model.Connections != null ?
                                                (Model.Connections != null ? Model.Connections.Count() : 0) +
                                                (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0)
                                                : (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0))
                                        </span>
                                    </a>
                                </li>
                                <li class="@sideTabsClass @(Model.HasOrderCalendar ? string.Empty : "hidden")">
                                    @if (!string.IsNullOrEmpty(Model.AcKey))
                                    {
                                        <a data-toggle="tab" href="#mini-calendar" class="local-tab cal-switcher">@Loc.Calendar</a>
                                        <a data-toggle="tab" href="#calendar" class="local-tab cal-switcher hidden">@Loc.Calendar</a>
                                    }
                                    else
                                    {
                                        <a data-toggle="tab" href="#mini-calendar" class="local-tab cal-switcher hidden">@Loc.Calendar</a>
                                        <a data-toggle="tab" href="#calendar" class="local-tab cal-switcher">@Loc.Calendar</a>
                                    }
                                </li>
                            </ul>
                            <div class="calendar-display-tab hidden">
                                <h4>@Loc.CalendarDisplay</h4>
                            </div>
                        </div>
                        <div class="tab-content">
                            <div id="home" class="tab-pane fade in active">
                                <div class="form-horizontal form-md form-right m-t-lg">
                                    <div class="form-group hidden">
                                        @Html.LabelFor(model => model.ConsigneeAddress, Loc.Address, new { @class = "col-md-3 control-label" })
                                        <div class="col-md-9">
                                            <div class="input-detail-indicator">
                                                @Html.HiddenFor(model => model.ConsigneeAddress)
                                                <p class="control-label" id="SupplierAddressContainer" title="@Model.ConsigneeAddress">
                                                    @Model.ConsigneeAddress
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Date, (Model.OrderType == OrderType.Buyer ? Loc.OrderInvoiceDate : Loc.OrderDateLong), new
                                        {
                                            @class = "col-md-4 control-label",
                                            @title = (Model.OrderType == OrderType.Buyer ? Loc.OrderInvoiceDate : Loc.OrderDateLong)
                                        })
                                        <div class="col-md-4">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @if (!Model.CanFiscalize && string.IsNullOrEmpty(Model.FiscalNumber))
                                                {
                                                    @Html.TextBoxFor(model => model.Date, Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateFormat) : null,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Date", false,
                                                        (Model.OrderType == OrderType.Buyer ? Loc.OrderInvoiceDate : Loc.OrderDateLong)))
                                                }
                                                else
                                                {
                                                    @Html.TextBoxFor(model => model.Date, Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateFormat) : null,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker hidden",
                                                        "Date", !Model.CanFiscalize))

                                                    @Html.TextBoxFor(model => model.FiscalDate, Model.FiscalDate.HasValue ? Model.FiscalDate.Value.ToString(Loc.DateTimeFormatFull) :
                                                        (Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateTimeFormat) : null),
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "FiscalDate", !Model.CanFiscalize,
                                                        (Model.OrderType == OrderType.Buyer ? Loc.OrderInvoiceDate : Loc.OrderDateLong), false, null, true))
                                                }
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                        </div>
                                    </div>

                                    @if (!string.IsNullOrEmpty(Model.FiscalNumber) && Model.FiscalNumber.Trim() != "0" && PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                                    {
                                        <div class="form-group">
                                            @Html.LabelFor(model => model.FiscalNumber, Loc.Invoice, new { @class = "col-md-4 control-label" })
                                            <div class="col-md-8">
                                                @Html.TextBoxFor(model => model.FiscalNumber, HtmlAttributesHelper.CreateInputAttributes("form-control", null, true,
                                                "", false, null, true))
                                                @Html.ValidationMessageFor(model => model.FiscalNumber, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                    }

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

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.DaysForPayment, Loc.DaysForPayment, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-4">
                                            <div class="input-group">
                                                @Html.TextBoxFor(model => model.DaysForPayment,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control", "DaysForPayment", false, Loc.NumOfDays, true, null, hasB2BGranule))
                                                <span class="input-group-addon">@Loc.Days.ToLower()</span>
                                            </div>
                                            @Html.ValidationMessageFor(model => model.DaysForPayment, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

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

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.PaymentMethod, Loc.PaymentMethod, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            <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-fiscalize="@item.FiscalGroup" @(Model.PaymentMethodId == item.PaymentMethod ? "selected" : string.Empty)>
                                                        @(item.PaymentMethod) - @(item.Name)
                                                    </option>
                                                }
                                            </select>
                                            @Html.ValidationMessageFor(model => model.PaymentMethodId, "", new { @class = "text-danger", @id = "PaymentMethodId-validation" })
                                        </div>
                                    </div>

                                    <div class="form-group @(hasB2BGranule ? "hidden" : string.Empty)">
                                        @Html.LabelFor(model => model.Currency, Loc.CurrencyAndRate, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8 col-sm-12">
                                            <div class="row">
                                                <div class="col-sm-6">
                                                    <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-sm-6 padding-left-none-lg padding-left-none-md padding-left-none-sm">
                                                    @Html.TextBoxFor(model => model.FXRate,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control numberInput", "FxRate", false, Loc.FxRate, true, new { step = 6 }))
                                                    @Html.ValidationMessageFor(model => model.FXRate, "", new { @class = "text-danger" })
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

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

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

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Receiver, Loc.Recipient, new { @class = "col-md-4 control-label", @title = Loc.Driver })
                                        <div class="col-md-8">
                                            @Html.HiddenFor(model => model.ReceiverId)
                                            @Html.HiddenFor(model => model.ReceiverName)
                                            @Html.TextBoxFor(model => model.Receiver,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide addable-input-btn", "Receiver", false, Loc.Recipient, false,
                                                new { dataUrl = Url.Action("SearchPartners", "Wholesale"), @autocomplete = "off", @title = Model.Receiver }))
                                            @Html.HiddenFor(model => model.ReceiverAddress)
                                            @if (!hasB2BGranule)
                                            {
                                                <div class="addable-button">
                                                    <button type="button" title="@Loc.AddingNewPartner"
                                                            id="NewReceiver" class="btn createNewButton" onclick="openSubjectModal('Receiver')">
                                                        <i class="fas fa-building"></i>
                                                    </button>
                                                </div>
                                            }
                                            <div class="input-detail-indicator">
                                                <p class="control-label" id="ReceiverAddressContainer" title="@Model.ReceiverAddress">
                                                    @Model.ReceiverAddress
                                                </p>
                                            </div>
                                            @Html.ValidationMessageFor(model => model.ReceiverId, "", new { @class = "text-danger", @id = "ReceiverId-validation" })
                                        </div>
                                    </div>

                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS && Model.OrderType == OrderType.Buyer)
                                    {
                                        <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>
                                    }

                                    <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="@(hasB2BGranule ? "col-md-8" : "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-lg padding-left-none-md padding-left-none-sm  @(hasB2BGranule ? "hidden" : string.Empty)">
                                            @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.Doc1, 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.Doc1,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Order", false, Loc.DocumentOne))
                                            @Html.ValidationMessageFor(model => model.Doc1, "", new { @class = "text-danger", @id = "Doc1-validation" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-lg padding-left-none-md padding-left-none-sm">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.Doc1Date, Model.Doc1Date.HasValue ? Model.Doc1Date.Value.ToString("dd.MM.yyyy") : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Doc1Date", false, Loc.DocumentOneDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Doc1Date, "", new { @class = "text-danger", @id = "IssueDate-validation" })
                                        </div>
                                    </div>

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

                                    @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS && Model.OrderType == OrderType.Buyer)
                                    {
                                        <div id="referenceDocCancellationContainer" class="form-group hidden">
                                            @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 order-dt-picker", "RefundRelatedDocDate", false, Loc.DocumentDate))
                                                </div>
                                                @Html.ValidationMessageFor(model => model.RefundRelatedDocDate, "", new { @class = "text-danger", @id = "OrderFormDate-validation" })
                                            </div>
                                        </div>
                                    }

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ClerkId, Loc.ClerkShort, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            <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.NoteClerkId, Loc.Referent, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            @Html.DropDownListFor(model => model.NoteClerkId,
                                                new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name", Model.NoteClerkId), "",
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "NoteClerkId", true, Loc.Referent, true, new { @disabled = "disabled" }))
                                            @Html.ValidationMessageFor(model => model.NoteClerkId, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="connections" class="row tab-pane fade in">
                                @Html.HiddenFor(x => x.CanceledOrder)
                                @if (Model.CanceledOrder)
                                {
                                    <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.Connections != null)
                                {
                                    for (var i = 0; i < Model.Connections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a href="@Url.GenerateInvoiceUrl(Model.Connections[i].TypeOfDocument, Model.Connections[i].AcKey)">
                                                    @Model.Connections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.Connections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                            </div>

                            <!-- CALENDAR TABS -->
                            <div id="calendar" class="tab-pane fade in">
                                <div class="calendar-period-wrapper">
                                    <select id="calendar-period" class="select2">
                                        <option value="@CalendarTypes.DailyShort">@Loc.Daily</option>
                                        <option value="@CalendarTypes.WeeklyShort">@Loc.Weekly</option>
                                        <option value="@CalendarTypes.MonthlyShort">@Loc.Monthly</option>
                                    </select>
                                </div>
                                <span class="calendar-header-border hidden"></span>
                                <div id="proforma-invoice-calendar"></div>
                            </div>
                            <div id="mini-calendar" class="tab-pane fade in">
                                @Html.Partial("_MiniCalendar", Model)
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

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

        <div class="modal inmodal fade" 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="modal-body">
                        @{Html.RenderPartial("~/Views/Subjects/_CreateSubjectFormPartial.cshtml",
                              new SubjectCreateViewModel()
                              {
                                  SubjectEditData = new SubjectEditData()
                                  {
                                      SelectedCountryId = Model.SelectedCountry,
                                      WayOfSale = Model.DefaultSubjWayOfSale,
                                      WayOfSaleSupplier = Model.DefaultSubjWayOfSaleSupplier,
                                      IsBuyer = Model.OrderType == OrderType.Buyer,
                                      IsSupplier = Model.OrderType == OrderType.Supplier,
                                  },
                                  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="deliveryDeadlineChangeModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <span id="deliveryDeadlineChangeModalMessage"></span>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" onclick="">@Loc.Cancel</button>
                        <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="changeIdentsDeliveryDeadline()">@Loc.Confirm</button>
                    </div>
                </div>
            </div>
        </div>

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

        <div class="modal inmodal fade" id="createDocumentModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-xxl" role="document">
                <div class="modal-content">
                    <div class="modal-header padding-bottom-none">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active"><a class="local-tab" data-toggle="tab" href="#createDocTab">@Loc.CreateDocumentFull</a></li>
                                <li><a class="local-tab" data-toggle="tab" href="#transferStatisticTab">@Loc.TransferStatistic</a></li>
                                <li class="pull-right flex-pull-right">
                                    <button type="button" class="btn-transparent no-padding" onclick="openCreateDocumentUserManualHelp()" title="@Loc.CheckSamples"><i class="fas fa-book-reader clickable-icon"></i></button>
                                    <button type="button" class="btn-transparent m-r-xxs" onclick="openCreateDocumentHelp()" title="@Loc.CheckInstructions"><i class="fas fa-question clickable-icon"></i></button>
                                </li>
                                <li class="pull-right m-r-md m-t-xxs"><button type="button" class="close" data-dismiss="modal" aria-label="Close" title="@Loc.Close"><span aria-hidden="true">&times;</span></button></li>
                            </ul>
                        </div>
                    </div>
                    <div class="modal-body">
                        @{Html.RenderPartial("~/Views/Order/_CreateDocumentPartial.cshtml",
                                  new OrderCreateDocumentModel()
                                  {
                                      DocumentAcKey = Model.AcKey,
                                      OrderType = Model.OrderType.ToString(),
                                      CreateDate = DateTime.Now,
                                      InvoiceDate = DateTime.Now,
                                      TaxDate = DateTime.Now,
                                      DocType = Model.OrderType == OrderType.Buyer ? DocType.DocTypeWholesale : DocType.DocTypeReceivedBills
                                  });
                        }
                    </div>
                </div>
            </div>
        </div>

        <div class="modal inmodal fade" id="createdDocDateWarningModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <span>@Loc.CreateDocumentFromOrderDateError</span>
                        <div class="well well-sm well-bg clickable-icon m-t-sm m-b-sm" onclick="fixCreatedDocumentDate()">
                            <div class="row">
                                <div class="col-xs-2">
                                    <div class="icon-arrow-right"></div>
                                </div>
                                <div class="col-xs-10 well-text-margin">
                                    <strong>@Loc.FixDateDue</strong>
                                    <p class="no-margins">@Loc.FixDateDueDescription</p>
                                </div>
                            </div>
                        </div>
                        <div class="well well-sm well-bg clickable-icon m-b-sm" data-dismiss="modal">
                            <div class="row">
                                <div class="col-xs-2">
                                    <div class="icon-arrow-right"></div>
                                </div>
                                <div class="col-xs-10 well-text-margin">
                                    <strong>@Loc.Continue</strong>
                                    <p class="no-margins">@Loc.ContinueDescription</p>
                                </div>
                            </div>
                        </div>
                        <div class="well well-sm well-bg clickable-icon m-b-sm" onclick="openCreateDocDateWarningHelp()">
                            <div class="row">
                                <div class="col-xs-2">
                                    <div class="icon-help">
                                        <img src="~/Content/Redesign/Icons/Trademark/icon-help.svg" />
                                    </div>
                                </div>
                                <div class="col-xs-10 well-text-margin">
                                    <strong>@Loc.ViewInstructions</strong>
                                    <p class="no-margins">@Loc.ViewInstructionsDescription</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        @{Html.RenderPartial("~/Views/Wizard/Wizard.cshtml");}
        @{Html.RenderPartial("~/Views/AdvancePayment/_CreateAdvancePaymentModal.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceDeleteModals.cshtml");}
        @{Html.RenderPartial("~/Views/Shared/Components/_InvoiceCurrencyChange.cshtml");}
        @if (Model.OrderType == OrderType.Supplier)
        { Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoModal.cshtml"); }
        else
        { Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoIssueModal.cshtml"); }
        @{Html.RenderPartial("~/Views/Shared/Components/_PartialCancelInvoice.cshtml", new PartialCancelInvoiceModalModel()
            {
                Type = InvoiceType.OrderBuyer,
                PartialCancelDefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
                PartialCancelDefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
                PartialCancelDefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue,
            });
        }
    </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="departmentOptions" hidden>
        <option></option>
        @foreach (var item in ViewBag.Departments)
        {
            <option value="@item.Id">
                @item.Name
            </option>
        }
    </div>

    <div id="mainColors" hidden>
        @foreach (var color in Model.MainColors)
        {
            <div class="col-md-12"
                 onclick="setColor('@color.Key.ToString()', this)">
                <div class="color-picker-box" style="background-color: @color.Key.ToString()"></div>
                <p> @color.Name</p>
            </div>
        }
    </div>

    <div id="tooltipColors" hidden>
        @foreach (var color in Model.MainColors)
        {
            <div class="col-md-12"
                 onclick="changeItemColor($(this).children()[0])">
                <div class="color-picker-box" style="background-color: @color.Key.ToString()"></div>
                <p style="margin-top: 5px;"> @color.Name</p>
            </div>
        }
    </div>

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

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

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

    <div id="DocumentTypesEdit" hidden>
        @foreach (var item in ViewBag.DocumentTypes)
        {
            <option value="@item.Id">
                @item.Value
            </option>
        }
    </div>
</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="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="OrderTypeBuyerEnum" value="@OrderType.Buyer" />
<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="PositiveAndNegativeQuantityCannotBeOnTheSameDocumentLoc" value="@Loc.PositiveAndNegativeQuantityCannotBeOnTheSameDocument" />
<input type="hidden" id="AllTaxesNeedFiscalCodeLoc" value="@Loc.AllTaxesNeedFiscalCode" />
<input type="hidden" id="isIdentPerDay" />
@Html.Partial("_HelperValues", Model)

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


    <script type="text/javascript">
        var invoiceItems = [];
        var paperSize = "";
        var consigneeTypeaheadData;
        var receiverTypeaheadData;
        var isSaving = false;
        var isSubjectChange = false;
        var firstTrigger = true;
        var hasTableLoaded = false;
        var hasUnfiscalizedInvoice = false;
        var isRetailSale = false;

        $(document).ready(function () {
            loadInvoiceItems();
            initializeSubjectsEdit();
            changeSubjectRabate($("#OrderType").val() === "@OrderType.Buyer" ? toNumber('@Model.ReceiverRabate') : toNumber('@Model.ReceiverSuppliersRabate'));
            initializeInvoiceIdentInputs(
                $('#IdentSearch'),
                $("#OrderType").val() === "@OrderType.Buyer" ? PriceType.OrderBuyer : PriceType.OrderSuppliers,
                $("#OrderType").val() === "@OrderType.Buyer" ? DiscountType.SellerDiscount : DiscountType.SupplierRebate,
                $("#DefaultDecimalPlacesPrice").val(),
                $("#WarehouseId"),
                $("#ConsigneeId"),
                $("#WayOfSale"),
                { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock'}
            );
            setStatements($("#Statements"), $("#Statement").val());
            showFiscalData();
            checkFormEditable();
            updateReportTreeDisplay($(".printMD"), $("#DocTypeSelect option:selected").attr("data-fiscalize"));

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

            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")'
            });

            var elems = Array.prototype.slice.call(document.querySelectorAll('#createDocumentForm .js-switch'));
            elems.forEach(function (html) {
                var switchery = new Switchery(html, { size: 'small' });
            });

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

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

            $("#Date").on('change', function () {
                var start = $("#Date").datepicker('getDate');
                if (!start) return;

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

                if (!$("#DateValid").datepicker('getDate') || $("#DateValid").datepicker('getDate').getTime() !== newDate.getTime())
                    $("#DateValid").datepicker('setDate', newDate);
            });

            $("#DaysForValid").on('change', function () {
                var start = $("#Date").datepicker('getDate');
                if (!start) return;

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

                if (!$("#DateValid").datepicker('getDate') || $("#DateValid").datepicker('getDate').getTime() !== newDate.getTime())
                    $("#DateValid").datepicker('setDate', newDate);
            });

            $("#DateValid").on('change', function () {
                var start = $("#Date").datepicker('getDate');
                var end = $("#DateValid").datepicker('getDate');
                if (!start || !end) return;

                var endDate = +new Date(end.getFullYear(), end.getMonth(), end.getDate());
                var startDate = +new Date(start.getFullYear(), start.getMonth(), start.getDate());
                var days = Math.round(Math.abs((endDate - startDate) / 1000 / 60 / 60 / 24));

                $("#DaysForValid").val(days);
            });

            $("#DeliveryDeadline").on('change', function () {
                if (invoiceItems.length > 0) {
                    $().customModal({
                        title: "",
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "deliveryDeadlineChangedAlertModal",
                        type: "question",
                        text: "@Loc.ChangeDeliveryDeadlineOnPositions",
                        buttons: [
                            {
                                icon: 'fa fa-times',
                                text: '@Loc.Cancel',
                                closeOnAction: true,
                                type: 'ghost'
                            },
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.Confirm',
                                action: function () {
                                    changeIdentsDeliveryDeadline();
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });

            $("#WarehouseId").on('change', function () {
                $("#WarehouseId").prop("title", $("#WarehouseId option:selected").text());
                $.get("@Url.Action("IsSubjRetailSale", "Subjects")" + "?subjectId=" + $("#WarehouseId").val(), function (response) {
                    $("#IsRetailSale").val(response);
                });
            });

            $("#Status").on('change', function () {
                $.get("@Url.Action("CanDelete", "Order")"
                    + "?acKey=" + $("#AcKey").val()
                    + "&type=" + ($("#OrderType").val() === "@OrderType.Buyer" ? "@CashRegType.OrdersBuyers" : "@CashRegType.OrdersSuppliers"),
                    function (response) {
                        if (response.ShowError === true && (response.DocumentAddedToDispatchList === true || response.DocumentAddedToDispatchListWithoutQuantity === true)) {
                            $().customModal({
                                title: "",
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "error",
                                text: "@Loc.OrderAlreadyTransferredToDispatchListCannotChangeStatus",
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: '@Loc.Confirm',
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });

                            $("#Status").val($("#OriginalStatus").val());
                        } else {
                            $("#OriginalStatus").val($("#Status").val());
                        }
                    });
            });

            $("#DocTypeSelect").on('change', async function () {
                $("#DocType").val($("#DocTypeSelect").val());
                $("#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);
                    $("#buyerTypeLookupContainer").removeClass("hidden");
                } else {
                    $("#CanFiscalize").val(false);
                    $("#BuyerCostCenterId").val("");
                    $("#BuyerCostCenterIdDef").val(null);
                    $("#BuyerIdDef").val(null);
                    $("#BuyerID").val("");
                    $("#buyerTypeLookupContainer").addClass("hidden");
                }

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

                if (!$("#AcKey").val() && $("#DocTypeSelect option:selected").attr("data-receiver") && '@hasB2BGranule' !== '@Boolean.TrueString') {
                    $("#Consignee").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                    $("#ConsigneeId").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                    getSubjectData($("#DocTypeSelect option:selected").attr("data-receiver"));

                    if ($("#DocTypeSelect option:selected").attr("data-thirdPrsn")) {
                        $("#Receiver").val($("#DocTypeSelect option:selected").attr("data-thirdPrsn"));
                        $("#ReceiverId").val($("#DocTypeSelect option:selected").attr("data-thirdPrsn"));
                    } else {
                        $("#Receiver").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                        $("#ReceiverId").val($("#DocTypeSelect option:selected").attr("data-receiver"));
                    }
                }

                if (!$("#AcKey").val() && $("#DocTypeSelect option:selected").attr("data-department"))
                    $("#Department").val($("#DocTypeSelect option:selected").attr("data-department"));

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

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

                if (!$("#AcKey").val())
                    getDocTexts($("#DocTextsUrl").val(), $("#Statement"), $("#Statements"), $("#DocType").val());

                showFiscalData();
                if (!$("#AcKey").val()) {
                    if (!firstTrigger || '@hasB2BGranule' !== '@Boolean.TrueString') {
                        $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
                    }
                    $("#Note").val($("#DocTypeSelect option:selected").attr("data-defaultNote"));
                    $("#NoteDisplay").text($("#Note").val());
                    $("#IsObligDept").val($("#DocTypeSelect option:selected").attr("data-isObligDept"));
                    setNoteIcon();

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

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

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

                changeTableId();

                $("#calendar-doc-head #DocumentTypes").val($("#main-doc-head #DocTypeSelect").val());
                $(".selectpicker").selectpicker("refresh");

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

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

            $("#DocTypeSelect").trigger("change");
            $("#DaysForValid").trigger("change");
            firstTrigger = false;

            function getSubjectData(id) {
                $.get("@Url.Action("GetSubjectById", "Subjects")" + "?subjectId=" + id, function (response) {
                    $("#WayOfSale").val($("#OrderType").val() === "@OrderType.Buyer" ? response.WayOfSale : response.WayOfSaleSupplier);
                });
            }

            initializePartnerTypeahead('@(Model.OrderType == PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer ?
                Url.Action("SearchPartners", "Wholesale") : Url.Action("SearchSuppliers", "ReceivedBills"))', $('#Consignee'), $("#ConsigneeId"), function (item) {

                consigneeTypeaheadData = item;
                $("#Consignee").prop("title", $("#Consignee").val());
                $("#ConsigneeName").val(item.value);
                $("#ConsigneeAddressContainer").text(item.completeAddress);
                $("#ConsigneeAddressContainer").prop('title', item.completeAddress);
                $("#ConsigneePriceRate").val(item.priceRate);
                $("#ConsigneeRebate").val(item.rebate);
                if ($("#FillRefFromSubj").val() === "True") {
                    $("#Clerk").val($("#OrderType").val() === "@OrderType.Buyer" ? item.clerk : item.clerkSupp);
                    $("#Clerk").trigger("change");
                }

                if ($("#OrderType").val() === "@OrderType.Buyer")
                    $("#WayOfSale").val(item.wayOfSale);
                else
                    $("#WayOfSale").val(item.wayOfSaleSupplier);

                if (item.paymentMethodId != null && item.paymentMethodId != "") {
                    if ($("#OrderType").val() === "@OrderType.Buyer") {
                        $("#PaymentMethodId").val(item.paymentMethodId);
                    } else {
                        $("#PaymentMethodId").val(item.paymentMethodIdSupplier);
                    }
                } else {
                    $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
                }

                $("#DaysForPayment").val($("#OrderType").val() === "@OrderType.Buyer" ? item.daysForPayment : item.daysForPaymentSupplier);
                $('#DaysForPayment').trigger('change');
                changeSubjectRabate($("#OrderType").val() === "@OrderType.Buyer" ? item.rebate : item.rabateSupplier);

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

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

                buyerChangedChangeIdentCurrency();

                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 ($("#ReceiverId").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 () {
                                    changeReceiverToConsignee(item);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                else
                    changeReceiverToConsignee(item);
            });

            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 () {
                                $('#Consignee').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());
                    }
                }
            }

            initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#Receiver'), $("#ReceiverId"), function (item) {
                receiverTypeaheadData = item;
                $("#ReceiverName").val(item.value);
                $("#Receiver").prop("title", $("#Receiver").val());
                $("#ReceiverAddressContainer").text(item.completeAddress);
                $("#ReceiverAddressContainer").prop('title', item.completeAddress);
            }, function () {
                    return { limitToSubjectId: $("#Consignee").val() };
            });

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

            $("#PaymentMethodId").on('change', function () {
                $("#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;
                }

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

            $("#Receiver").blur(function () {
                createNewSubjectModal($("#ReceiverId"), $("#Receiver"), "Receiver", $("#ReceiverName"));
            });

            $("#Consignee").blur(function () {
                createNewSubjectModal($("#ConsigneeId"), $("#Consignee"), "Consignee", $("#ConsigneeName"));
            });

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

            $("#Currency").on("customSelectChange", function () {
                var date = $("#Date").datepicker("getDate");

                $.get('@Url.Action("GetFxRate", "Currency")', { Currency: $("#Currency").val(), Date: new Date(date).toISOString() })
                    .done(function (response) {
                        $(".ToPayCurrency").text($("#Currency").val());
                        $("#FxRate").val(response);
                        formatNumberInput($("#FxRate"));
                        toPayDisplay();

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

                        onClickSave("@InvoiceSaveType.SaveAndChangeFxRate");
                        if (invoiceItems.length > 0 && isSubjectChange === false) {
                            $("#invoiceCurrencyChangeWarningModal").modal("show");
                        } else if (isSubjectChange === true && $("#ConsigneeIdOld").val()) {
                            isSubjectChange = false;
                            $("#ConsigneeIdOld").val($("#ConsigneeId").val());

                            $().customModal({
                                title: "",
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "question",
                                text: "@Loc.BuyerChangedGetIdentPrices",
                                buttons: [
                                    {
                                        icon: 'fa fa-times',
                                        text: '@Loc.No',
                                        closeOnAction: true,
                                        type: 'ghost'
                                    },
                                    {
                                        icon: 'fa fa-check',
                                        text: '@Loc.Yes',
                                        action: function () {
                                            recalculateMovePrices('O');
                                        },
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }

                        isSubjectChange = false;
                    });
            });

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

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

            toPayDisplay();

            $('#createDocumentModal').on('hidden.bs.modal', function () {
                if (createdDocAcKey && createdDocAcKey != "") {
                    $().customModal({
                        title: "",
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "",
                        type: "success",
                        text: "@Loc.CreatedDocumentWithNumber: " + createdDocAcKey,
                        buttons: [
                            {
                                icon: 'fa fa-times',
                                text: '@Loc.Continue',
                                closeOnAction: true,
                                type: 'ghost'
                            },
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.Open',
                                action: function () {
                                    redirectToUrlWithAcKey(createdDocUrl, createdDocAcKey);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            });

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

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

            calendarInit();
            getInputVisibilityData();
            timeInputsOnFocus();

            $(".custom-scrollable-tabs").children("#" + $("#Calendar").val()).on("click", function () {
                openCalendarTab($(this));
            });

            $("a[href='#mini-calendar']").on("click", function () {
                miniCalendarSidebarClick();
            });

            $("a[href='#calendar']").on("click", function () {
                calendarSidebarClick();
            });

            $("#DateValid").change(function() {
                setIdentsQuantityEqualsDurationDays();
            });

            $("#SelectedItemQuantity").change(function () {
                if ($("#isIdentPerDay").val()) {
                    $("#DaysForValid").val($("#SelectedItemQuantity").val()).trigger("change");
                }
            });

            openCalendarTabViaMenu();
        });

        function changeReceiverToConsignee(item) {
            $("#ReceiverId").val(item.id);
            $("#Receiver").val(item.value);
            $("#ReceiverName").val(item.value);
            $("#Receiver").prop("title", $("#Receiver").val());
            $("#ReceiverAddressContainer").text(item.completeAddress);
            $("#ReceiverAddressContainer").prop('title', item.completeAddress);
            receiverTypeaheadData = 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'
                        }
                    ]
                });
            }
        }

        function buyerChangedChangeIdentCurrency() {
            let item = consigneeTypeaheadData;

            if (($("#OrderType").val() === "@OrderType.Buyer" && $("#Currency").val() !== item.currency)
                || ($("#OrderType").val() === "@OrderType.Supplier" && $("#Currency").val() !== item.suppCurrency)) {
                isSubjectChange = true;
                var curr = $("#OrderType").val() === "@OrderType.Buyer" ? item.currency : item.suppCurrency;

                $("#OrderCurrency").val(curr);
                $("#Currency").val(curr);
                $("#Currency").trigger("customSelectChange");
                $("#OldCurrency").val(curr);
            } else
                $("#ConsigneeIdOld").val($("#ConsigneeId").val());

            getDeliveryFillType();
        }

        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 setIdentPrices() {
            var model = {
                AcKey: $("#AcKey").val(),
                Subject: $("#ConsigneeId").val(),
                PriceRate: $("#ConsigneePriceRate").val(),
                Warehouse: $("#WarehouseId").val(),
                Currency: $("#Currency").val(),
                Date: new Date($("#Date").datepicker("getDate")).toISOString(),
            };

            $.ajax({
                method: "POST",
                url: "@Url.Action("OrderChaPriceClass", "Order")",
                data: JSON.stringify(model),
                contentType: "application/json",
                success: function (data) {
                    if (data === true) {
                        swapLoadingIcon(true, "add-position", "fa fa-plus");
                        $.get('@Url.Action("OrderItems", "Order")?acKey=' + $("#AcKey").val()
                            + ($("#OrderType").val() === "@OrderType.Buyer" ? "&subject=" + $("#ReceiverId").val()
                                + "&subjectType=" + $("#WayOfSale").val()
                                + "&saleType=P" : ""),
                            function (data) {
                                for (var i = 0; i < data.length; i++) {
                                    $("#price-" + data[i].AnNo).val(data[i].Price);
                                    $("#rabate-" + data[i].AnNo).val(data[i].Rebate);
                                    $("#value-" + data[i].AnNo).val(data[i].Value);
                                    $("#lastPrice-" + data[i].AnNo).val(data[i].LastPrice);
                                    $("#totalPrice-" + data[i].AnNo).val(data[i].TotalPrice);

                                    formatNumberInput($("#price-" + data[i].AnNo));
                                    formatNumberInput($("#rabate-" + data[i].AnNo));
                                    formatNumberInput($("#value-" + data[i].AnNo));
                                    formatNumberInput($("#lastPrice-" + data[i].AnNo));
                                    formatNumberInput($("#totalPrice-" + data[i].AnNo));

                                    setChangedIdentData(data[i].AnNo)
                                }

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

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

                                save();
                            }, "json");
                    }
                },
                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 setIdentsQuantityEqualsDurationDays() {
            $("#identRows tr").each(function (index) {
                var durationDays = $("#DaysForValid").val();
                var iterator = index + 1;
                var durationDaysDecimal = formatDisplay($("#DefaultDecimalPlacesQuantity").val(), durationDays);
                if ($("#measurementUnit-" + iterator).val() == $("#MeusurementUnitDay").val()
                    && $(this).find("#quantity-" + iterator).val() != durationDaysDecimal)
                {
                    $(this).find("#quantity-" + iterator).val(durationDaysDecimal);
                    changeIdentData(iterator);
                }
            });
        }

        function miniCalendarSidebarClick() {
            let miniCalendarWrapperId = $(miniCalendarTypeId).val() === calendarByEmployees ? miniCalendarWrapperWorkers : miniCalendarWrapperTools;
            let miniCalendarTableId = "#" + $("#" + miniCalendarWrapperId + " table").attr("id");
            let isTools = $(miniCalendarTypeId).val() === calendarByTools ? true : false;
            $("#calendar").removeClass("active in");
            $("#mini-calendar").addClass("active in");
            $("#" + miniCalendarWrapperId).removeClass("hidden");
            initScroll(miniCalendarTableId);
            updateElementsWidthMini(isTools);
        }

        function calendarSidebarClick() {
            $("#calendar").addClass("active in");
            $("#mini-calendar").removeClass("active in");
            $(".calendar-period-wrapper").addClass("m-t-sm");
        }

        function openCalendarTabViaMenu() {
            var urlString = window.location.href;
            var url = new URL(urlString);
            var calendarTab = url.searchParams.get("calendarTab");

            if (calendarTab != null) {
                let calendarTab = $(".custom-scrollable-tabs").children("#" + $("#Calendar").val())
                openCalendarTab(calendarTab);
            }
        }

        function openCalendarTab(calendarTab) {
            calendarTab.parent().find(".active").removeClass("active");
            calendarTab.addClass("active");

            $("#calendar").addClass("active in");
            $("#home").removeClass("active in");
            $("#mini-calendar").removeClass("active in");
            $(".ui-state-active").click();

            $(".order-sidebar-tabs").addClass("hidden");
            $(".calendar-display-tab").removeClass("hidden");
            $(".calendar-header-border").removeClass("hidden");
            $("#calendar #select2-calendar-period-container").addClass("select2-calendar-period");
            $(".calendar-period-wrapper").removeClass("m-t-sm");
            setGlobalHelpUrl($("#CalendarUrlHelp").val());
        }

        function timeInputsOnFocus() {
            $("#TimeStart, #TimeDuration").focus(function () {
                if (!$(this).val()) {
                    $(this).val("00:00");
                }
            });
        }

        function changeTableId() {
            var isCalendarTab = decodeURI(new URL(window.location.href).searchParams.get("calendarTab"));
            $("#invoice").attr("data-grid-id", "create-order-" + $("#main-doc-head #DocTypeSelect").val());
            $("#sh-dropdown-menu").remove();
            $(".showhidecolumns th").removeClass("hidden-column");

            if (hasTableLoaded || isCalendarTab === "True") {
                displayShowHideDropdown();
            }
            getInputVisibilityData();
        }

        function getInputVisibilityData() {
            var tableName = table.attr('data-grid-id');

            return $.ajax({
                url: $("#GetTableGrid").val(),
                data: {
                    TableName: tableName
                },
                success: function (data) {
                    if (!jQuery.isEmptyObject(data)) {
                        setInputFieldsVisibility(data.Columns)
                    } else {
                        setDefaultInputFieldsVisibility();
                    }
                }
            });
        }

        function setInputFieldsVisibility(columnData) {
            if ($("#userHasB2BGranule").val() == "False") {
                let fields = ["Quantity", "Price/MeasUnit", "Discount", "Begin", "Duration", "Contractor", "Means"];

                $.each(fields, function (index, item) {
                    let hidden = columnData.filter(e => e.Id === item)[0].IsHidden;
                    if (hidden) {
                        $(".InputField-" + item.split("/")[0]).addClass("hidden");
                    } else {
                        $(".InputField-" + item.split("/")[0]).removeClass("hidden");
                    }
                });
            }
        }

        function setDefaultInputFieldsVisibility() {
            $("#identSearchTable th:not(.order-calendar-th), td:not(.order-calendar-td)").each(function () {
                if ($(this).hasClass("hidden")) {
                    $(this).removeClass("hidden");
                }
            });
            $("#identSearchTable th.order-calendar-th, td.order-calendar-td").each(function () {
                if (!$(this).hasClass("hidden")) {
                    $(this).addClass("hidden");
                }
            });
        }

        $(document).on("click", ".sh-checkbox", function () {
            var checked = $(this).is(":checked");
            var columnId = $(this).attr("name");
            columnId = columnId.slice(4).split("/")[0];

            if (!checked) {
                $(".InputField-" + columnId).addClass("hidden");
            } else {
                $(".InputField-" + columnId).removeClass("hidden");
            }
        })

        function setColor(color, currentElement) {
            let rowNum = $(currentElement).parents(':eq(1)').data("row");

            $("#input-main-color-box-" + rowNum).css("background-color", color);
            $("#colorCode-" + rowNum).val(color);

            changeIdentData(rowNum);
        }

        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 = createOrderIdentsTableRows($("#invoice"), data, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#IsVATObligee").val(), $("#OrderType").val(),
                '@hasB2BGranule' === '@Boolean.TrueString', $("#IsRetailSale").val() === "True" && $("#OrderType").val() === "@OrderType.Buyer");

            initializeNumberInputs();
            if (isNewIdent) {
                reorderColumns(true, newRow);
                $("#sh-dropdown-menu").remove();
                setDropdownMenu();
                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",
                                    action: function () {
                                        checkForIdentSerial(data);
                                    },
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    } else
                        checkForIdentSerial(data);
                } else {
                    checkForIdentSerial(data);
                }
            }
        }

    function checkForIdentSerial(item) {
        if ($("#OrderType").val() === "@OrderType.Buyer")
            checkIdentSerialNoIssue(item.AnNo, "O", item.SerialNo, item.Quantity);
        else
            checkIdentSerialNo(item.AnNo, "O", item.SerialNo, item.Quantity);
    }

    async function addPosition(selectedInvoiceItemData) {
            if ($("#isIdentPerDay").val()) {
                $("#DaysForValid").val(Math.round(toNumber($("#SelectedItemQuantity").val()))).trigger("change");
            }

            if (hasUnfiscalizedInvoice) {
                hasUnfiscalizedInvoiceErrorDisplay();
                return;
            }

            if ($("#OrderType").val() === "@OrderType.Buyer" && "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS") {
                if (checkIdentQuantity(invoiceItems, $("#SelectedItemQuantity"), true) === false)
                    return;
            }

            if (($("#OrderType").val() === "@OrderType.Buyer" && ($("#WayOfSale").val() === "@WayOfSale.ExportSale" || $("#WayOfSale").val() === "@WayOfSale.ExportSaleEU")) ||
                ($("#OrderType").val() === "@OrderType.Supplier" && ($("#WayOfSale").val() === "@WayOfSale.Nonresident"
                    || $("#WayOfSale").val() === "@WayOfSale.Flatrate" || $("#WayOfSale").val() === "@WayOfSale.OtherNotTaxComitted"))) {
                selectedInvoiceItemData.vat = 0;
                selectedInvoiceItemData.vatCode = "NN";
            }

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

            if (selectedInvoiceItemData != null) {
                var invoiceItem = {
                    AcKey: $("#AcKey").val() ? $("#AcKey").val() : null,
                    Ident: selectedInvoiceItemData.id,
                    AnNo: 0,
                    Name: selectedInvoiceItemData.name_only,
                    Quantity: formatDisplay($("#DefaultDecimalPlacesQuantity").val(), selectedInvoiceItemData.measurementUnit == $("#MeusurementUnitDay").val() ? $("#DaysForValid").val() : selectedInvoiceItemData.quantity, true),
                    Price: formatDisplay($("#DefaultDecimalPlacesPrice").val(), selectedInvoiceItemData.price, true),
                    RetailPrice: formatDisplay($("#DefaultDecimalPlacesPrice").val(), selectedInvoiceItemData.retailPrice, true),
                    OriginalPrice: formatDisplay($("#DefaultDecimalPlacesPrice").val(), selectedInvoiceItemData.price, true),
                    Rebate: formatDisplay($("#DefaultDecimalPlacesPrice").val(), selectedInvoiceItemData.rabate, true),
                    VAT: formatDisplay($("#DefaultDecimalPlacesPrice").val(), selectedInvoiceItemData.vat, true),
                    VATCode: selectedInvoiceItemData.vatCode,
                    VATFiscalCode: selectedInvoiceItemData.vatFiscalCode,
                    Note: "",
                    UM: selectedInvoiceItemData.measurementUnit,
                    Value: 0,
                    OriginalValue: 0,
                    QtyDispDoc: 0,
                    DeliveryDeadline: $("#DeliveryDeadline").val(),
                    CostDrv: selectedInvoiceItemData.costDrv ? selectedInvoiceItemData.costDrv : "",
                    Department: dept,
                    TotalPrice: 0,
                    LastPrice: 0,
                    ColorCode: selectedInvoiceItemData.colorCode,
                    Worker: selectedInvoiceItemData.worker,
                    FixedAsset: selectedInvoiceItemData.fixedAsset,
                    FixedAssetName: selectedInvoiceItemData.fixedAssetName,
                    PrstTime: selectedInvoiceItemData.prstTime,
                    PrstUMTime: selectedInvoiceItemData.prstUMTime,
                    StartTime: selectedInvoiceItemData.timeStart,
                    EndTime: selectedInvoiceItemData.timeEnd,
                    SerialNo: selectedInvoiceItemData.serialNo,
                    DateDue: selectedInvoiceItemData.dateDue,
                    PackQty: 0,
                    ExciseInc: 0,
                    ExciseNotInc: 0,
                    ExciseIncP: 0,
                    ExciseNotIncP: 0
                }

                var insert = !invoiceItem.AcKey;
                if (insert)
                    await onClickSave();

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

                displayLoading(true);
                invoiceItem.AcKey = $("#AcKey").val() ? $("#AcKey").val() : null;

                $.post('@Url.Action("SaveIdent", "Order")', invoiceItem).done(function (response) {
                    if (!response.success) {
                        if (!response.result)
                            displayPopupError($("#GeneralErrorMessage").val());
                        else if (response.result.Error)
                            displayPopupError(response.result.Error);
                        else if (!response.result.Item)
                            displayPopupError($("#GeneralErrorMessage").val());
                        else if (response.result.Item.Error)
                            displayPopupError(response.result.Item.Error);
                    }
                    else {
                        let item = response.result.Item;
                        item.DeliveryDeadline = item.DeliveryDeadline ? moment(item.DeliveryDeadline) : item.DeliveryDeadline;
                        item.OriginalPrice = invoiceItem.OriginalPrice;
                        item.OriginalValue = invoiceItem.OriginalValue;
                        item.SerialNo = invoiceItem.SerialNo;
                        item.DateDue = invoiceItem.DateDue;
                        item.PricesForSelect = selectedInvoiceItemData.pricesForSelect;
                        item.ExciseInc = item.ExciseInc;
                        item.ExciseNotInc = item.ExciseNotInc;
                        item.ExciseIncP = item.ExciseIncP;
                        item.ExciseNotIncP = item.ExciseNotIncP;

                        invoiceItems.push(item);
                        appendIdentToTable(item, true);
                        checkForIdentNegativeQuantity();
                        updatePriceTable(response.result);
                        displayLoading(false);
                        $("a[href='#calendar']").addClass("hidden");
                        $("a[href='#mini-calendar']").removeClass("hidden");
                        getOrdersByDateMini();
                    }

                    displayLoading(false);
                });
            }
        }

        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 () {
                            canDelete(anNo);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        async function saveIdent(anNo) {
            if (isSaving === true)
                return;

            setChangedIdentData(anNo);
            var item = getInvoiceItem(anNo);
            if (!item)
                return;

            item.DeliveryDeadline = item.DeliveryDeadline != null ? moment(item.DeliveryDeadline).toISOString() : null;
            item.Quantity = formatDisplay($("#DefaultDecimalPlacesQuantity").val(), item.Quantity, true);
            item.Price = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.Price, true);
            item.RetailPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.RetailPrice, true);
            item.TotalPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.TotalPrice, true);
            item.Rebate = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.Rebate, true);
            item.VAT = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.VAT, true);
            item.QtyDispDoc = formatDisplay($("#DefaultDecimalPlacesQuantity").val(), item.QtyDispDoc, true);
            item.Value = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.Value, true);
            item.LastPrice = 0;
            item.SetItemRTPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.SetItemRTPrice, true);
            item.SetItemWSPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.SetItemWSPrice, true);
            item.SetItemWSPrice2 = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.SetItemWSPrice2, true);
            item.SetItemPrStPrice = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.SetItemPrStPrice, true);
            item.PackQty = formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.PackQty, true);

            return $.post('@Url.Action("SaveIdent", "Order")', { model: item }).done(function (response) {
                if (!response.success) {
                    if (!response.result)
                        displayPopupError($("#GeneralErrorMessage").val());
                    else if (response.result.Error)
                        displayPopupError(response.result.Error);
                    else if (!response.result.Item)
                        displayPopupError($("#GeneralErrorMessage").val());
                    else if (response.result.Item.Error)
                        displayPopupError(response.result.Item.Error);
                }
                else {
                    onSuccessfulIdentSave(response, item);
                }
            });
        }

        function onSuccessfulIdentSave(response, item) {
            response.result.Item.DeliveryDeadline = item.DeliveryDeadline != null ? moment(item.DeliveryDeadline).toISOString() : null;
            response.result.Item.OriginalPrice = item.OriginalPrice;
            response.result.Item.OriginalValue = item.OriginalValue;

            invoiceItems[invoiceItems.indexOf(item)] = response.result.Item;

            isSaving = true;
            updateIdentRow(response.result.Item);
            updatePriceTable(response.result);
            checkForIdentNegativeQuantity();
            isSaving = false;
            checkIfTaxReverseItemsExist();
        }

        function onChangeIdentValue(anNo) {
            var newPrice = toNumber($("#value-" + anNo).val()) / toNumber($("#quantity-" + anNo).val());

            $("#price-" + anNo).val(newPrice);
            $("#rabate-" + anNo).val(0);
            saveIdent(anNo);
        }

        function changeIdentRetailPrice(anNo) {
            let item = getInvoiceItem(anNo);

            var newPrice = toNumber($("#retailPrice-" + anNo).val()) - toNumber(item.ExciseInc) - (toNumber(item.ExciseInc) * (toNumber(item.VAT) / 100)) - toNumber(item.ExciseNotInc);
            newPrice = newPrice / ((1 + toNumber(item.ExciseIncP) / 100) * (1 + toNumber(item.VAT) / 100) + toNumber(item.ExciseNotIncP) / 100);

            $("#price-" + anNo).val(newPrice);
            formatNumberInput($("#price-" + anNo));
            saveIdent(anNo);
        }

        function changeIdentPrice(anNo) {
            let item = getInvoiceItem(anNo);

            var newRetailPrice = ((toNumber($("#price-" + anNo).val()) * (1 + toNumber(item.ExciseIncP) / 100)) + toNumber(item.ExciseInc)) * (1 + toNumber(item.VAT) / 100);
            newRetailPrice = newRetailPrice + (toNumber($("#price-" + anNo).val()) * (toNumber(item.ExciseNotIncP) / 100)) + toNumber(item.ExciseNotInc);

            $("#retailPrice-" + anNo).val(newRetailPrice);
            formatNumberInput($("#retailPrice-" + anNo));
            saveIdent(anNo);
        }

        async function changeIdentQuantity(anNo) {
            await saveIdent(anNo);
            if($("#OrderType").val() === "@OrderType.Supplier")
                checkIdentSerialNo(anNo, "O");
            else
                checkIdentSerialNoIssue(anNo, "O");
        }

        async function changeIdentPackQty(anNo) {
            if ($("#CalcPackQty").val() === "True") {
                $.get("@Url.Action("GetById", "SetItem")" + "?id=" + $("#id-" + anNo).val(),
                    function (response) {
                        var faktor;
                        var result = 0;

                        if ($("#ItemMethCalcUM2Qntty").val() === "2")
                            faktor = toNumber(response.UmtoUm2);
                        else if ($("#ItemMethCalcUM2Qntty").val() === "3")
                            faktor = toNumber(response.UmtoUm3);
                        else
                            faktor = 1;

                        if ($("#ItemUM2QnttyRound").val() === "@Status.Active")
                            result = evenRound((toNumber($("#packQty-" + anNo).val()) * faktor) + 0.49, 0);
                        else if ($("#RoundQntty").val() !== 0)
                            result = evenRound(toNumber($("#packQty-" + anNo).val()) * faktor, toNumber($("#RoundQntty").val()));
                        else
                            result = toNumber($("#packQty-" + anNo).val()) * faktor;

                        if ($("#quantity-" + anNo).val() !== result) {
                            $("#quantity-" + anNo).val(result);
                            formatNumberInput($("#quantity-" + anNo));
                        }

                        saveIdent(anNo);
                    });
            } else
                saveIdent(anNo);
        }

        function changeIdentData(anNo) {
            if (isSaving === true)
                return;

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

            $.get("@Url.Action("CanDelete", "Order")"
                + "?acKey=" + $("#AcKey").val()
                + "&type=" + ($("#OrderType").val() === "@OrderType.Buyer" ? "@CashRegType.OrdersBuyers" : "@CashRegType.OrdersSuppliers")
                + "&anNo=" + anNo,
                function (response) {
                    if (response.ShowError === true && response.HasWorkOrder === true) {
                        $().customModal({
                            title: "",
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: stringFormat('@Loc.OrderIdentTransferredOnWorkOrderConfirm', response.WorkOrderAcKey),
                            buttons: [
                                {
                                    icon: 'fa fa-times',
                                    text: '@Loc.Cancel',
                                    closeOnAction: true,
                                    action: function () {
                                        isSaving = true;
                                        var item = getInvoiceItem(anNo);
                                        updateIdentRow(item);
                                        isSaving = false;
                                    },
                                    type: 'ghost'
                                },
                                {
                                    icon: 'fa fa-check',
                                    text: '@Loc.Confirm',
                                    action: function () {
                                        saveIdent(anNo);
                                    },
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    } else {
                        saveIdent(anNo);
                    }
                })
                .done(function () {
                    getOrdersByDateMini();
                });
        }

        function setChangedIdentData(anNo) {
            let item = getInvoiceItem(anNo);
            if (!item)
                return;

            item.AcKey = $("#acKey-" + anNo).val();
            item.Note = $("#note-" + anNo).val();
            item.Ident = $("#id-" + anNo).val();
            item.Name = $("#name-" + anNo).val();
            item.Quantity = toNumber($("#quantity-" + anNo).val());
            item.UM = $("#measurementUnit-" + anNo + " option:selected").val();
            item.Price = toNumber($("#price-" + anNo).val());
            item.RetailPrice = toNumber($("#retailPrice-" + anNo).val());
            item.TotalPrice = toNumber($("#totalPrice-" + anNo).val());
            item.Rebate = toNumber($("#rabate-" + 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.Value = toNumber($("#value-" + anNo).val());
            item.QtyDispDoc = toNumber($("#qtyDispDoc-" + anNo).val());
            item.DeliveryDeadline = $("#deliveryDeadline-" + anNo).val() ? $("#deliveryDeadline-" + anNo).datepicker('getDate') : null;
            item.CostDrv = $("#costDrv-" + anNo).val();
            item.Department = $("#department-" + anNo).val();
            item.ColorCode = $("#colorCode-" + anNo).val();
            item.Worker = $("#worker-" + anNo).val();
            item.FixedAsset = $("#fixedAsset-" + anNo).val();
            item.StartTime = $("#startTime-" + anNo).val();
            item.PrstTime = $("#prstTime-" + anNo).val();
            item.PrstUMTime = $("#prstUMTime-" + anNo).val();
            item.EndTime = $("#endTime-" + anNo).val();
            item.PackQty = $("#packQty-" + anNo).val();
        }

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

        var selectedItemAnNo = '';
        function openNoteModal(anNo) {
            selectedItemAnNo = anNo;

            var note = $("#note-" + anNo).val();
            if (note)
                note = note.trim();

            $("#item-note").val(note);
            $("#noteModal").modal('show');
        }

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

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

            changeIdentData(selectedItemAnNo);

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

        function tryChangeIdentTotalPrice() {
            if (isSaving === true)
                return;

            $.get("@Url.Action("CanDelete", "Order")"
                + "?acKey=" + $("#AcKey").val()
                + "&type=" + ($("#OrderType").val() === "@OrderType.Buyer" ? "@CashRegType.OrdersBuyers" : "@CashRegType.OrdersSuppliers")
                + "&anNo=" + anNo,
                function (response) {
                    if (response.ShowError === true && response.HasWorkOrder === true) {
                        $().customModal({
                            title: "",
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: stringFormat('@Loc.OrderIdentTransferredOnWorkOrderConfirm', response.WorkOrderAcKey),
                            buttons: [
                                {
                                    icon: 'fa fa-times',
                                    text: '@Loc.Cancel',
                                    closeOnAction: true,
                                    action: function () {
                                        isSaving = true;
                                        var item = getInvoiceItem(anNo);
                                        updateIdentRow(item);
                                        isSaving = false;
                                    },
                                    type: 'ghost'
                                },
                                {
                                    icon: 'fa fa-check',
                                    text: '@Loc.Confirm',
                                    action: function () {
                                        changeIdentTotalPrice(anNo);
                                    },
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    } else {
                        changeIdentTotalPrice(anNo);
                    }
                });
        }

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

        function changeIdentTotalPrice(anNo) {
            var item = getInvoiceItem(anNo);

            if (isSaving === true || !item || item.TotalPrice === toNumber($("#totalPrice-" + anNo).val()))
                return;

            var price = formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#totalPrice-" + anNo).val(), true);
            return $.post('@Url.Action("ChangeIdentTotalPrice", "Order")', { model: { AcKey: $("#AcKey").val(), AnNo: anNo, Price: price } }).done(function (response) {
                if (!response.success) {
                    if (!response.result)
                        displayPopupError($("#GeneralErrorMessage").val());
                    else if (response.result.Error)
                        displayPopupError(response.result.Error);
                    else if (!response.result.Item)
                        displayPopupError($("#GeneralErrorMessage").val());
                    else if (response.result.Item.Error)
                        displayPopupError(response.result.Item.Error);
                }
                else {
                    onSuccessfulIdentSave(response, item);
                }
            });
        }

        function updatePriceTable(data) {
            if (!data)
                return;

            if ($("#AcKey").val() === '') {
                refreshArrows(data.AcKey, data.AcKeyView, $("#DocTypeSelect").val());
            }
            $("#AcKey").val(data.AcKey);
            $("#AcKeyDisplay").val(data.AcKeyView);
            $("#TotalAmount").val(data.Value);
            $("#DiscountAmount").val(data.Discount);
            $(".ToPayAmount").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), data.ForPay, false));
            $("#ToPayAmountSub").val(formatDisplay($("#DefaultDecimalPlacesValue").val(), data.ForPay, false));
            $("#DiscountPercent").val(data.DiscountPercent);
            $("#Value").val(data.CalcSum);
            $("#TaxAmount").val(data.VAT);
            $("#ToPayAmountOurCurrency").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(data.CurrencyValue, $("#RoundValue").val()), false));

            let pageUrl = '@Model.OrderType' === '@PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer' ? '@Url.Action("EditBuyerOrder", "Order")' : '@Url.Action("EditSupplierOrder", "Order")';
            window.history.pushState({}, null, pageUrl+ '?id=' + data.AcKey);

            formatNumberInput($("#TotalAmount"));
            formatNumberInput($("#DiscountAmount"));
            formatNumberInput($(".ToPayAmount"));
            formatNumberInput($("#ToPayAmountSub"));
            formatNumberInput($("#DiscountPercent"));
            formatNumberInput($("#TaxAmount"));
            formatNumberInput($("#Value"));
            formatNumberInput($("#ToPayAmountOurCurrency"));
        }

        function updateIdentRow(item) {
            $("#acKey-" + item.AnNo).val(item.AcKey);
            $("#note-" + item.AnNo).val(item.Note);
            $("#id-" + item.AnNo).val(item.Ident);
            $("#name-" + item.AnNo).val(item.Name);
            $("#quantity-" + item.AnNo).val(item.Quantity);
            $("#measurementUnit-" + item.AnNo).val(item.UM);
            $("#price-" + item.AnNo).val(item.Price);
            $("#retailPrice-" + item.AnNo).val(item.RetailPrice);
            $("#totalPrice-" + item.AnNo).val(item.TotalPrice);
            $("#rabate-" + item.AnNo).val(item.Rebate);
            $("#vat-" + item.AnNo).val(item.VATCode);
            $("#value-" + item.AnNo).val(item.Value);
            $("#lastPrice-" + item.AnNo).val(item.LastPrice);
            $("#qtyDispDoc-" + item.AnNo).val(item.QtyDispDoc);
            $("#packQty-" + item.AnNo).val(item.PackQty);
            if (item.DeliveryDeadline)
                $("#deliveryDeadline-" + item.AnNo).datepicker('setDate', new Date(item.DeliveryDeadline));

            formatNumberInput($("#quantity-" + item.AnNo));
            formatNumberInput($("#price-" + item.AnNo));
            formatNumberInput($("#retailPrice-" + item.AnNo));
            formatNumberInput($("#totalPrice-" + item.AnNo));
            formatNumberInput($("#rabate-" + item.AnNo));
            formatNumberInput($("#value-" + item.AnNo));
            formatNumberInput($("#lastPrice-" + item.AnNo));
            formatNumberInput($("#qtyDispDoc-" + item.AnNo));
            formatNumberInput($("#packQty-" + item.AnNo));

            var priceWithMargin = item.LastPrice + (item.LastPrice / 100 * toNumber($("#AcctMinProfMarginOrder").val()));
            if (item.Value < priceWithMargin && $("#OrderType").val() === "@OrderType.Buyer")
                $("#value-" + item.AnNo).addClass("text-danger");
            else
                $("#value-" + item.AnNo).removeClass("text-danger");
        }

        function onSaveOrPrint(option, printType = null) {
            if ($("#AcKey").val()) {
                displayLoading(true);
                $.get("@Url.Action("CanDelete", "Order")"
                    + "?acKey=" + $("#AcKey").val()
                    + "&type=" + ($("#OrderType").val() === "@OrderType.Buyer" ? "@CashRegType.OrdersBuyers" : "@CashRegType.OrdersSuppliers")
                    + "&anNo=" + null,
                    function (response) {
                        if (response.ShowError === true && response.HasCashExpenditureOrTransfer === true) {
                            $("#deleteOrderWarningMessage").text(stringFormat("@Loc.OrderAssociatedCashExpenditureOrTransfer", $("#AcKey").val()));
                            $("#continueOrderDeleteDocument").attr('onclick', 'onClickSave("' + option + '", "' + printType + '")');
                            $("#deleteOrderWarningModal").modal("show");
                        } else {
                            onClickSave(option, printType);
                        }
                        displayLoading(false);
                    });
            } else {
                onClickSave(option, printType);
            }
        }

        var printWindow;
        onClickSave = async function (option, printType = null) {
            var insert = !$("#AcKey").val();

            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 ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS"
                && (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview')
                && $("#AcKey").val()
                && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")
                && ($("#FiscalCode").val() || $("#ProtectionCode").val())) {

                if (option === '@InvoiceSaveType.SaveAndPreview') {
                    await handleSaveOption(option, printType);
                    return;
                } else {
                    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'
                            }
                        ]
                    });
                }
                return;
            }

            if (!insert) {
                displayLoading(true);
                for (let index = 0; index < invoiceItems.length; index++) {
                    await saveIdent(invoiceItems[index].AnNo);
                }
                displayLoading(false);
            }

            await save(option, printType);
        }

        function setInvoiceCreatedData(response) {
            $("#AcKey").val(response.data.AcKey);
            $("#AcKeyDisplay").val(response.data.AcKeyDisplay);
            refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
            $("#NoteClerkId").val(response.data.NoteClerkId);
            $("#Clerk").val(response.data.ClerkId);
            $("#DocTypeSelect").attr("disabled", true);
            $("#OrderForm").val(response.data.OrderForm);
            $("#invoiceDelete").removeClass("hidden");
            $("#wizardButton").attr("disabled", false);
            $("#wizardButton + button").attr("disabled", false);
            var pageUrl = '@Model.OrderType' === '@PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer' ? '@Url.Action("EditBuyerOrder", "Order")' : '@Url.Action("EditSupplierOrder", "Order")';
            window.history.pushState({}, null, pageUrl + '?id=' + response.data.AcKey);
            clearValidationErrors();
        }

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

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

            $("#Statement").val($("#Statements").val() ? $("#Statements").val().toString() : "");
            let formData = new FormData($("#PageForm")[0]);
            formData.set('Note', $("#Note").val());
            formData.set('DaysForValid', formatDisplay(0, $("#DaysForValid").val()));
            formData.set('DaysForPayment', formatDisplay(0, $("#DaysForPayment").val()));
            formData.set('FXRate', formatDisplay($("#FxRate").attr("step"), $("#FxRate").val()));
            formData.set('Date', $("#Date").datepicker("getDate").toISOString());
            formData.set('CanFiscalize', false);

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

            let url = '@Url.Action("SaveOrder", "Order")';
            await fetch(url, {
                method: "POST",
                body: formData
            }).then((response) => response.json()
            ).then(async (response) => {
                clearValidationErrors();
                if (response.Success) {
                    if (!$("#AcKey").val()) {
                        $("#wizardButton").attr("disabled", false);
                        $("#wizardButton + button").attr("disabled", false);
                        $("#invoiceDelete").removeClass("hidden");
                        $("#newOrderButton").removeClass("hidden");
                        $("#orderDuplicate").removeClass("hidden");
                        setInvoiceCreatedData(response);
                    }

                    if (response.result)
                        updatePriceTable(response.result);

                    $("#DocTypeSelect").attr("disabled", true);

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

                        $("#errorModalMessage").text(errorText);
                        $("#errorModal").modal('show');
                    } else {
                        await handleSaveOption(option, printType);
                    }
                }
                else {
                    if (printWindow) {
                        printWindow.close();
                    }

                    if (response.errors)
                        displayResponseValidationErrors(response);
                    else if (!response.result)
                        displayPopupError($("#GeneralErrorMessage").val());
                    else if (response.result.Error)
                        displayPopupError(response.result.Error);
                }

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

        async function handleSaveOption(option, printType) {
            if (option == '@InvoiceSaveType.SaveAndNew')
                window.location.href = ('@Model.OrderType' === '@PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer' ?
                    '@Url.Action("CreateBuyerOrder", "Order")' : '@Url.Action("CreateSupplierOrder", "Order")');
            else if (option === '@InvoiceSaveType.SaveAndClose')
                window.location.href = ('@Model.OrderType' === '@PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer' ?
                    '@Url.Action("BuyerOrdersReport", "Order")' : '@Url.Action("SupplierOrdersReport", "Order")')
            else if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
                var fisc = false;
                if ($("#CanFiscalize").val() ?.toLowerCase() === "true" && option !== '@InvoiceSaveType.SaveAndPreview' &&
                    ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR" || "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS"))
                    fisc = true;

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

                let pinUrlLpfr = $("#DocTypeSelect option:selected").attr("data-pinUrlLpfr");
                await printPAAS(printType, fisc, option === '@InvoiceSaveType.SaveAndPreview', undefined, undefined, undefined, undefined, undefined,
                    '@Url.Action("LPFRUpdateInvoice", "Move")', pinUrlLpfr && $("#FiscalStatus").val() === "4" ? "@Url.Action("GetLpfrFiscalizationData", "Move")" + "?acKey=" + $("#AcKey").val() : undefined);
            } else if (option === '@InvoiceSaveType.SaveAndChangeCurrency') {
                changeOrderCurrency();
            } else if (option === '@InvoiceSaveType.SaveAndChangeFxRate') {
                changeFxRate();
            } else
                checkFormEditable();
        }

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

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.get('@Url.Action("OrderItems", "Order")?acKey=' + $("#AcKey").val()
                + ($("#OrderType").val() === "@OrderType.Buyer" ? "&subject=" + $("#ReceiverId").val()
                    + "&subjectType=" + $("#WayOfSale").val()
                    + "&saleType=P" : ""),
                function (data) {
                    invoiceItems = [];
                    isSaving = true;

                    for (var i = 0; i < data.length; i++) {
                        data[i].DeliveryDeadline = data[i].DeliveryDeadline ? moment(data[i].DeliveryDeadline) : null;
                        data[i].OriginalPrice = data[i].Price;
                        data[i].OriginalValue = data[i].Value;

                        appendIdentToTable(data[i]);
                        invoiceItems.push(data[i]);
                    }

                    isSaving = false;
                    checkForIdentNegativeQuantity();
                    checkFormEditable();
                    swapLoadingIcon(false, "add-position", "fa fa-plus");
                    checkIfTaxReverseItemsExist();

                    if (data.length > 0) {
                        displayShowHideDropdown();
                    }
                }, "json")
                .done(function () {
                    hasTableLoaded = true;
                    getOrdersByDateMini();
                });
        }

        var subjectType;
        var isCalendar;
        function openSubjectModal(subject, fromCalendar = false) {
            clearValidationErrors();
            $('#subjectModal form')[0].reset();
            subjectType = subject;
            isCalendar = fromCalendar;
            $("#Name").val($("#" + subjectType).val());
            $("#subjectModal").modal('show');
        }

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

            $.post('@Url.Action("CreateFromPartial", "Subjects")', formData)
                .done(function (response) {
                    clearValidationErrors();
                    if (response.Success) {
                        if (isCalendar) {
                            $("[data-id='customerTInput']").attr("title", response.subject.Name)
                            $("[data-id='customerTInput'] .filter-option-inner-inner").text(response.subject.Name)
                            $("#customerTInput option:first-child").attr("value", response.subject.Id);
                            $("#customerTInput option:first-child").text(response.subject.Id);
                        } else {
                            createSubjectSetValues("Consignee", response.subject.Id);
                            createSubjectSetValues("Receiver", response.subject.Id);

                            var receiverAddress = response.subject.Address + (!response.subject.ZipCode ? "" : ", " + response.subject.ZipCode) + (!response.subject.VAT ? "" : ", " + response.subject.VAT);
                            $("#" + subjectType + "AddressContainer").text(receiverAddress);
                        }

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

        function deleteInvoice() {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "removeOrderAlertModal",
                type: "question",
                text: $("#OrderType").val() === '@PantheonRA.WebApi.Contracts.Enums.OrderType.Buyer' ? "@Loc.DeleteBuyerOrder" : "@Loc.DeleteSupplierOrder",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: async function () {
                            canDelete();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function showFiscalData() {
            if ($("#CanFiscalize").val() === "True" || $("#CanFiscalize").val() === "true") {
                $(".fiscalizeData").removeClass("hidden");
                $("#Date").datepicker("update", $("#Date").val() != null ? $("#Date").val() : new Date());
                $("#Date").addClass("hidden");
                $("#FiscalDate").removeClass("hidden");
            } else {
                $(".fiscalizeData").addClass("hidden");
                $("#Date").removeClass("hidden");
                $("#FiscalDate").addClass("hidden");
            }
        }

        function checkFormEditable() {
            if ($("#FiscalCode").val()) {
                $("#PageForm :input").prop("disabled", true);
                $("#PageForm :input").closest("div:not(.form-group)").addClass("document-head-disabled-input");
                $("#invoiceDelete").prop("disabled", true);
                $("#printButton").prop("disabled", false);
                $("#printButton + button").prop("disabled", false);
                $("#copyButton").prop("disabled", false);
                $("#wizardButton").prop("disabled", false);
                $("#wizardButton + button").prop("disabled", false);
                $("#saveButton").prop("disabled", false);
                $("#saveButton + button").prop("disabled", false);
                $(".identNote").prop("disabled", false);
                $("#orderDuplicate").prop("disabled", false);

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

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

            $(".wizardInput").attr("disabled", false);
        }

        function displayLoading(loading) {
            if ($("#FiscalCode").val() && "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS")
                return;

            if (loading) {
                swapLoadingIcon(true, "add-position", "fa fa-plus");
            }
            else {
                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }

            $("#PageForm input:not(.custom-typeahead-display, #IdentSearch)").prop("disabled", loading);
            $("#invoiceDelete").prop("disabled", loading);
            $("#printButton").prop("disabled", loading);
            $("#printButton + button").prop("disabled", loading);
            $("#copyButton").prop("disabled", loading);
            $("#orderDuplicate").prop("disabled", loading);

            if ($("#AcKey").val()) {
                $("#DocTypeSelect").attr("disabled", true);
                $("#DocTypeSelect").closest("div:not(.form-group)").addClass("document-head-disabled-input");
            }

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

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

        function changeIdentsDeliveryDeadline() {
            for (var i = 0; i < invoiceItems.length; i++) {
                invoiceItems[i].DeliveryDeadline = $("#DeliveryDeadline").val();
                $("#deliveryDeadline-" + invoiceItems[i].AnNo).datepicker('setDate', new Date($("#DeliveryDeadline").datepicker('getDate')));
            }
        }

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

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

            setNoteIcon();

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

        function saveNotePost(note, anNo) {
            $.post('@Url.Action("SaveNote", "Order")', {
                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'
                            }
                        ]
                    });
                }
            });
        }

        function createNewDocumentModal() {
            $('[href="#createDocTab"]').tab('show');
            $("#DocumentAcKey").val($("#AcKey").val());
            $("#createDocumentModal").modal("show");
        }

        var createdDocAcKey = "";
        var createdDocUrl = "";
        function createNewDocument() {
            var formData = $("#createDocumentForm").serializeArray();

            swapLoadingIcon(true, "createNewDocumentBtn", "");
            $.post('@Url.Action("CreateNewDocument", "Order")', formData)
                .done(function (response) {
                    if (response.Items && response.Items.length > 0) {
                        getTransferStatistic(response.Items);
                    }

                    if (response.Success) {
                        createdDocAcKey = response.AcKey;
                        createdDocUrl = response.Url;
                        $("#createdDocumentAcKey").text(createdDocAcKey);
                        $("#connectionsContainer").attr("hidden", false);
                        addConnection(createdDocAcKey, response.Price, response.Url, response.AcKeyDisplay);

                        if (("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.HR" ||
                            "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.SI") &&
                            (response.Status === "T" || response.Status === "C") && $("#DeliveryDeadline").datepicker('getDate') > $("#CreateDate").datepicker('getDate')) {
                            $("#createdDocDateWarningModal").modal("show");
                        } else {
                            $().customModal({
                                title: "",
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "success",
                                text: "@Loc.AddingCompletedTransfered",
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: '@Loc.Confirm',
                                        action: function () {
                                            addingComplete();
                                        },
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                    else {
                        clearValidationErrors();

                        if (response.Items)
                            addingComplete();

                        if (response.errors)
                            displayResponseValidationErrors(response, "createDocumentForm");

                        if (response.Error) {
                            $("#createDocumentModal").modal('hide');
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: false,
                                id: "createDocumentErrorModal",
                                type: "alert",
                                text: response.Error,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Close",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                    swapLoadingIcon(false, "createNewDocumentBtn", "");
                });
        }

        function getTransferStatistic(items) {
            if (!items)
                return;

            $dataTable = $('#statistics-grid');
            if ($.fn.dataTable.isDataTable('#statistics-grid'))
                $dataTable.DataTable().destroy();

            $dataTable.DataTable({
                serverSide: false,
                ajax: undefined,
                data: items,
                columns: [
                    { data: "PositionShort" },
                    { data: "DocumentOn" },
                    { data: "PositionOn" },
                    { data: "Ident" },
                    { data: "Title", render: $.fn.dataTable.render.ellipsis(30) },
                    { data: "RequiredQuantity", className: 'dt-body-right' },
                    { data: "AddedQuantity", className: 'dt-body-right' },
                    { data: "UM" },
                    { data: "Comment" },
                    {
                        data: "MessageType",
                        render: function (data, type, full) {
                            if (data === "W" && full.AddedQuantity > 0) {
                                setQtyDispDoc(full.PositionShort, full.AddedQuantity);
                                return '<span class="label label-primary">' + "@Loc.PartiallyTransferred" + '</span>';
                            } else if (data === "I") {
                                setQtyDispDoc(full.PositionShort, full.AddedQuantity);
                                return '<span class="label label-grey"> ' + "@Loc.Transferred" + '</span>';
                            } else {
                                return '<span class="label label-danger"> ' + "@Loc.NotTransferred" + '</span>';
                            }
                        },
                        className: 'dt-body-right'
                    }
                ]
            });

            $dataTable.DataTable().rows().recalcHeight().draw();
        }

        function addingComplete() {
            $('[href="#transferStatisticTab"]').tab('show');
        }

        function redirectToDocument(acKey, typeOfDoc) {
            if (typeOfDoc)
                dtType = typeOfDoc;
            if (acKey)
                createdDocAcKey = acKey;
            if (createdDocAcKey && $("#OrderType").val() === "@OrderType.Buyer" && dtType === "@TypeOfDoc.AdvancePayment")
                window.location = "@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")" + "?id=" + createdDocAcKey;
            else if (createdDocAcKey && $("#OrderType").val() === "@OrderType.Supplier" && dtType === "@TypeOfDoc.AdvancePayment")
                window.location = "@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")" + "?id=" + createdDocAcKey;
            else if (createdDocAcKey && $("#OrderType").val() === "@OrderType.Buyer" && (dtType === "@TypeOfDoc.Material" || dtType === "@TypeOfDoc.Wholesale"))
                window.location = "@Url.Action("Edit", "Wholesale")" + "?id=" + createdDocAcKey;
            else if (createdDocAcKey && $("#OrderType").val() === "@OrderType.Supplier" && (dtType === "@TypeOfDoc.Material" || dtType === "@TypeOfDoc.ReceivedBill"))
                window.location = "@Url.Action("Edit", "ReceivedBills")" + "?id=" + createdDocAcKey;
        }

        function redirectToUrlWithAcKey(url) {
            if (url)
                window.location = url;
        }

        function canceledLink(ackey) {
            if($("#OrderType").val() === "@OrderType.Buyer")
                location.href = '@Url.Action("EditBuyerOrder", "Order")?id=' + ackey;
            else
                location.href = '@Url.Action("EditSupplierOrder", "Order")?id=' + ackey;
        }

        function setQtyDispDoc(anNo, quantity) {
            $("#qtyDispDoc-" + anNo).val(quantity);
            formatNumberInput($("#qtyDispDoc-" + anNo));
        }

        function fixCreatedDocumentDate() {
            $.post('@Url.Action("CreatedDocumentUpdateDate", "Order")', { AcKeyOrder: $("#AcKey").val(), AcKeyMove: createdDocAcKey })
                .done(function (response) {
                    $("#createdDocDateWarningModal").modal('hide');
                });
        }

        function openCreateDocDateWarningHelp() {
            window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.CreateDocFromOrderInstructionsUrl)', '_blank');
        }

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

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

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

                if (response && deliveryType) {
                    var consigneeDelivery;
                    var receiverDelivery;

                    if (consigneeTypeaheadData && receiverTypeaheadData) {
                        if ($("#OrderType").val() === "@OrderType.Buyer") {
                            consigneeDelivery = consigneeTypeaheadData.delivery;
                            receiverDelivery = receiverTypeaheadData.delivery;
                        } else {
                            consigneeDelivery = consigneeTypeaheadData.suppDelivery;
                            receiverDelivery = receiverTypeaheadData.suppDelivery;
                        }
                    }

                    if (deliveryType === "@DeliveryFillType.FirstPerson") {
                        if (consigneeTypeaheadData && consigneeDelivery)
                            $("#DeliveryType").val(consigneeDelivery);
                        else
                            getSubjectDeliveryType($("#ConsigneeId").val());
                    } else if (deliveryType === "@DeliveryFillType.ThirdPerson") {
                        if (receiverTypeaheadData && receiverDelivery)
                            $("#DeliveryType").val(receiverDelivery);
                        else
                            getSubjectDeliveryType($("#ReceiverId").val());
                    }
                }
            });
        }

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

        function openCreateDocumentHelp() {
            window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.OrderCreateDocument)', '_blank');
        }

        function openCreateDocumentUserManualHelp() {
            if ($("#OrderType").val() === "@OrderType.Buyer")
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleOrderBuyerCreateInvoice)', '_blank');
            else
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleOrderSupplierCreateInvoice)', '_blank');
        }

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

        function openCreateAdvancePayment() {
            $("#AdvancePaymentOrderValue").val($("#ToPayAmount").text());
            $("#AdvancePaymentValue").val($("#ToPayAmount").text());
            $(".currencyAddon").text($("#OrderCurrency").val());

            if ("@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && ($("#DocTypeSelect option:selected").attr("data-fiscalize") === "True" || $("#CanFiscalize").val() === "True")) {
                $("#CreateAdvPayIsFiscal").val(true);
                $("#AdvancePaymentIdentCheckedContainer").addClass("hidden");
                $("#AdvancePaymentIdentContainer").removeClass("col-xs-5 padding-right-none").addClass("col-xs-7");
            } else {
                $("#CreateAdvPayIsFiscal").val(false);
                $("#AdvancePaymentIdentCheckedContainer").removeClass("hidden");
                $("#AdvancePaymentIdentContainer").removeClass("col-xs-7").addClass("col-xs-5 padding-right-none");
            }

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

        function checkCreateAdvancePayment() {
            $.get("@Url.Action("GetAdvancePaymentsForOrder", "AdvancePayment")?acKey=" + $("#AcKey").val(), function (response) {
                if (response && response.length > 0) {
                    $().customModal({
                        title: "",
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "question",
                        text: "@Loc.AdvancePaymentAlreadyExists",
                        buttons: [
                            {
                                icon: 'fa fa-times',
                                text: '@Loc.Cancel',
                                closeOnAction: true,
                                type: 'ghost'
                            },
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.Confirm',
                                action: function () {
                                    createAdvancePayment();
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else
                    createAdvancePayment();
            });
        }

        function createAdvancePayment() {
            if (!$("#AdvancePaymentIdent").val()) {
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.IdentIsRequired",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.OK',
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }

            swapLoadingIcon(true, "createAdvancePaymentBtn", "fa fa-check");
            $.post('@Url.Action("CreateAdvancePayment", "AdvancePayment")', {
                AcKey: $("#AcKey").val(),
                DocType: $("#AdvancePaymentDocType").val(),
                Owner: "N",
                AnNo: -1,
                DateType: -1,
                NoteText: stringFormat("@Loc.AdvancePaymentFromOrderNoteText", $("#AdvancePaymentPercent").val() + "%", $("#AcKey").val()),
                Date: $("#AdvancePaymentDate").val(),
                DateBeforeVAT: $("#AdvancePaymentDateBeforeVAT").val(),
                Ident: $("#AdvancePaymentIdent").val(),
                Percent: $("#AdvancePaymentPercent").val(),
                IdentChecked: "@PantheonRA.BackOffice.CurrentUser.Localization" === "@Localization.Code.RS" && $("#CreateAdvPayIsFiscal").val() === "true" ? true : $("#AdvancePaymentIdentChecked").prop("checked"),
                CreateByVAT: $("#AdvancePaymentByVatChecked").prop("checked")
            }).done(function (response) {
                if (response && response.AcKey) {
                    if ($("#OrderType").val() === "@OrderType.Buyer")
                        window.open('@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")?id=' + response.AcKey, "_self");
                    else
                        window.open('@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=' + response.AcKey, "_self");
                } else {
                    swapLoadingIcon(false, "createAdvancePaymentBtn", "fa fa-check");

                    if (response.errors)
                        displayAdvancePaymentValidationErrors(response);

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

        function openCreateAdvancePaymentModalHelp() {
            if ($("#OrderType").val() === "@OrderType.Buyer")
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentOrderBuyer)', '_blank');
            else
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentOrderSupplier)', '_blank');

        }

        function openUserManualHelp() {
            if ($("#OrderType").val() === "@OrderType.Buyer")
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleOrderBuyerCreateAdvancePayment)', '_blank');
            else
                window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleOrderSupplierCreateAdvancePayment)', '_blank');
        }

        var canDeleteResponse;
        var deleteErrorChecked = [];

        function canDelete(anNo) {
            deleteErrorChecked = [];
            if ($("#CanFiscalize").val() === true && @PantheonRA.BackOffice.CurrentUser.Localization === @Localization.Code.HR)
                showDefaultErrorCustomModal('@Loc.DocumentAlreadyFiscalizedDeleteNotPossible', '@Loc.Confirm');

            displayLoading(true);
            $.get("@Url.Action("CanDelete", "Order")"
                + "?acKey=" + $("#AcKey").val()
                + "&type=" + ($("#OrderType").val() === "@OrderType.Buyer" ? "@CashRegType.OrdersBuyers" : "@CashRegType.OrdersSuppliers")
                + "&anNo=" + (anNo ? anNo : null),
                function (response) {
                    canDeleteResponse = response;
                    canDeleteResponse.anNo = anNo;

                    if (response.ShowError === true) {
                        checkErrorsForDelete(anNo);
                    } else {
                        if (anNo)
                            deletePosition(anNo);
                        else
                            location.href = '@Url.Action("DeleteOrder", "Order")?acKey=' + $("#AcKey").val() + '&orderType=' + $("#OrderType").val();
                    }
                    displayLoading(false);
                });
        }

        function hasErrorAlreadyBeenChecked(error) {
            return deleteErrorChecked.indexOf(error) > -1;
        }

        function checkErrorsForDelete(deleteBPBI) {
            if (canDeleteResponse.IsLastDoc === false && !canDeleteResponse.anNo && hasErrorAlreadyBeenChecked("IsLastDoc") === false) {
                deleteErrorChecked.push("IsLastDoc");
                if ($("#CanFiscalize").val() === true && @PantheonRA.BackOffice.CurrentUser.Localization === @Localization.Code.HR)
                    showDefaultErrorCustomModal('@Loc.OrderDeleteNotLastDocumentFiscalization', '@Loc.Confirm');
                else
                    showDeleteConfirmationError('@Loc.DeleteWholeDocumentIsNotLastOne', '@Loc.Delete');
            } else if (canDeleteResponse.HasCashExpenditureOrTransfer === true && hasErrorAlreadyBeenChecked("HasCashExpenditureOrTransfer") === false) {
                deleteErrorChecked.push("HasCashExpenditureOrTransfer");
                $("#deleteOrderWarningMessage").text(stringFormat("@Loc.OrderAssociatedCashExpenditureOrTransfer", $("#AcKey").val()));
                $("#continueOrderDeleteDocument").attr('onclick', 'continueOrderDelete()');
                $("#deleteOrderWarningModal").modal("show");
            } else if (canDeleteResponse.MissingDeletePermission === true && hasErrorAlreadyBeenChecked("MissingDeletePermission") === false) {
                deleteErrorChecked.push("MissingDeletePermission");
                showDefaultErrorCustomModal('@Loc.PermissionForDeleteMissing', '@Loc.Confirm');
            } else if (canDeleteResponse.HasLinkMnemoOrder === true && hasErrorAlreadyBeenChecked("HasLinkMnemoOrder") === false) {
                deleteErrorChecked.push("HasLinkMnemoOrder");
                showDefaultErrorCustomModal('@Loc.DocumentTransferredToDocumentationDeleteNotPossible', '@Loc.Confirm');
            } else if (canDeleteResponse.HasWorkOrder === true && hasErrorAlreadyBeenChecked("HasWorkOrder") === false) {
                deleteErrorChecked.push("HasWorkOrder");
                showDefaultErrorCustomModal(stringFormat((canDeleteResponse.anNo ? '@Loc.OrderIdentTransferredOnWorkOrder' : '@Loc.OrderTransferredOnWorkOrder'), canDeleteResponse.WorkOrderAcKey), '@Loc.Confirm');
            } else if (canDeleteResponse.DocumentAddedToThePlan === true && hasErrorAlreadyBeenChecked("DocumentAddedToThePlan") === false) {
                deleteErrorChecked.push("DocumentAddedToThePlan");
                showDocumentPlanItemsModal(canDeleteResponse.DocumentPlanItems);
            } else if ($("#OrderType").val() === "@OrderType.Buyer" && canDeleteResponse.DocumentAddedToDispatchList === true
                && hasErrorAlreadyBeenChecked("DocumentAddedToDispatchList") === false) {
                deleteErrorChecked.push("DocumentAddedToDispatchList");
                showDefaultErrorCustomModal('@Loc.OrderIdentsDispatchedDeleteNotPossible', '@Loc.Confirm');
            } else if ($("#OrderType").val() === "@OrderType.Buyer" && canDeleteResponse.DocumentAddedToDispatchListWithoutQuantity === true
                && hasErrorAlreadyBeenChecked("DocumentAddedToDispatchListWithoutQuantity") === false) {
                deleteErrorChecked.push("DocumentAddedToDispatchListWithoutQuantity");
                showDeleteConfirmationError('@Loc.DispatchListCreatedForOrderIdents', '@Loc.Confirm');
            } else {
                if (canDeleteResponse.anNo)
                    deletePosition(canDeleteResponse.anNo);
                else
                    location.href = '@Url.Action("DeleteOrder", "Order")?acKey=' + $("#AcKey").val() + '&orderType=' + $("#OrderType").val() + '&deleteBPBI=' + deleteBPBI;
            }
        }

        function continueOrderDelete(deleteBPBI) {
            checkErrorsForDelete(deleteBPBI);
        }

        function deleteNotLastDoc() {
            checkErrorsForDelete();
        }

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

        function showDocumentPlanItemsModal(items) {
            var $dataTablePlanItems = $('#planItemsGrid');
            if ($.fn.dataTable.isDataTable('#planItemsGrid'))
                $dataTablePlanItems.DataTable().destroy();

            $dataTablePlanItems.DataTable({
                serverSide: false,
                ajax: undefined,
                scroller: false,
                responsive: false,
                paging: false,
                info: false,
                data: items,
                columns: [
                    { data: "AcKeyView" },
                    { data: "AnNo" }
                ]
            });

            $dataTablePlanItems.DataTable().rows().recalcHeight().draw();

            $("#deleteWarningPlanItemsModal").modal("show");
        }

        function showDeleteConfirmationError(error, primaryBtnText) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: error,
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.Cancel',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: primaryBtnText,
                        action: async function () {
                            checkErrorsForDelete();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function deletePosition(anNo, key = "", fromCalendar = false) {
            var ident = getInvoiceItem(anNo);
            if (!ident && !fromCalendar) return;
            let acKey = key != "" ? key : $("#AcKey").val();

            displayLoading(true);
            $.get('@Url.Action("RemoveIdent", "Order")', { acKey: acKey, anNo: anNo }).done(function (response) {
                invoiceItems = invoiceItems.filter(el => el !== ident);
                $("#position-" + anNo).remove();
                updatePriceTable(response);
                displayLoading(false);
                getOrdersByDateMini();
            });

            if (invoiceItems.length < 1 && (!$("#AcKey").val() || $("#AcKey").val() === "")) {
                $("#DocTypeSelect").attr("disabled", false);
                $("#sh-dropdown-menu").remove();
            }
        }

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

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

        function changeOrderCurrency() {
            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("OrderCurrencyChange", "Currency")',
                contentType: "application/json"
            }).done(function (response) {
                if (response) {
                    swapLoadingIcon(true, "add-position", "fa fa-plus");

                    $.get('@Url.Action("OrderItems", "Order")?acKey=' + $("#AcKey").val()
                        + ($("#OrderType").val() === "@OrderType.Buyer" ? "&subject=" + $("#ReceiverId").val()
                            + "&subjectType=" + $("#WayOfSale").val()
                            + "&saleType=P" : ""),
                        function (data) {
                            $("#OldCurrency").val($("#Currency").val());
                            invoiceItems = [];

                            for (var i = 0; i < data.length; i++) {
                                data[i].DeliveryDeadline = data[i].DeliveryDeadline ? moment(data[i].DeliveryDeadline) : null;
                                data[i].OriginalPrice = data[i].Price;
                                data[i].OriginalValue = data[i].Value;

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

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

                            if (data.length > 0) {
                                displayShowHideDropdown();
                            }
                        }, "json");
                }
            });
        }

        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 toPayDisplay() {
            if ($("#CompanyCurrency").val() !== $("#Currency").val()) {
                $("#toPayContainer").attr("hidden", true);
                $("#toPayNewCurrencyContainer").attr("hidden", false);
            } else {
                $("#toPayNewCurrencyContainer").attr("hidden", true);
                $("#toPayContainer").attr("hidden", false);
            }
        }

        function onClickNewOrder() {
            if($("#OrderType").val() === "@OrderType.Buyer")
                window.location = "@Url.Action("CreateBuyerOrder", "Order")?docType=" + $("#DocTypeSelect option:selected").val();
            else
                window.location = "@Url.Action("CreateSupplierOrder", "Order")?docType=" + $("#DocTypeSelect option:selected").val();
        }

        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 duplicateOrder() {
            $.ajax({
                url: "@Url.Action("DuplicateOrder", "Order")",
                dataType: 'json',
                data: { acKey: $("#AcKey").val() },
                method: "GET",
                success: function (data) {
                    if (data.Success && data.AcKey) {
                        canceledLink(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'
                            }
                        ]
                    });
                }
            });
        }
    </script>
}
