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

@model ReceivedBillsCreateViewModel
@{
    ViewBag.Title = Loc.Invoice;

    var pnButtonClass = "btn-default btn-outline disabled";
    var redirectAction = Url.Action("AddPayOrderFromMove", "PayOrders");
    var pnButtonName = Loc.CreatePayOrder;
    var pnTitle = Loc.CreatePayOrder;
    var shouldCreatePn = true;

    if (Model.IsPayorderExist)
    {
        shouldCreatePn = false;
        pnButtonClass = "btn-default btn-outline";
        //redirectAction = Url.Action("Index", "PayOrders", new { acKey = Model.ExistingPayOrderAcKey });
        pnButtonName = string.Format("{0} {1}", Loc.AcKey, Model.ExistingPayOrderAcKeyView);
        pnTitle = string.Format("{0} {1}", Loc.PayOrderIsAlreadyCreated, Model.ExistingPayOrderAcKey);
    }
    else if (!string.IsNullOrEmpty(Model.AcKey) && string.Equals(Model.Status, ReceivedBillStatus.Confirmed) && !Model.IsPayorderExist)
    {
        pnButtonClass = "btn-success";
    }
}

@Html.Hidden("PayOrderRedirectAction", redirectAction)
@Html.Hidden("SubjectInfo", Url.Action("SubjectInfo", "PayOrders"))
@Html.Hidden("SubjectEdit", Url.Action("Edit", "Subjects"))
@Html.Hidden("UrlMoveStatus", Url.Action("MoveStatus", "ReceivedBills"))
@Html.Hidden("UrlCheckDocType", Url.Action("CheckDocType", "ReceivedBills"))
@Html.Hidden("UrlMovePosting", Url.Action("MovePosting", "ReceivedBills"))
@Html.Hidden("ShouldCreatePn", shouldCreatePn)
@Html.Hidden("ConfirmLoc", Loc.Confirm)
@Html.Hidden("MovePostingNotConfirmed", Loc.MovePostingNotConfirmed)
@Html.Hidden("PayOrderCreateInvalidDocType", Loc.PayOrderCreateInvalidDocType)

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_RecievedBillsTabNavigation")
        <div class="tab-content">
            <form method="post" id="ReceivedBillsForm" enctype="multipart/form-data" class="custom-dirty-checker">
                @Html.Hidden("ConfirmedStatus", ReceivedBillStatus.Confirmed)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                @Html.HiddenFor(model => model.IsVATObligee)
                @Html.HiddenFor(model => model.IsTaxPeriodLocked)
                @Html.HiddenFor(model => model.TaxPeriodError)
                @Html.HiddenFor(model => model.SelectedCountry)
                @Html.HiddenFor(model => model.IsObligDept)
                @Html.HiddenFor(model => model.UserDepartment)
                @Html.HiddenFor(model => model.VatBase)
                @Html.HiddenFor(model => model.CompanyCurrency)
                @Html.HiddenFor(model => model.AdvancePaymentMsgType)
                @Html.HiddenFor(model => model.ExistingPayOrderAcKey)
                @Html.HiddenFor(model => model.FillDeptFromCostDrv)
                @Html.HiddenFor(model => model.FilterDeptForCostDrv)
                @Html.HiddenFor(model => model.FxRateCalcOperation)
                @Html.HiddenFor(model => model.GenerItemNoLen)
                @Html.HiddenFor(model => model.GenerItemNoFieldLen)
                @Html.HiddenFor(model => model.GenerItemNoConst)
                @Html.HiddenFor(model => model.GenerItemNoField)
                @Html.HiddenFor(model => model.RoundReceiving)
                @Html.HiddenFor(model => model.RoundPrice)
                @Html.HiddenFor(model => model.DocumentTabActive)
                @Html.HiddenFor(model => model.ActiveTaskDocumentAcKey)
                @Html.Hidden("DefaultReport", string.Empty)
                @Html.HiddenFor(model => model.CalcInvoInFallDue)
                @Html.HiddenFor(model => model.CurrencyFxRateType)
                @Html.HiddenFor(model => model.OurCompIsName2)
                @Html.HiddenFor(model => model.FillRefFromSubj)
                @Html.HiddenFor(model => model.FillDeptFromPersonResp)
                @Html.HiddenFor(model => model.CalcInvoInFallDue)
                @Html.HiddenFor(model => model.CurrencyFxRateType)

                <input id="ItemsJsonString" name="ItemsJsonString" hidden />
                <input id="NoteUri" name="NoteUri" hidden />

                <div class="row buttons-tabbed">
                    @if (Model.ActiveTask != null)
                    {
                        @Html.Partial("~/Views/Task/_AvailableActions.cshtml", Model.ActiveTask.AvailableActions)
                    }

                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                       ShowCloseBtn = false,
                       IsWizardDisabled = string.IsNullOrEmpty(Model.AcKey) ? true : false,
                       IsWizardVisible = true,
                       BackUrl = Url.Action("Index", "ReceivedBills"),
                       SaveButtonGroup = new FormButtonGroup
                       {
                           Buttons = new List<FormButton>
                                {
                                    new FormButton { Text = Loc.Save, Icon = "far fa-print fa-lg", OnClick = "onClickSave()", Class = "hidden" },
                                    new FormButton { Text = Loc.SaveAndNew, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndNew + "')" },
                                    new FormButton { Text = Loc.SaveAndPrint, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndPrint + "')" },
                                    new FormButton { Text = Loc.SaveAndClose, Icon = "far fa-print fa-lg", OnClick = "onClickSave('" + InvoiceSaveType.SaveAndClose + "')" }
                                }
                       },
                       PrintSettings = Model.PrintSettings,
                       PrintType = ReportFormName.ReceivedBills,
                       PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                                Model.ReportTreeViewModel,
                                "onClickSave('" + InvoiceSaveType.SaveAndPrint + "', '{0}')",
                                "onClickSave('" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                            ),
                       WizardButtonGroup = new FormButtonGroup
                       {
                           Buttons = new List<FormButton>
                                 {
                                    new FormButton { Text = Loc.AdvancePayments, Icon = "", OnClick = "moveAdvancePaymentLinks()" },
                                    new FormButton { Text = Loc.CancelInvoice, Icon = "", OnClick = "openPartialCancelInvoice()" },
                                    new FormButton { Text = Loc.ConnectDocumentWizard, Icon = "", OnClick = "startConnectDocWizardModal()" },
                                    //new FormButton { Text = Loc.MovePosting, Icon = "", OnClick = "startMovePosting()" },
                                    new FormButton { Text = Loc.CreatePayOrder, Icon = "", OnClick = "addNewPayOrder()" }
                                 }
                       }
                    })

                    <!--<span class="pull-right" title="@pnTitle">
                        <a id="addPayOrderFromMove"
                           onclick="addNewPayOrder()"
                           class="btn @pnButtonClass">
                            <i class="fa fa-money"></i>
                            <span class="visible-lg-inline m-l-xs">@pnButtonName</span>
                        </a>
                    </span>-->

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

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

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

                <div class="divided-content">
                    <div class="divided-content-main">
                        <div class="placeholder placeholder-invoice-coin"><span class="placeholder-text">@Loc.RecievedBillsPlaceholder</span></div>
                        <div class="row document-head">
                            <div class="col-md-2 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ?  string.Empty : " document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.DocType, Loc.DocType, new { @class = "control-label" })
                                    <div>
                                        @Html.HiddenFor(model => model.DocType)
                                        <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-warehouse="@item.Receiver"
                                                        data-payMethod="@item.PayMethod"
                                                        data-doc1="@item.Doc1"
                                                        data-doc2="@item.Doc2"
                                                        data-department="@item.Department"
                                                        data-isObligDept="@item.ISObligDept"
                                                        data-isInternal="@item.IsInternal"
                                                        data-isObligCostDrv="@item.IsObligCostDrv"
                                                        data-allowZeroTotal="@item.AllowZeroTotal"
                                                        data-checkPosPriceQty="@item.CheckPositionPriceQty"
                                                        data-docTypeDms="@item.DocTypeDms"
                                                        data-classification="@item.Classification"
                                                        data-checkIdentDpl="@item.CheckIdentDpl"
                                                        data-roundT="@item.RoundT"
                                                        data-roundValue="@item.RoundValue"
                                                        data-roundPrice="@item.RoundPrice"
                                                        data-roundTfc="@item.RoundTfc"
                                                        data-roundValueOc="@item.RoundValueOc"
                                                        @(Model.DocType == item.Id ? "selected" : string.Empty)>
                                                    @item.Value
                                                </option>
                                            }
                                        </select>
                                    </div>
                                </div>
                            </div>

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

                            <div class="col-md-2 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.PaymentMethod, Loc.PaymentMethod, new { @class = "control-label" })
                                    <input id="ValidPaymentMethodId" value="@Model.PaymentMethodId" hidden />
                                    @Html.DropDownListFor(model => model.PaymentMethodId,
                                    new SelectList(ViewBag.PaymentTypes != null ? ViewBag.PaymentMethods : new List<string>
                                        (), "Id", "Name"), Loc.Select,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "PaymentMethodId", false, Loc.PaymentMethod, true, new { title = Model.PaymentMethod }))
                                    @Html.ValidationMessageFor(model => model.PaymentMethodId, "", new { @class = "text-danger" })
                                </div>
                            </div>

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

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

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

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

                        <div class="row document-footer">
                            <div id="invoiceNoteContainer" class="col-md-1 col-sm-6">
                                <div class="form-group text-center text-left-xs" onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note)
                                    <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-6" id="statementsContainer">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Statement, Loc.TextMessage, new { @class = "control-label m-t-sm" })
                                    <div>
                                        @Html.HiddenFor(model => model.Statement)
                                        @Html.DropDownList("Statements", new SelectList(ViewBag.DocTexts != null ? ViewBag.DocTexts : new List<string>
                                            (), "Id", "Code"),
                                            HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Statements", false, Loc.TextMessage, true, new { @multiple = "multiple", @title = Loc.Select }))
                                        @Html.ValidationMessageFor(model => model.Statement, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-6 document-head-disabled-input" title="@Loc.Total">
                                <div class="form-group text-right">
                                    <label>@Loc.Total</label>
                                    <input type="text" id="TotalAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Price" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-6">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount %</label>
                                    <input type="text" id="DiscountPercent" step="@Model.DefaultDecimalPlacesValue" value="" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-6">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount</label>
                                    <input type="text" id="DiscountAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Discount" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 col-sm-6 document-head-disabled-input" title="@Loc.Value">
                                <div class="form-group text-right">
                                    <label>@Loc.Value</label>
                                    <input type="text" id="Value" value="" step="@Model.DefaultDecimalPlacesValue" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            @if (Model.IsVATObligee)
                            {
                                <div class="col-md-1 col-sm-6 document-head-disabled-input">
                                    <div class="form-group text-right">
                                        <label>@Loc.VAT</label>
                                        <input type="text" id="TaxAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.VAT" class="form-control text-right numberInput" disabled />
                                    </div>
                                </div>
                            }
                            <div class="col-md-1 col-sm-6 document-head-disabled-input padding-left-none" id="forPay76aContainer" hidden>
                                <div class="form-group text-right">
                                    <label title="@Loc.Article76a">@Loc.Article76a</label>
                                    <input type="text" id="ForPay76a" step="@Model.DefaultDecimalPlacesValue" value="" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="@(Model.IsVATObligee ? " col-md-3 col-sm-6" : "col-md-4 col-sm-12" ) document-head-highlight-input" id="toPayContainer">
                                <div class="form-group text-right">
                                    <label>@Loc.ToPay</label>
                                    <div>
                                        <span id="ToPayAmount" class="ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span id="ToPayCurrency" class="ToPayCurrency">@Model.Currency</span>
                                    </div>
                                </div>
                            </div>
                            <div class="@(Model.IsVATObligee ? " col-md-3 col-sm-6" : "col-md-4  col-sm-12" ) document-head-highlight-input" id="toPayNewCurrencyContainer" hidden>
                                <div class="row">
                                    <div class="col-md-5">
                                        <div class="form-group">
                                            <label>@Loc.ToPay</label>
                                        </div>
                                    </div>
                                    <div class="col-md-7 text-right padding-left-none">
                                        <span class="font-sm ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                    </div>
                                    <div class="col-md-5 line-height-18">
                                        <span class="font-sm">@Loc.In.ToUpper()</span>
                                        <span class="font-sm" id="ToPayOurCurrency">@Model.Currency</span>
                                    </div>
                                    <div class="col-md-7 text-right padding-left-none line-height-18">
                                        <span id="ToPayAmountOurCurrency" class="font-sm">@Model.CurrencyValue.ToString("n2")</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="divided-content-side">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active divided-tab-3"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</a></li>
                                <li class="divided-tab-3">
                                    <a data-toggle="tab" href="#connections" class="local-tab">
                                        @Loc.Connected <span class="badge" id="connectionsCount">
                                            @(Model.OrderConnections != null || Model.AdvancePaymentConnections != null || Model.DocMoveConnections != null || Model.LinkedDocs != null ?
                                                (Model.OrderConnections != null ? Model.OrderConnections.Count() : 0) +
                                                (Model.LinkedDocs != null ? Model.LinkedDocs.Count() : 0) +
                                                (Model.AdvancePaymentConnections != null ? Model.AdvancePaymentConnections.Count() : 0) +
                                                (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0) +
                                                (Model.DocMoveConnections != null ? Model.DocMoveConnections.Count() : 0)
                                                : (Model.CanceledLinkAcKey != null ? Model.CanceledLinkAcKey.Count() : 0) +
                                                (Model.CanceledLinkAcKeyLnk != null ? Model.CanceledLinkAcKeyLnk.Count() : 0))
                                        </span>
                                    </a>
                                </li>
                                <li class="divided-tab-3">
                                    <a data-toggle="tab" href="#documents" class="local-tab">
                                        @Loc.Documents <span class="badge" id="documentsCount">@(Model.Files == null ? 0 : Model.Files.Count)</span>
                                    </a>
                                </li>
                                <li style="display: none" class="divided-tab-4">
                                    <a data-toggle="tab" href="#movetransitems" class="local-tab">
                                        @Loc.TransItemsKnjizbe <span class="badge">@Model.TransItems.Count</span>
                                    </a>
                                </li>
                            </ul>
                        </div>
                        <div class="tab-content">
                            <div id="home" class="tab-pane fade in active">
                                <div class="form-horizontal form-md form-right m-t-lg">
                                    <div class="form-group hidden">
                                        @Html.LabelFor(model => model.SupplierAddress, Loc.Address, new { @class = "col-md-3 control-label" })
                                        <div class="col-md-9">
                                            <div class="input-detail-indicator">
                                                @Html.HiddenFor(model => model.SupplierAddress)
                                                <p class="control-label" id="SupplierAddressContainer" title="@Model.SupplierAddress">
                                                    @Model.SupplierAddress
                                                </p>
                                            </div>
                                        </div>
                                    </div>

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


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

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

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

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

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

                                    <hr class="hr-dashed" />

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

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

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

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

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.DeliveryType, Loc.DeliveryType, new { @class = "col-md-4 col-sm-12 text-left-sm control-label" })
                                        <div class="col-md-3 col-sm-6">
                                            <select id="DeliveryType" name="DeliveryType" class="form-control custom-select">
                                                <option></option>
                                                @foreach (var item in ViewBag.DeliveryTypes)
                                                {
                                                    <option value="@item.Id" @(Model.DeliveryType == item.Id ? "selected" : string.Empty)>
                                                        @item.Name
                                                    </option>
                                                }
                                            </select>
                                            @Html.ValidationMessageFor(model => model.DeliveryType, "", new { @class = "text-danger", @id = "DeliveryType-validation" })
                                        </div>
                                        <div class="col-md-5 col-sm-6 padding-left-none-sm padding-left-none-md padding-left-none-lg">
                                            @Html.TextBoxFor(model => model.DeliveryPlace,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_medium side-content-move-to-left", "DeliveryPlace", false, Loc.DeliveryPlace))
                                            @Html.ValidationMessageFor(model => model.DeliveryPlace, "", new { @class = "text-danger", @id = "DeliveryPlace-validation", @autocomplete = "off" })
                                        </div>
                                    </div>

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

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

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ClerkId, Loc.ClerkShort, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            <select id="Clerk" name="ClerkId" class="form-control custom-select">
                                                <option value="0">@Loc.Select</option>
                                                @foreach (var item in ViewBag.Users)
                                                {
                                                    <option value="@item.Id" data-dept="@item.Dept" @(Model.ClerkId.ToString() == item.Id ? "selected" : string.Empty)>
                                                        @item.Name
                                                    </option>
                                                }
                                            </select>
                                            @Html.ValidationMessageFor(model => model.ClerkId, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Referent, Loc.Referent, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            @Html.TextBoxFor(model => model.Referent,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control", "Referent", true, Loc.Referent))
                                            @Html.ValidationMessageFor(model => model.Referent, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="documents" class="row tab-pane fade in">
                                @Html.Partial("~/Views/Documents/_FileDisplayPartial.cshtml", Model.Files != null ? Model.Files : new List<PantheonRA.Contracts.DataContracts.FileData>(),
                                    new ViewDataDictionary(ViewData) { { "uploadFiles", true } })
                            </div>

                            <div id="movetransitems" class="row tab-pane fade in">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>@Loc.TransItemsTemeljnica</th>
                                            <th>@Loc.Account</th>
                                            <td><span class="pull-right font-bold">@Loc.TransItemsBreme</span></td>
                                            <td><span class="pull-right font-bold">@Loc.TransItemsDobro</span></td>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @for (var i = 0; i < Model.TransItems.Count; i++)
                                        {
                                            <tr>
                                                <td>
                                                    <a onclick="openAccountCards('@Model.TransItems[i].Temeljnica')">
                                                        @InvoiceHelper.FormatAcKey(Model.TransItems[i].Temeljnica)
                                                    </a>
                                                </td>
                                                <td>@Model.TransItems[i].Konto</td>
                                                <td><span class="pull-right">@Model.TransItems[i].Breme.ToString("n2")</span></td>
                                                <td><span class="pull-right">@Model.TransItems[i].Dobro.ToString("n2")</span></td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>

                            <div id="connections" class="row tab-pane fade in">
                                @Html.HiddenFor(x => x.CanceledInvoice)
                                @if (Model.CanceledInvoice)
                                {
                                    <div class="form-group">
                                        @if (Model.CanceledLinkAcKey.Count() > 0)
                                        {
                                            for (var x = 0; x < Model.CanceledLinkAcKey.Count(); x++)
                                            {
                                                <h4 class="form-control clickable-icon connectionContainer" id="canceledLinkAcKey" disabled>
                                                    <a class="text-danger" onclick="canceledLink('@Model.CanceledLinkAcKey[x].AcLinkKey')">
                                                        @Model.CanceledLinkAcKeyDisplay[x].AcLinkKeyDisplay
                                                    </a>
                                                    <span class="pull-right text-danger">@Model.CanceledLinkAcKeyDisplay[x].LinkValue.ToString("n2") @Model.Currency</span>
                                                </h4>
                                            }
                                        }
                                        else
                                        {
                                            for (var y = 0; y < Model.CanceledLinkAcKeyLnkDisplay.Count(); y++)
                                            {
                                                <h4 class="form-control clickable-icon connectionContainer" id="canceledLinkAcKeyLnk" disabled>
                                                    <a class="text-danger" onclick="canceledLink('@Model.CanceledLinkAcKeyLnk[y].AcKey')">
                                                        @Model.CanceledLinkAcKeyLnkDisplay[y].AcKeyDisplay
                                                    </a>
                                                    <span class="pull-right text-danger">@Model.CanceledLinkAcKeyLnkDisplay[y].Value.ToString("n2") @Model.Currency</span>
                                                </h4>
                                            }
                                        }
                                    </div>
                                }
                                @if (Model.OrderConnections != null)
                                {
                                    for (var i = 0; i < Model.OrderConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="redirectToOrderDocument('@Model.OrderConnections[i].AcLnkKey', '@Model.OrderConnections[i].OrderType')">
                                                    @Model.OrderConnections[i].AcLnkKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.OrderConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                                <input id="hasAdvancePayments" value="@(Model.AdvancePaymentConnections != null && Model.AdvancePaymentConnections.Any(conn => conn.Price < 0) ? "true" : "false")" hidden />
                                @if (Model.AdvancePaymentConnections != null)
                                {
                                    for (var i = 0; i < Model.AdvancePaymentConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="redirectToOrderDocument('@Model.AdvancePaymentConnections[i].AcKey', '@TypeOfDoc.AdvancePayment')">
                                                    @Model.AdvancePaymentConnections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.AdvancePaymentConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                                @if (Model.DocMoveConnections != null)
                                {
                                    for (var i = 0; i < Model.DocMoveConnections.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="canceledLink('@Model.DocMoveConnections[i].AcKey')">
                                                    @Model.DocMoveConnections[i].AcKeyDisplay
                                                </a>
                                                <span class="pull-right">@Model.DocMoveConnections[i].Price.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                                @if (Model.LinkedDocs != null && Model.LinkedDocs.Count > 0)
                                {
                                    @*<h4 class="panel-delimiter"></h4>*@
                                    for (var i = 0; i < Model.LinkedDocs.Count(); i++)
                                    {
                                        <div class="form-group">
                                            <h4 class="form-control clickable-icon connectionContainer" disabled>
                                                <a onclick="openLinkedDocument('@Model.LinkedDocs[i].AcKey', '@Model.LinkedDocs[i].AcDocType')">
                                                    @InvoiceHelper.FormatAcKey(Model.LinkedDocs[i].AcKey) <span class="m-l-md">@Model.LinkedDocs[i].Status</span>
                                                </a>
                                                <span class="pull-right">@Model.LinkedDocs[i].AmountMove.ToString("n2") @Model.Currency</span>
                                            </h4>
                                        </div>
                                    }
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@{Html.RenderPartial("~/Views/Wizard/Wizard.cshtml");}
@{Html.RenderPartial("~/Views/Shared/Components/_InvoiceDeleteModals.cshtml");}
@{Html.RenderPartial("~/Views/AdvancePayment/_MoveAdvancePaymentLinksModal.cshtml");}

<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="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="subjectModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable 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">
                <div class="modal-body-scrollable">
                    @{Html.RenderPartial("~/Views/Subjects/_CreateSubjectFormPartial.cshtml",
                        new SubjectCreateViewModel()
                        {
                            SubjectEditData = new SubjectEditData()
                            {
                                SelectedCountryId = Model.SelectedCountry,
                                WayOfSale = Model.DefaultSubjWayOfSale,
                                WayOfSaleSupplier = Model.DefaultSubjWayOfSaleSupplier,
                                IsBuyer = false,
                                IsSupplier = true,
                            },
                            Countries = ViewBag.Countries,
                            ForCountry = PantheonRA.BackOffice.CurrentUser.Localization.ToString()
                        });
                    }
                </div>
            </div>
            <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="productModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" 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">@Loc.CreateNewProduct</h4>
            </div>
            <div class="modal-body">
                @{Html.RenderPartial("~/Views/Products/_CreateProductFormPartial.cshtml", new SetItemCreateViewModel()
                    {
                        TaxGroups = ViewBag.Taxes,
                        MeasurementUnits = ViewBag.MeasurementUnitsSelectList,
                        PrimaryCategories = ViewBag.PrimaryClassifSelectList,
                        SecondaryCategories = ViewBag.SecondaryClassif,
                        Types = ViewBag.SetItemTypesSelectList,
                        Tariffs = ViewBag.CustTariffs,
                        ProductEditData = Model.SetItemModel,
                        IsVATObligee = Model.IsVATObligee,
                        DefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
                        DefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
                        DefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue
                    });}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="createIdent()">@Loc.Save</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 id="taxOptions" hidden>
    @foreach (var tax in ViewBag.Taxes)
    {
        <option value="@tax.VATCode" data-vat="@tax.VAT" data-displaytext="@(tax.VATCode + " " + tax.VAT + " % - " + tax.Name)">
            @tax.VATCode
        </option>
    }
</div>

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

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

@Html.Partial("~/Views/PayOrders/_IRIS.cshtml")
@Html.Partial("~/Views/Shared/Components/_CreateDocumentModals.cshtml")
@{Html.RenderPartial("~/Views/Shared/Components/_ConnectDocumentWizardModal.cshtml");}
@{Html.RenderPartial("~/Views/Shared/Components/_PartialCancelInvoice.cshtml", new PartialCancelInvoiceModalModel()
    {
        Type = InvoiceType.ReceivedBills,
        PartialCancelDefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
        PartialCancelDefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
        PartialCancelDefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue,
    });
}

<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="IdentEditUrl" value="@Url.Action("Edit", "Products")" />
<input type="hidden" id="RepeatAnimation" value="@Url.Content("~/Content/Animations/DocumentLoading.gif")" />
<input type="hidden" id="LoadingDocumentLoc" value="@Loc.LoadingDocument" />
<input type="hidden" id="PAASPrintByAcKeyAndTypeUrl" value="@Url.Action("PAASPrintByAcKeyAndType", "Move")" />
<input type="hidden" id="SearchCostDrvUrl" value="@Url.Action("SearchCostDrv", "CostDrv")" />
<input type="hidden" id="GetCostDrvUrl" value="@Url.Action("GetCostDrv", "CostDrv")" />
<input type="hidden" id="GetFxRateCalcOperationUrl" value="@Url.Action("GetFxRateCalcOperation", "Currency")" />

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

<script>
        var invoiceItems = [];
        var openStatus = "";
        var paperSize = "";
        var supplierTypeaheadData;
        var driverTypeaheadData;
        var fxRateChanged = false;

        $(document).ready(function () {
            checkPayOrderMessage();

            function payOrderButton() {
                var acKey = $("#AcKey").val();
                var status = $("#Status option:selected").val();
                var isPayorderExist = @Model.IsPayorderExist.ToString().ToLower();
                var isInternalDoc = @Model.IsInternalDoc.ToString().ToLower();
                var confirmedStatus = $("#ConfirmedStatus").val();

                if (isPayorderExist && !isInternalDoc) {
                    $("#addPayOrderFromMove").removeClass("disabled").addClass("btn-default btn-outline");
                }
                else if (acKey.length > 0 && status === confirmedStatus && !isPayorderExist) {
                    $("#addPayOrderFromMove").removeClass("btn-default btn-outline disabled").addClass("btn-success");
                } else {
                    $("#addPayOrderFromMove").addClass("btn-default btn-outline disabled").removeClass("btn-success");
                }
            }

            $("#Status").on('change', function () {
               payOrderButton();
            });

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

            getFxRateCalcOperation("TakeoverDate");
            initializeFileDisplay('@Model.PreviewImage', '@(Model.Files != null && Model.Files.Any() ? Model.Files[0].Id.ToString() : string.Empty)');
            loadInvoiceItems();
            initializeSubjectsEdit();
            initializeProductsEdit();
            checkFormEditable();
            initializeInvoiceIdentInputs($("#IdentSearch"), PriceType.ReceivedBills, DiscountType.SupplierRebate, $("#DefaultDecimalPlacesPrice").val(), $("#ReceivingWarehouse"), $("#SupplierId"), $("#Purchase"),
                { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock'});
            openStatus = $("#Status").val();
            setStatements($("#Statements"), $("#Statement").val());
            payOrderButton();

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

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

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

            $(".datepicker").datepicker({
                format: 'dd.mm.yyyy',
                language: '@Loc.Language'
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });


            initializePartnerTypeahead($('#Supplier').attr('dataUrl'), $('#Supplier'), $("#SupplierId"), function (item) {
                supplierTypeaheadData = item;

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

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

            initializePartnerTypeahead($('#Driver').attr('dataUrl'), $('#Driver'), $("#DriverId"), function (item) {
                driverTypeaheadData = item;
                $("#DriverName").val(item.value);
                $("#Driver").prop("title", $("#Driver").val());
                $("#DriverAddressContainer").text(item.completeAddress);
                $("#DriverAddressContainer").prop('title', item.completeAddress);
            });

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

            $("#Received, #IssueDate, #OrderFormDate, #TakeoverDate, #TaxDate").on('change', function () {
                var start = getStartDate($("#CalcInvoInFallDue").val());
                var newDate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + Number($("#DateDueDays").val()));
                $("#DateDue").datepicker('setDate', newDate);
                $("#Currency").trigger("customSelectChange");
            });

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

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

                if ($("#IssueDate").datepicker('getDate') != null)
                    start = new Date($("#IssueDate").datepicker('getDate'));
                else
                    start = new Date($("#Received").datepicker('getDate'));

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

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

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

                return start;
            }

            calculatePriceWithDiscount();
            calculateDiscountPercent();

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

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

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

            $("#Received").on('change', function () {
                $("#TaxDate").val($("#Received").val());
            });

            $("#BillNumber").on('change', function () {
                $("#RefNumber").val($("#BillNumber").val());
            });

            $("#DocTypeSelect").on('change', async function () {
                $("#DocType").val($("#DocTypeSelect").val());
                $("#DocTypeSelect").prop("title", $("#DocTypeSelect option:selected").text());
                setDocTypeRounding("#DocTypeSelect");

                if ($("#AcKey").val() && $("#ReceivingWarehouseSelect option:selected").val() !== $("#ReceivingWarehouse").val()) {
                    $("#ReceivingWarehouseSelect").append(new Option($("#ReceivingWarehouse").val(), $("#ReceivingWarehouse").val(), true, true));
                    $("#ReceivingWarehouseSelect").trigger("change");
                }

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

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

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

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

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

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

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

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

            $("#ReceivingWarehouseSelect").on('change', function () {
                $("#ReceivingWarehouse").val($("#ReceivingWarehouseSelect").val());
            });

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

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

            $("#NewSupplier, #NewDriver").mousedown(function () {
                addSubjectMousedown = true;
            });

            $("#PaymentMethodId").on("change", function () {
                $("#PaymentMethodId").prop("title", $("#PaymentMethodId option:selected").text());
                $.get("@Url.Action("CanDelete", "ReceivedBills")" + "?acKey=" + $("#AcKey").val(), function (response) {
                    canDeleteResponse = response;
                    if (response.HasCashExpenditureOrTransfer == true) {
                        $("#deleteWarningMessage").text(stringFormat("@Loc.AssociatedCashExpenditureOrTransfer", $("#AcKeyDisplay").val()));
                        $("#continueAndDeleteBPBIDocuments").attr("hidden", false);
                        $("#deleteWarningModal").modal("show");
                        $("#continueDeleteDocument").attr("onclick", "changePaymentMethodData()");
                        $("#continueAndDeleteBPBIDocuments").attr("onclick", "changePaymentMethodData(true)");
                        $("#cancelDeleteDocument").attr("onclick", "cancelChangePaymentType()");
                    }
                });
            });

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

                $.get('@Url.Action("GetFxRate", "Currency")', { Currency: $("#Currency").val(), Date: new Date(date).toISOString() })
                    .done(function (response) {
                        if (toNumber($("#FxRate").val()) !== response)
                            fxRateChanged = true;

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

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

                        save("@InvoiceSaveType.SaveAndChangeFxRate");
                    });
            });

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

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

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

            toPayDisplay();

            $('#IdentSearch').on("focus-custom-typeahead", function () {
                var errMsg;
                var $focusNext;

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

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

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

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

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

            $('#deleteWarningModal').on('hidden.bs.modal', function (e) {
                $("#continueAndDeleteBPBIDocuments").attr("hidden", true);
            });

            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($(e.target).attr("href") === "#documents")
                    fixIframeAttachments();
            });

            dropifyUploadAttachments();

            $("#uploadFiles").on("click", function (e) {
                if (!$("#AcKey").val()) {
                    e.preventDefault();
                    onClickSave('@InvoiceSaveType.SaveAndCreateDocument');
                }
            });

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

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

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


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

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

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

        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 changeSupplierData() {
            var item = supplierTypeaheadData;
            if ($("#ValidSupplierId").val() === item.value)
                return;

            $("#Supplier").prop("title", $("#Supplier").val());
            $("#SupplierName").val(item.value);
            $("#SupplierAddressContainer").text(item.completeAddress);
            $("#SupplierAddressContainer").prop('title', item.completeAddress);
            $("#RefCode").val(item.bankAccountRefCode);
            if ($("#FillRefFromSubj").val() === "True") {
                $("#Clerk").val(item.clerkSupp);
                $("#Clerk").trigger("change");
            }
            $("#Purchase").val(item.wayOfSaleSupplier);
            if (item.paymentMethodIdSupplier != null && item.paymentMethodIdSupplier != "") {
                $("#PaymentMethodId").val(item.paymentMethodIdSupplier);
            } else {
                $("#PaymentMethodId").val($("#DocTypeSelect option:selected").attr("data-payMethod"));
            }
            $("#DateDueDays").val(item.daysForPaymentSupplier);
            $("#DateDueDays").trigger('change');
            changeSubjectRabate(item.rabateSupplier);

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

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

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

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

        function changeDriverToSupplier(item) {
            $("#DriverId").val(item.id);
            $("#Driver").val(item.value);
            $("#DriverName").val(item.value);
            $("#Driver").prop("title", $("#Driver").val());
            $("#DriverAddressContainer").text(item.completeAddress);
            $("#DriverAddressContainer").prop('title', item.completeAddress);
            driverTypeaheadData = item;
            supplierChangedChangeIdentRebate(item);
        }

        function supplierChangedChangeIdentRebate(item) {
            if (invoiceItems.length > 0)
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "changeIdentRebateAlertModal",
                    type: "question",
                    text: "@Loc.BuyerChangedChangeIdentRebate",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.No',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Yes',
                            action: function () {
                                updateInvoiceItemsDiscount(toNumber(item.rebate));
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

            getDeliveryFillType();
            if ($("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.OnSubjectChange")
                moveAdvancePaymentLinks(true);
        }

        function calculatePriceWithDiscount() {
            $("#Value").val(toNumber($("#TotalAmount").val()) - toNumber($("#DiscountAmount").val()));
            var taxAmount = $("#Purchase").val() === "@WayOfSale.Import" || $("#Purchase").val() === "@WayOfSale.ImportEU" ||
                    $("#Purchase").val() === "@WayOfSale.Nonresident" || $("#Purchase").val() === "@WayOfSale.Flatrate" ? 0 : toNumber($("#TaxAmount").val());
            var toPayAmount = formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound((toNumber($("#Value").val()) + taxAmount).toString(), 2));
            var toPayAmountOurCurrency = calculateWithOperation((toNumber(toPayAmount) - taxAmount), toNumber($("#FxRate").val()), true);
            $(".ToPayAmount").text(toPayAmount);
            $("#ToPayAmountSub").val(toPayAmount);
            $("#ToPayAmountOurCurrency").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound((toNumber(toPayAmountOurCurrency).toString()), 2)));
            initializeNumberInputs();
        }

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

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

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

            updateInvoiceItemsDiscount(percent);
            calculatePriceWithDiscount();
        }

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

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

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

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

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

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

            item.TaxPrice = excise.vat;
            item.TotalPrice = $("#Purchase").val() === "@WayOfSale.Nonresident" ||
                $("#Purchase").val() === "@WayOfSale.Flatrate" ? excise.discountedPriceWithExcise - excise.vat : excise.discountedPriceWithExcise;

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

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

        function appendIdentToTable(data, isNewIdent = false) {
            if ((!data.Department || data.Department === "") && $("#DocTypeSelect option:selected").attr("data-isObligDept") === "True")
                data.Department = $("#Department option:selected").val();

            let newRow = createIdentsTableRows($("#invoice"), data, SaleType.NotSale, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#IsVATObligee").val(), $("#RoundReceiving").val());
            initializeNumberInputs();

            if (isNewIdent) {
                reorderColumns(true, newRow);

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

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

        function addPosition(selectedInvoiceItemData) {
            if ($("#ReceivingWarehouse").val() === "") {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "issuerIdReqErrorModal",
                    type: "alert",
                    text: "@Loc.WarehouseIsRequired",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            action: async function () {
                                $("#ReceivingWarehouseSelect").focus();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }

            var totalPrice = toNumber($("#SelectedItemQuantity").val()) * toNumber(selectedInvoiceItemData.price);
            var discount = totalPrice / 100 * toNumber($("#SelectedItemRebate").val());
            var vat = (totalPrice - discount) / 100 * selectedInvoiceItemData.vatTR;
            var price = totalPrice - discount + vat;

            var excise = calculatePriceWithExcise(selectedInvoiceItemData);

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

            if (selectedInvoiceItemData != null) {
                var invoiceItem = {
                    AcKey: "",
                    Ident: selectedInvoiceItemData.id,
                    AnNo: invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].AnNo + 1 : 1,
                    Name: selectedInvoiceItemData.name_only,
                    Quantity: selectedInvoiceItemData.quantity,
                    Price: selectedInvoiceItemData.price,
                    Rabate: selectedInvoiceItemData.rabate,
                    VAT: selectedInvoiceItemData.vatTR,
                    VATCodeTR: selectedInvoiceItemData.vatCodeTR,
                    TotalPrice: $("#Purchase").val() === "@WayOfSale.Nonresident" ||
                        $("#Purchase").val() === "@WayOfSale.Flatrate" ? excise.discountedPriceWithExcise - excise.vat : excise.discountedPriceWithExcise,
                    Note: "",
                    MeasurementUnit: selectedInvoiceItemData.measurementUnit,
                    TaxPrice: excise.vat,
                    BasisForTax: totalPrice - discount,
                    PriceForValue: 0,
                    Excise: (excise.priceWithExcise - totalPrice - vat) / selectedInvoiceItemData.quantity,
                    IncBase: selectedInvoiceItemData.incBase,
                    NotIncBase: selectedInvoiceItemData.notIncBase,
                    IncBaseP: selectedInvoiceItemData.incBaseP,
                    NotIncBaseP: selectedInvoiceItemData.notIncBaseP,
                    PricesForSelect: selectedInvoiceItemData.pricesForSelect,
                    CostDrv: selectedInvoiceItemData.costDrv ? selectedInvoiceItemData.costDrv : invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].CostDrv : "",
                    Department: dept,
                    SalePrice: selectedInvoiceItemData.retailPrice
                }

                invoiceItems.push(invoiceItem);
                appendIdentToTable(invoiceItem, true);
                updatePriceTable();
                $("#DocTypeSelect").attr("disabled", true);
                $("#ReceivingWarehouseSelect").attr("disabled", true);

                if ($("#DocTypeSelect option:selected").attr("data-checkPosPriceQty") === "@true" && (invoiceItem.Quantity === 0 || invoiceItem.Price === 0)) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "checkPosPriceQtyModal",
                        type: "alert",
                        text: stringFormat("@Loc.InoicePositionQuantityOrPrice0Warning", invoiceItem.AnNo),
                        onClose: function () { onClickSave() },
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else
                    onClickSave();
            }
        }

        function swapLoadingIcon(loading, buttonId) {
            var buttonIcon;
            if (buttonId == "saveButton") {
                buttonIcon = "fa fa-save";
            }
            else {
                buttonIcon = "fa fa-plus";
            }

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

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

        function deleteInvoiceItem(anNo) {
            invoiceItems.splice(getInvoiceItemIndex(anNo), 1);
            $("#position-" + anNo).remove();
            updatePriceTable();

            if (invoiceItems.length < 1) {
                $("#ReceivingWarehouseSelect").attr("disabled", false);
                $("#sh-dropdown-menu").remove();

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

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

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

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

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

            changeIdentData(selectedItemAnNo);
        }

        function changeIdentTotalPrice(anNo) {
            var price = toNumber($("#totalPrice-" + anNo).val());
            var invoiceIndex = getInvoiceItemIndex(anNo);

            if (price === invoiceItems[invoiceIndex].TotalPrice)
                return;

            if ($("#Purchase").val() !== "@WayOfSale.Import"
                    && $("#Purchase").val() !== "@WayOfSale.ImportEU"
                    && $("#Purchase").val() !== "@WayOfSale.Nonresident") {

                price = toNumber($("#totalPrice-" + anNo).val()) / (1 + (toNumber($("#vatPercent-" + anNo).val()) / 100));
            }

            if (toNumber($("#quantity-" + anNo).val()) > 1)
                price = price / toNumber($("#quantity-" + anNo).val());

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

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

            for (var i = 0; i < invoiceItems.length; i++) {
                totalPrice = totalPrice + (invoiceItems[i].Price * invoiceItems[i].Quantity);
                var discount = ((invoiceItems[i].Price * invoiceItems[i].Rabate) / 100) * invoiceItems[i].Quantity;
                discountSum = discountSum + discount;
                excise += invoiceItems[i].Excise;
                taxAmount += invoiceItems[i].TaxPrice;
            }

            var toPayAmount = formatDisplay($("#DefaultDecimalPlacesValue").val(),
                evenRound(totalPrice - discountSum + ($("#Purchase").val() === "@WayOfSale.Import" || $("#Purchase").val() === "@WayOfSale.ImportEU" ||
                    $("#Purchase").val() === "@WayOfSale.Nonresident" || $("#Purchase").val() === "@WayOfSale.Flatrate" ? 0 : taxAmount) + excise, 2));
            var toPayAmountForPay76a = formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(totalPrice - discountSum + excise, 2));
            var toPayAmountOurCurrency = formatDisplay($("#DefaultDecimalPlacesValue").val(), evenRound(calculateWithOperation((totalPrice - discountSum), toNumber($("#FxRate").val()), true), 2));
            var discountPercent = 0;

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

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

            initializeNumberInputs();
            calculatePriceWithDiscount();
        }

        onClickSave = function (option, printType = null) {
            let isFormClean = $("#ReceivedBillsForm").customDirtyChecker("check");
            if (isFormClean) {
                save(option, printType);
                return;
            }

            if (openStatus === '@WholesaleStatus.Confirmed') {
                if ($("#ExistingPayOrderAcKey").val()) {
                    $("#deleteWarningMessage").text(stringFormat("@Loc.AssociatedCashExpenditureOrTransfer", $("#AcKeyDisplay").val()));
                    $("#continueAndDeleteBPBIDocuments").attr("hidden", false);
                    $("#deleteWarningModal").modal("show");
                    $("#continueDeleteDocument").attr("onclick", "save('" + option + "', '" + printType + "')");
                    $("#continueAndDeleteBPBIDocuments").attr("onclick", "save('" + option + "', '" + printType + "', '" + true + "')");
                    $("#cancelDeleteDocument").attr("onclick", "");
                } else {
                    $().customModal({
                        title: "",
                        destroyOnClose: true,
                        showCloseButton: true,
                        id: "confirmedDocumentAlertModal",
                        type: "question",
                        text: "@Loc.DocumentIsAlreadyConfirmed",
                        buttons: [
                            {
                                icon: 'fa fa-times',
                                text: '@Loc.No',
                                closeOnAction: true,
                                type: 'ghost'
                            },
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.Yes',
                                action: async function () {
                                    $("#ReceivedBillsForm").customDirtyChecker();
                                    save(option, printType);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            }
            else
                save(option, printType);
        }

        var printWindow;
        function save(option, printType, deleteBPBI = false) {
            if ($("#IsTaxPeriodLocked").val() === "@true.ToString()" && (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview')) {
                handleSaveOption(option, printType, deleteBPBI);
                return;
            }

            swapLoadingIcon(true, "saveButton");
            $("#Statement").val($("#Statements").val() ? $("#Statements").val().toString() : "");

            var formData = $("#ReceivedBillsForm").serializeArray();
            formData = changeFormDataValue(formData, 'ItemsJsonString', JSON.stringify(invoiceItems));
            formData = changeFormDataValue(formData, 'Note', encodeURIComponent($("#Note").val()));

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

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

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

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

                        if (option === '@InvoiceSaveType.SaveAndPrint' && $("#AdvancePaymentMsgType").val() === "@AdvancePaymentMsgType.WhenPrinting" && $("#hasAdvancePayments").val() === "false")
                            moveAdvancePaymentLinks(true, option, printType);
                        else
                            handleSaveOption(option, printType, deleteBPBI);
                    }
                    else {
                        $('[href="#home"]').tab('show');
                        if (response.data && response.data.AcKey && !$("#AcKey").val()) {
                            setInvoiceCreatedData(response);
                        }

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

                        clearValidationErrors();
                        displayErrors(response);

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

                    swapLoadingIcon(false, "saveButton");
                });
        }

        function handleSaveOption(option, printType, deleteBPBI) {
            if (deleteBPBI)
                tryDeleteBPBI();

            if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
                printPAAS((printType ? printType : $("#DefaultReport").val()), false, option === '@InvoiceSaveType.SaveAndPreview');
            } else if (option === '@InvoiceSaveType.SaveAndNew') {
                window.location.href = '@Url.Action("Create", "ReceivedBills")';
            } else if (option === '@InvoiceSaveType.SaveAndClose') {
                window.location.href = '@Url.Action("Index", "ReceivedBills")';
            } else if (option === '@InvoiceSaveType.SaveAndChangeFxRate') {
                showRecalculatePositionsModal();
            } else if (option === '@InvoiceSaveType.SaveAndCreateDocument') {
                $("#uploadFiles").click();
            } else {
                setIdentsPriceForValue();
            }
        }

        function setInvoiceCreatedData(response) {
            $("#AcKey").val(response.data.AcKey);
            $("#AcKeyDisplay").val(response.data.AcKeyDisplay);
            refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
            $("#PaymentReference").val(response.data.Reference);
            $("#OrderForm").val(response.data.OrderForm);
            $("#invoiceDelete").removeClass("hidden");
            $("#cancelInvoice").removeClass("hidden");
            $("#printButton").removeClass("hidden");
            $("#printButton").attr("disabled", false);
            $("#printButton + button").prop("disabled", false);
            $("#newInvoice").removeClass("hidden");
            $("#invoiceDuplicate").removeClass("hidden");
            $("#Referent").val(response.data.Referent);
            $("#DocTypeSelect").attr("disabled", true);
            $("#DocTypeSelect").closest(".form-group").parent().addClass("document-head-disabled-input");
            $("#additionalFuncButton").removeClass("hidden");
            $("#additionalFuncButton + button").removeClass("hidden");
            $("#wizardButton").attr("disabled", false);
            $("#wizardButton + button").attr("disabled", false);
            window.history.pushState({}, null, '@Url.Action("Edit", "ReceivedBills")?id=' + response.data.AcKey);

            //$('#addPayOrderFromMove').attr("href", "/PayOrders/AddPayOrderFromMove?id=" + response.data.AcKey);
            $("#Status").trigger('change');

            clearValidationErrors();
        }

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

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

                //TODO: Scroll to the bottom of the datatable. Currently has huge performance issues
                //$("#invoice")[0].scrollIntoView(false);
                if (data.length > 0) {
                    $("#ReceivingWarehouseSelect").attr("disabled", true);
                    displayShowHideDropdown();
                }

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

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

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

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

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

        $('#productModal').on('shown.bs.modal', function () {
            $("#ProductEditData_Id").focus();
            $("#ProductEditData_TaxRateNumber").val($("#ProductEditData_SelectedTaxGroupId").find("option:selected").attr("data-vat"));
            $("#ProductEditData_TaxRateNumberReceive").val($("#ProductEditData_SelectedTaxGroupIdReceive").find("option:selected").attr("data-vat"));
        });

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

            var url = '@Url.Action("CreateFromPartial", "Subjects")';
            if ($("#IsEdit").val() === "True")
                url = '@Url.Action("EditFromPartial", "Subjects")';

            $.post(url, formData)
                .done(function (response) {
                    if (response.Success) {
                        $("#Purchase").val(response.subject.WayOfSaleSupplier);

                        if ($("#IsEdit").val() !== "True") {
                            createSubjectSetValues("Supplier", response.subject.Id);
                            createSubjectSetValues("Driver", response.subject.Id);

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

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

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

        // Attachments collapsible script
        var coll = document.getElementsByClassName("collapsible");
        var i;

        for (i = 0; i < coll.length; i++) {
            coll[i].addEventListener("click", function () {
                this.classList.toggle("active");
                var content = this.nextElementSibling;
                if (content.style.display === "block") {
                    content.style.display = "none";
                } else {
                    content.style.display = "block";
                }
            });
        }

        function deleteReceivedBill() {
            if ($(".attachments-grid-file").length > 0) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: "@Loc.DocumentTransferredToDocumentationDeleteNotPossible",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }

            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "removeReceivedBillAlertModal",
                type: "question",
                text: "@Loc.DeleteInvoiceDocument",
                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 setIdentsPriceForValue() {
            if (!$("#AcKey").val())
                return;

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

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

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

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

                disableCreateNewButtons();
            }

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

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

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

        function payOrderButton() {
           var acKey = $("#AcKey").val();
           var status = $("#Status option:selected").val();
           var isPayorderExist = @Model.IsPayorderExist.ToString().ToLower();

           if (acKey.length > 0 && status === 'P' && !isPayorderExist) {
               $("#addPayOrderFromMove").removeClass("btn-default btn-outline disabled").addClass("btn-success");
           } else {
               $("#addPayOrderFromMove").addClass("btn-default btn-outline disabled").removeClass("btn-success");
           }
        }

        function createNewIdentModal() {
            $("#productModal").modal('show');
        }

        function createIdent() {
            var formData = $("#productForm").serializeArray();
            formData = changeFormDataValue(formData, 'ProductEditData.SuppliersPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_SuppliersPrice").val(), true));
            formData = changeFormDataValue(formData, 'ProductEditData.SellingPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_SellingPrice").val(), true));
            formData = changeFormDataValue(formData, 'ProductEditData.RetailPrice', formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#ProductEditData_RetailPrice").val(), true));

            $.post('@Url.Action("CreateFromPartial", "Products")', formData)
                .done(function (response) {
                    if (response.Success) {
                        $("#IdentSearch").val(response.product.Ident);
                        $("#IdentSearch").trigger("change");
                        $("#SelectedItemQuantity").val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), 1));
                        $("#SelectedItemPrice").val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), response.product.SuppliersPrice));
                        $("#SelectedItemRebate").val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), response.product.Rebate));

                        selectedInvoiceItemData.data = {
                            id: response.product.Ident,
                            name_only: response.product.Name,
                            price: response.product.SuppliersPrice,
                            sellingPrice: response.product.SellingPrice,
                            retailPrice: response.product.RetailPrice,
                            quantity: 1,
                            discount: response.product.Discount,
                            rabate: response.product.Rebate,
                            vat: response.product.VAT,
                            vatCode: response.product.VATCode,
                            vatTR: response.product.VATReceive,
                            vatCodeTR: response.product.VATCodeTR,
                            measurementUnit: response.product.Unit,
                            taxPrice: 0,
                            basisForTax: response.product.SuppliersPrice - (response.product.SuppliersPrice / 100 * 10),
                            priceForValue: 0,
                            stock: response.product.Stock,
                            wsPrice: response.product.WSPrice,
                            department: response.product.Department,
                            costDrv: response.product.CostDrv ? response.product.CostDrv : invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].CostDrv : "",
                            salePrice: response.product.RetailPrice,
                            serialNo: response.product.SerialNo,
                            priceType: PriceType.ReceivedBills
                        };

                        clearValidationErrors();
                        $('#productModal form')[0].reset();
                        $("#productModal").modal('hide');
                    }
                    else {
                        clearValidationErrors();

                        if (response.errors) {
                            response.errors.forEach(function (error) {
                                error.Key = error.Key.replace(".", "_");
                            });

                            displayResponseValidationErrors(response);
                        }
                    }
                });
        }

        function openInvoiceNoteModal() {
            if ($("#invoiceNoteContainer").hasClass("document-head-disabled-input"))
                return;

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

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

            $("#noteIcon")
                .removeClass("btn-active")
                .addClass($("#Note").val() !== "" ? "btn-active" : "");
        }

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

        function openLinkedDocument(ackey, docType) {
            if (docType == '8000') {
                location.href = '@Url.Action("Index", "CashTransactions")?type=P&acKey=' + ackey;
            }
            else if (docType == '8100') {
                location.href = '@Url.Action("Index", "CashTransactions")?type=CR&acKey=' + ackey;
            }
            else if (docType == '1600') {
                location.href = '@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")?id=' + ackey;
            }
            else {
                location.href = '@Url.Action("Index", "PayOrders")?acKey=' + ackey;
            }
        }

        function openAccountCards(ackey) {
            location.href = '@Url.Action("Index", "AccountCard")?acKey=' + ackey;
        }

        var canDeleteResponse;
        function canDelete() {
            $.get("@Url.Action("CanDelete", "ReceivedBills")" + "?acKey=" + $("#AcKey").val(), function (response) {
                canDeleteResponse = response;
                if (response.ShowError == true) {
                    if (response.HasConnectedCredit == true) {
                        showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
                    } else if (response.HasCashExpenditureOrTransfer == true) {
                        $("#deleteWarningMessage").text(stringFormat("@Loc.AssociatedCashExpenditureOrTransfer", $("#AcKeyDisplay").val()));
                        $("#continueAndDeleteBPBIDocuments").attr("hidden", false);
                        $("#deleteWarningModal").modal("show");
                        $("#continueDeleteDocument").attr("onclick", "continueDelete()");
                        $("#continueAndDeleteBPBIDocuments").attr("onclick", "continueDelete(true)");
                        $("#cancelDeleteDocument").attr("onclick", "");
                    } else if (response.IsLastDoc == false) {
                        showDeleteNotLastDocModal();
                    } else if (response.HasConnectedSummaryDocument == true) {
                        $("#deleteInternalDocWarningMessage").text(stringFormat("@Loc.InternalDocumentHasSummaryDocument", response.AcKey));
                        $("#deleteInternalDocWarningModal").modal('show');
                        $("#continueDeleteInternalDoc").attr("onclick", "deleteWithInternalDoc()");
                        $("#cancelDeleteInternalDocument").attr("onclick", "");
                    }
                } else
                    removeReceivedBill();
            });
        }

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

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

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

                    removeReceivedBill();
                }
            } else {
                showDeleteNotPossibleModal(stringFormat("@Loc.DocumentIsConnectedToCredit", response.AcKey));
            }
        }

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

        function deleteWithInternalDoc() {
            removeReceivedBill();
        }

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

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

        function changePaymentMethodData(deleteBPBI = false) {
            $("#ValidPaymentMethodId").val($("#PaymentMethodId").val());

            if (deleteBPBI)
                tryDeleteBPBI();
        }

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

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

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

                if (response && deliveryType) {
                    if (deliveryType === "@DeliveryFillType.FirstPerson") {
                        if (supplierTypeaheadData && supplierTypeaheadData.suppDelivery)
                            $("#DeliveryType").val(supplierTypeaheadData.suppDelivery);
                        else
                            getSubjectDeliveryType($("#SupplierId").val());
                    } else if (deliveryType === "@DeliveryFillType.ThirdPerson") {
                        if (driverTypeaheadData && driverTypeaheadData.suppDelivery)
                            $("#DeliveryType").val(driverTypeaheadData.suppDelivery);
                        else
                            getSubjectDeliveryType($("#DriverId").val());
                    }
                }
            });
        }

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

        function checkIfTaxReverseItemsExist() {
            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("CheckForReceivedBillTaxReverseItems", "ReceivedBills")', {
                AcKey: $("#AcKey").val(),
                WayOfSale: $("#Purchase").val(),
            }).done(function (response) {
                if (response && (response.Error == "" || !response.Error)) {
                    $("#ForPay76a").val(response.ForPay76aOnly);
                    formatNumberInput($("#ForPay76a"));
                    showForPay76a(true);
                } else {
                    showForPay76a(false);
                }
                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }).fail(function () {
                showForPay76a(false);
                swapLoadingIcon(false, "add-position", "fa fa-plus");
            });
        }

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

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

                    $('#advancePaymentCreatedContinueOpenOrPrint').removeAttr('onclick');
                    if (option)
                        $('#advancePaymentCreatedContinueOpenOrPrint, #advancePaymentContinueOpenOrPrint').on('click', function () {
                            printWindow = createPrintWindow(printWindow);
                            handleSaveOption(option, printType, fiscalize);
                        });

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

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

        function moveAdvancePaymentLinksHelp() {
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(PantheonRA.BackOffice.Enums.HelpIds.ExampleReceivedBillsAdvancePayment)', '_blank');
        }

        function openAdvancePaymentForSubjectHelp() {
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(PantheonRA.BackOffice.Enums.HelpIds.MoveAdvancePaymentLinksExistOnSupplier)', '_blank');
        }

        function showRecalculatePositionsModal() {
            if (invoiceItems.length > 0 && fxRateChanged === true) {
                fxRateChanged = false;

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

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

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

            var model = {
                AcKey: $("#AcKey").val(),
                FxRate: toNumber($("#FxRate").val()),
                WayOfSale: $("#Purchase").val(),
            };

            $.ajax({
                type: "POST",
                data: JSON.stringify(model),
                url: '@Url.Action("RecalculatePositionsWithFxRate", "Currency")',
                contentType: "application/json"
            }).done(function (response) {
                if (response) {
                    swapLoadingIcon(true, "add-position");
                    invoiceItems = [];

                    $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                        for (var i = 0; i < data.length; i++) {
                            data[i].TotalPrice = data[i].TotalPriceForReceivedItem;
                            data[i].TaxPrice = data[i].TaxPrice + data[i].Excise;
                            invoiceItems.push(data[i]);

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

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

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

        function startMovePosting() {
            let acKey = $("#AcKey").val();

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

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

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

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

        function addNewPayOrder() {
            let acKey = $("#AcKey").val();

            $.ajax({
                url: $("#SubjectInfo").val(),
                dataType: 'json',
                data: { subjectId: $("#SupplierId").val() },
                method: "GET",
                success: function (data) {
                    if (data.SubjAcct) {
                        tryCreateNewPayOrder(acKey);
                    }
                    else {
                        let subjectId = $("#SupplierId").val();

                        $("#poIrisSubj1").text(subjectId);
                        $("#poIrisSubj2").text(subjectId);

                        $('#pay-orders-iris').modal('show');
                    }
                },
                fail: function (error) {
                    swal(error);
                }
            });
    }

        function tryCreateNewPayOrder(acKey) {
            $.ajax({
                url: $("#UrlCheckDocType").val(),
                dataType: 'json',
                data: { acKey: acKey },
                method: "GET",
                success: function (data) {
                    if (data.Status) {
                        $.ajax({
                            url: $("#UrlMoveStatus").val(),
                            dataType: 'json',
                            data: { acKey: acKey },
                            method: "GET",
                            success: function (data) {
                                if (data.Status) {
                                    urlRedirect = $("#PayOrderRedirectAction").val() + '?id=' + acKey;
                                    window.open(urlRedirect, "_self");
                                }
                                else {
                                    $().customModal({
                                        destroyOnClose: true,
                                        showCloseButton: true,
                                        type: "error",
                                        text: $("#MovePostingNotConfirmed").val(),
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: $("#ConfirmLoc").val(),
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });
                                }
                            },
                            fail: function (error) {
                                swal(error);
                            }
                        });
                    }
                    else {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: $("#PayOrderCreateInvalidDocType").val(),
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#ConfirmLoc").val(),
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }
                },
                fail: function (error) {
                    swal(error);
                }
            });
        }


        function checkPayOrderMessage() {
            let hasPayOrderKey = '@ViewBag.HasPayOrderError';

            if (hasPayOrderKey.toLowerCase() == 'true') {
                $().customModal({
                    destroyOnClose: true,
                    title: '@Loc.Information',
                    showCloseButton: true,
                    id: "modalPayorderCreateFromMoveInfo",
                    type: "alert",
                    text: '@Loc.PayOrderCreateError0',
                    buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        closeOnAction: true,
                        type: 'primary'
                    }]
                });
            }
        }

    function RunTaskAction(action) {
        console.log("here", action, $("#ActiveTaskDocumentAcKey").val());
        let taskModel = {
            Action: action,
            Id: @(Model.ActiveTask != null ? Model.ActiveTask.Id : 0),
            SubjectId: @(Model.ActiveTask != null && Model.ActiveTask.SubjectId.HasValue ? (object)Model.ActiveTask.SubjectId : (object)"null"),
        };

        $.ajax({
            url: "@Url.Action("RunTaskAction", "Task")",
            contentType: "application/json",
            data: JSON.stringify(taskModel),
            method: "POST",
            success: function (data) {
                console.log("here2", data);
                if (data) {
                    window.location = "@Url.Action("Edit", "Documents")" + "?id=" + $("#ActiveTaskDocumentAcKey").val();
                }
                else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: '@Loc.GeneralError',
                        buttons: [
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Confirm',
                            closeOnAction: true,
                            type: 'primary'
                        }]
                    });
                }
            },
            fail: function (error) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: '@Loc.GeneralError',
                    buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        closeOnAction: true,
                        type: 'primary'
                    }]
                });
            }
        });
    }

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