@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@model PriceChangeCreateViewModel
@{
    ViewBag.Title = Loc.PriceChange;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_PriceChangeTabNavigation")
        <div class="tab-content">
            <form method="post" id="PriceChangeForm" class="custom-dirty-checker">
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        ShowCloseBtn = false,
                        BackUrl = Url.Action("Index", "PriceChange"),
                        SaveButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Save, Icon = "far fa-print fa-lg", OnClick = "onSaveClick()"},
                            }
                        },
                        PrintType = ReportFormName.PriceChange,
                        PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                            Model.ReportTreeViewModel,
                            "onSaveClick('" + InvoiceSaveType.SaveAndPrint + "', '{0}')",
                            "onSaveClick('" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                        )
                    })

                    <button id="confirmButton" onclick="confirm()" type="button"
                            class="btn btn-success pull-right" @(string.IsNullOrEmpty(Model.AcKey) ? "disabled" : string.Empty)>
                        <i class="fa fa-check"></i>
                        <span class="visible-lg-inline visible-md-inline m-l-xs">@Loc.Confirm</span>
                    </button>

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

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

                <div class="divided-content">
                    <div class="divided-content-main">
                        <div class="placeholder placeholder-price-tag"><span class="placeholder-text">@Loc.PriceChangePlaceholder</span></div>
                        <div class="row document-head">
                            <div class="col-md-3 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ?  string.Empty : "document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.DocType, Loc.DocType, new { @class = "control-label" })
                                    @Html.HiddenFor(model => model.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.DocType"
                                                    data-warehouse="@item.WarehouseReceivedBills"
                                                    data-doc1="@item.Doc1Name"
                                                    data-doc2="@item.Doc2Name"
                                                    @(Model.DocType == item.DocType ? "selected" : string.Empty)>
                                                @item.DocTypeView - @item.Name
                                            </option>
                                        }
                                    </select>
                                </div>
                            </div>

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

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

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

                            <div class="col-md-2 col-sm-12 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Loc.PriceChangeNumber, new { @class = "control-label m-t-xs" })
                                    @Html.HiddenFor(model => model.AcKey)
                                    <h4 class="control-label" id="AcKeyDisplayContainer">
                                        @{
                                            Html.RenderPartial("~/Views/Shared/Components/_PrevNextKeyDisplay.cshtml",
                                            new PrevNextKeyDisplayViewModel
                                            {
                                                KeyDisplayHint = Loc.OpenListOfPriceChange,
                                                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", "PriceChange", 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", "PriceChange", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action("Index", "PriceChange", new { acKey = Model.AcKey, date = Model.Date.Value.ToString("o") })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>

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

                            <div class="table-responsive document-table m-b-md">
                                <div class="dt-bootstrap" style="position:relative">
                                    <table id="idents" data-grid-id="idents-price-change" class="table table-bordered showhidecolumns" data-dynamic-table="true" role="grid">
                                        <thead>
                                            <tr role="row">
                                                <th style="width:4%" data-column-id="PositionShort">@Loc.PositionShort</th>
                                                <th style="width:16%" data-column-id="Ident">@Loc.Ident</th>
                                                <th style="width:16%" data-column-id="Name">@Loc.Name</th>
                                                <th style="width:8%" class="text-right" data-column-id="Stock">@Loc.Stock</th>
                                                <th style="width:8%" data-column-id="MeasUnit">@Loc.MeasUnit</th>
                                                <th style="width:5%" data-column-id="PriceType"></th>
                                                <th style="width:8%" class="text-right" data-column-id="OldPrice">@Loc.OldPrice</th>
                                                <th style="width:8%" class="text-right" data-column-id="NewPrice">@Loc.NewPrice</th>
                                                <th style="width:8%" class="text-right" data-column-id="Difference">@Loc.Difference</th>
                                                <th style="width:8%" class="text-right" data-column-id="Percent">%</th>
                                                <th style="width:8%" class="text-right" data-column-id="MarginPC">@Loc.MarginPC</th>
                                                <th style="min-width:71px;width:71px" data-column-id="CommentDelete"></th>
                                            </tr>
                                        </thead>
                                        <tbody id="identRows"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="row document-footer">
                            <div class="col-md-8 col-sm-4">
                                <div class="form-group text-left" onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note)
                                    <i id="noteIcon" class="fa fa-comment clickable-icon m-l-md @(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-2 col-sm-4 document-head-disabled-input" title="@Loc.TotalSalePrice">
                                <div class="form-group text-right">
                                    <label>@Loc.TotalSalePrice</label>
                                    <input type="text" id="TotalPC" step="@Model.DefaultDecimalPlacesValue" value="@Model.PriceWithVAT" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-2 col-sm-4 document-head-disabled-input" title="@Loc.TotalRetailprice">
                                <div class="form-group text-right">
                                    <label>@Loc.TotalRetailprice</label>
                                    <input type="text" id="TotalMPC" step="@Model.DefaultDecimalPlacesValue" value="@Model.Price" class="form-control text-right numberInput" disabled />
                                </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-1"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</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">
                                        @Html.LabelFor(model => model.Date, Loc.DateChange, new {
                                            @class = "col-md-4 control-label",
                                            @title = Loc.DateChange
                                        })
                                        <div class="col-md-8">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.Date, Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateFormat) : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Date", false, Loc.DateChange))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

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

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

                                    <hr class="hr-dashed" />

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

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

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

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

    <div class="modal inmodal fade" id="warehousesModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="project-list">
                        <table id="warehousesGrid" data-grid-id="create-price-change" data-url="@Url.Action("DocTypePrChList", "DocTypePrCh")" class="list-table">
                            <thead>
                                <tr>
                                    <th width="5%" class="dt-head-center"></th>
                                    <th width="80%">@Loc.Warehouse</th>
                                    <th width="15%">@Loc.DocTypeShort</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="confirmWarehousesSelection()">@Loc.Confirm</button>
                </div>
            </div>
        </div>
    </div>

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

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

<input type="hidden" id="IdentEditUrl" value="@Url.Action("Edit", "Products")" />
<input type="hidden" id="PAASPrintByAcKeyAndTypeUrl" value="@Url.Action("PAASPrintByAcKeyAndType", "Move")" />

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

<script>
        var invoiceItems = [];
        var selectedWarehouses = [];
        var openStatus = "";
        var selectedInvoiceItem;
        var warehousesWithoutDocTypeExist = false;

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

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

            @*initializeIdentTypeahead($('#IdentSearch').attr('dataUrl'), $('#IdentSearch'), undefined, function (item) {
                $("#IdentSearch").val(item.id);
                $("#SelectedItemQuantity").val(item.stock);
                formatNumberInput($("#SelectedItemQuantity"));
                $("#SelectedItemPrice").val(getPriceByType(item, null));
                formatNumberInput($("#SelectedItemPrice"));
                $("#SelectedItemRebate").val(item.rabate);
                formatNumberInput($("#SelectedItemRebate"));
                selectedInvoiceItemData.data = item;
                return { selected: true, value: item.id };
            }, null, $("#DefaultDecimalPlacesPrice").val(), $("#ReceiverId"), null, null, { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock' });*@

            initializeInvoiceIdentInputs($('#IdentSearch'), null, DiscountType.SellerDiscount, $("#DefaultDecimalPlacesPrice").val(), $("#ReceiverId"), null, null,
                { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock' }, null, null);

            $("#ReceiverId, #Department").on('change', function () {
                $(this).prop("title", $(this).val());
            });

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

                if (!$("#AcKey").val() && $("#DocTypeSelect option:selected").attr("data-warehouse")) {
                    $("#ReceiverId").val($("#DocTypeSelect option:selected").attr("data-warehouse"));
                    $("#ReceiverId").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())
                    await setDocTypeStatusOptions($("#DocTypeSelect option:selected").val(), $("#Status"));
            });

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

            $dataTableWarehouses = $('#warehousesGrid');
            $dataTableWarehouses.DataTable({
                ajax: {
                    url: $dataTableWarehouses.attr('data-url'),
                },
                columns: [
                    { data: "AnQid", orderable: false, render: $.fn.dataTable.render.checkbox("warehousesSelectionChanged"), className: 'dt-body-center' },
                    { data: "Warehouse", name: "AcWarehouse" },
                    { data: "DocType", name: "AcDocType" },
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.DocType === "") {
                        warehousesWithoutDocTypeExist = true;
                    }
                }
            });

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

            $('#ReceiverId').focus();
        });

        function onChangeNewPrice(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                $("#rabateRetail-" + anNo).val(toNumber($("#newRetailPrice-" + anNo).val()) - toNumber($("#retailPrice-" + anNo).val()));
            } else {
                $("#rabateSale-" + anNo).val(toNumber($("#newSalePrice-" + anNo).val()) - toNumber($("#salePrice-" + anNo).val()));
            }

            calculateIdentPercent(anNo, type);
            calculateIdentMargin(anNo, type);
            recalculateIdent(anNo, type);
        }

        function onChangeRabate(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                $("#newRetailPrice-" + anNo).val(toNumber($("#retailPrice-" + anNo).val()) + toNumber($("#rabateRetail-" + anNo).val()));
            } else {
                $("#newSalePrice-" + anNo).val(toNumber($("#salePrice-" + anNo).val()) + toNumber($("#rabateSale-" + anNo).val()));
            }

            calculateIdentPercent(anNo, type);
            calculateIdentMargin(anNo, type);
            recalculateIdent(anNo, type);
        }

        function onChangePercent(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                $("#rabateRetail-" + anNo).val(toNumber($("#percentRetail-" + anNo).val()) / 100 * toNumber($("#retailPrice-" + anNo).val()));
            } else {
                $("#rabateSale-" + anNo).val(toNumber($("#percentSale-" + anNo).val()) / 100 * toNumber($("#salePrice-" + anNo).val()));
            }

            onChangeRabate(anNo, type);
        }

        function changeIdentMargin(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                var retailPrice = (((toNumber($("#priceCurrency-" + anNo).val()) * (1 + (toNumber($("#marginRetail-" + anNo).val()) / 100)) + toNumber($("#exciseInc-" + anNo).val())) *
                    (1 + (toNumber($("#vat-" + anNo).val()) / 100))) + toNumber($("#exciseNotInc-" + anNo).val()));

                $("#newRetailPrice-" + anNo).val(retailPrice);
            } else {

                var salePrice = (1 + (toNumber($("#marginSale-" + anNo).val()) / 100)) * toNumber($("#priceCurrency-" + anNo).val());

                $("#newSalePrice-" + anNo).val(salePrice);
            }

            calculateIdentRabate(anNo, type);
            calculateIdentPercent(anNo, type);
            recalculateIdent(anNo, type);
        }

        function calculateIdentPercent(anNo, type) {
            if (type === '@PriceChangeType.Retail')
                $("#percentRetail-" + anNo).val(toNumber($("#rabateRetail-" + anNo).val()) / ((toNumber($("#retailPrice-" + anNo).val()) === 0 ? 1 : toNumber($("#retailPrice-" + anNo).val())) / 100));
            else if(type === '@PriceChangeType.Sale')
                $("#percentSale-" + anNo).val(toNumber($("#rabateSale-" + anNo).val()) / ((toNumber($("#salePrice-" + anNo).val()) === 0 ? 1 : toNumber($("#salePrice-" + anNo).val())) / 100));
        }

        function calculateIdentMargin(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                var marginRetail = toNumber($("#priceCurrency-" + anNo).val()) === 0 ? 0 : ((((((toNumber($("#newRetailPrice-" + anNo).val()) - toNumber($("#exciseNotInc-" + anNo).val())) / ((100 +
                    toNumber($("#vat-" + anNo).val())) / 100)) - toNumber($("#exciseInc-" + anNo).val())) - toNumber($("#priceCurrency-" + anNo).val())) / toNumber($("#priceCurrency-" + anNo).val())) * 100);

                $("#marginRetail-" + anNo).val(marginRetail);
            } else if(type === '@PriceChangeType.Sale') {
                var marginSale = toNumber($("#priceCurrency-" + anNo).val()) === 0 ? 0 : (((toNumber($("#newSalePrice-" + anNo).val()) - toNumber($("#priceCurrency-" + anNo).val())) / toNumber($("#priceCurrency-" + anNo).val())) * 100);

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

        function calculateIdentRabate(anNo, type) {
            if (type === '@PriceChangeType.Retail')
                $("#rabateRetail-" + anNo).val(toNumber($("#newRetailPrice-" + anNo).val()) - toNumber($("#retailPrice-" + anNo).val()));
            else if(type === '@PriceChangeType.Sale')
                $("#rabateSale-" + anNo).val(toNumber($("#newSalePrice-" + anNo).val()) - toNumber($("#salePrice-" + anNo).val()));
        }

        function calculateIdentRabateByPercent(anNo, type) {
            if (type === '@PriceChangeType.Retail')
                $("#rabateRetail-" + anNo).val((toNumber($("#retailPrice-" + anNo).val()) === 0 ? 1 : toNumber($("#retailPrice-" + anNo).val()))
                    / 100 * (toNumber($("#percentRetail-" + anNo).val()) === 0 ? 1 : toNumber($("#percentRetail-" + anNo).val())));
            else if (type === '@PriceChangeType.Sale')
                $("#rabateSale-" + anNo).val((toNumber($("#salePrice-" + anNo).val()) === 0 ? 1 : toNumber($("#salePrice-" + anNo).val()))
                    / 100 * (toNumber($("#percentSale-" + anNo).val()) === 0 ? 1 : toNumber($("#percentSale-" + anNo).val())));
        }

        function calculateIdentPrice(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                var newRetailPrice = (((toNumber($("#newSalePrice-" + anNo).val()) * (1 + toNumber($("#exciseIncP-" + anNo).val()) / 100)) + toNumber($("#exciseInc-" + anNo).val()))
                    * (1 + (toNumber($("#vat-" + anNo).val()) / 100))) + (toNumber($("#newSalePrice-" + anNo).val()) * (toNumber($("#exciseNotIncP-" + anNo).val()) / 100))
                    + toNumber($("#exciseNotInc-" + anNo).val());

                $("#newRetailPrice-" + anNo).val(newRetailPrice);
            }
            else if (type === '@PriceChangeType.Sale') {
                var newSalePrice = (toNumber($("#newRetailPrice-" + anNo).val()) - toNumber($("#exciseInc-" + anNo).val()) - (toNumber($("#exciseInc-" + anNo).val())
                    * (toNumber($("#vat-" + anNo).val()) / 100)) - toNumber($("#exciseNotInc-" + anNo).val())) / (((1 + (toNumber($("#exciseIncP-" + anNo).val()) / 100))
                        * (1 + toNumber($("#vat-" + anNo).val()) / 100)) + toNumber($("#exciseNotIncP-" + anNo).val()) / 100);

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

        function recalculateIdent(anNo, type) {
            if (type === '@PriceChangeType.Retail') {
                calculateIdentPrice(anNo, '@PriceChangeType.Sale');
                calculateIdentRabate(anNo, '@PriceChangeType.Sale');
                calculateIdentPercent(anNo, '@PriceChangeType.Sale');
                calculateIdentMargin(anNo, '@PriceChangeType.Sale');
            } else {
                calculateIdentPrice(anNo, '@PriceChangeType.Retail');
                calculateIdentRabate(anNo, '@PriceChangeType.Retail');
                calculateIdentPercent(anNo, '@PriceChangeType.Retail');
                calculateIdentMargin(anNo, '@PriceChangeType.Retail');
            }

            getIdentData(anNo);
            updatePriceTable();
            initializeNumberInputs();
        }

        function addPosition(invoiceItemData) {
            if (invoiceItemData != null) {
                selectedInvoiceItem = invoiceItemData;

                if (!$("#AcKey").val()) {
                    onSaveClick();
                } else {
                    addIdent();
                }

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

        function appendIdentToTable(data) {
            createIdentTableRow($("#idents"), data, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val());
            initializeNumberInputs();
        }

        function createIdentTableRow($element, data, decimalPlacesPrice, decimalPlacesQuntity) {
            var $row = $('<tr role="row" id="position-' + data.AnNo + '"></tr>');
            $row.append('<td><table><tr><td rowspan="2"><input id="anNo-' + data.AnNo + '" type="text" value="' + data.AnNo + '" class="form-control table-input-2" readonly /></td></tr></table></td>');
            $row.append('<td onclick="redirectToIdent(&quot;' + data.Ident + '&quot;)"><table><tr><td rowspan="2"><input id="id-' + data.AnNo + '" type="text" value="' + data.Ident + '" title="' + data.Ident + '" class="form-control table-input-2" readonly /></td></tr></table></td>');
            $row.append('<td><table><tr><td rowspan="2"><input id="name-' + data.AnNo + '" type="text" value="' + data.Name + '" title="' + data.Name + '" class="form-control table-input-2 border-left-solid" /></td></tr></table></td>');
            $row.append('<td><table><tr><td rowspan="2"><input id="stock-' + data.AnNo + '" type="text" value="' + data.Stock + '" onblur="getIdentData(' + data.AnNo + ')" step="' + decimalPlacesPrice + '" min="0" class="form-control table-input-2 numberInput border-left-solid invoice-input editableInput text-right required" autocomplete="off" readonly /></td></tr></table></td>');
            $row.append('<td><table><tr><td rowspan="2"><select id="measurementUnit-' + data.AnNo + '" value="' + data.MeasurementUnit + '" onchange="getIdentData(' + data.AnNo + ')" class="form-control table-input-2 border-left-solid">' + $("#measUnitOptions").html() + '</select></td></tr></table></td>');

            $row.append('<td><table><tr><td><input type="text" value="@Loc.RetailPriceShort" class="form-control text-right border-left-solid price-change-price-type-col" readonly /></td></tr>' +
                '<tr><td><input type="text" value="@Loc.SalePriceShort" class="form-control text-right border-left-solid price-change-price-type-col" autocomplete="off" readonly /></td></tr></table></td>');

            $row.append('<td><table><tr><td><input id="retailPrice-' + data.AnNo + '" type="text" value="' + data.RetailPrice + '" step="' + decimalPlacesPrice + '" min="0" class="form-control border-left-solid numberInput invoice-input editableInput text-right required" autocomplete="off" readonly /></td></tr>' +
                '<tr><td><input id="salePrice-' + data.AnNo + '" type="text" value="' + data.SalePrice + '" step="' + decimalPlacesPrice + '" min="0" class="form-control border-left-solid numberInput invoice-input editableInput text-right required" autocomplete="off" readonly /></td></tr></table></td>');

            $row.append('<td><table><tr><td><input id="newRetailPrice-' + data.AnNo + '" type="text" value="' + data.NewRetailPrice + '" onblur="onChangeNewPrice(' + data.AnNo + ', \'' + '@PriceChangeType.Retail' + '\')" step="' + decimalPlacesPrice + '" data-min="0" class="form-control numberInput border-left-solid invoice-input editableInput text-right required" autocomplete="off" /></td></tr>' +
                '<tr><td><input id="newSalePrice-' + data.AnNo + '" type="text" value="' + data.NewSalePrice + '" onblur="onChangeNewPrice(' + data.AnNo + ', \'' + '@PriceChangeType.Sale' + '\')" step="' + decimalPlacesPrice + '" data-min="0" class="form-control numberInput border-left-solid invoice-input editableInput text-right required" autocomplete="off" /></td></tr></table></td>');

            $row.append('<td><table><tr><td><input id="rabateRetail-' + data.AnNo + '" type="text" value="' + data.RabateRetail + '" onblur="onChangeRabate(' + data.AnNo + ',\'' + '@PriceChangeType.Retail' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr>' +
                '<tr><td><input id="rabateSale-' + data.AnNo + '" type="text" value="' + data.RabateSale + '" onblur="onChangeRabate(' + data.AnNo + ', \'' + '@PriceChangeType.Sale' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr></table></td>');

            $row.append('<td><table><tr><td><input id="percentRetail-' + data.AnNo + '" type="text" value="' + data.PercentRetail + '" onblur="onChangePercent(' + data.AnNo + ', \'' + '@PriceChangeType.Retail' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr>' +
                '<tr><td><input id="percentSale-' + data.AnNo + '" type="text" value="' + data.PercentSale + '" onblur="onChangePercent(' + data.AnNo + ', \'' + '@PriceChangeType.Sale' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr></table></td>');

            $row.append('<td><table><tr><td><input id="marginRetail-' + data.AnNo + '" type="text" value="' + data.MarginRetail + '" onblur="changeIdentMargin(' + data.AnNo + ', \'' + '@PriceChangeType.Retail' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr>' +
                '<tr><td><input id="marginSale-' + data.AnNo + '" type="text" value="' + data.MarginSale + '" onblur="changeIdentMargin(' + data.AnNo + ', \'' + '@PriceChangeType.Sale' + '\')" step="' + decimalPlacesPrice + '" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off" /></td></tr></table></td>');

            var $actions = $('<td><table><tr><td rowspan="2"></td></tr></table></td>');
            var $actionsTable = $('<table></table>');
            var $actionsTd = $('<td rowspan="2" class="actions-cell"></td>');
            $actionsTd.append(
                '<button id="noteModal-' + data.AnNo + '" onclick="openNoteModal(' + data.AnNo + ')" type="button" class="identNote btn btn-link table-input-2 ' + (data.Note !== "" ? "btn-active" : "") + '">' +
                '<i class="fa fa-comment"></i></button>' +
                '<input id="acKey-' + data.AnNo + '" value="' + data.AcKey + '" class="hidden" />' +
                '<input id="vat-' + data.AnNo + '" value="' + data.VAT + '" hidden />' +
                '<input id="exciseInc-' + data.AnNo + '" value="' + data.IncBase + '" hidden />' +
                '<input id="exciseNotInc-' + data.AnNo + '" value="' + data.NotIncBase + '" hidden />' +
                '<input id="exciseIncP-' + data.AnNo + '" value="' + data.IncBaseP + '" hidden />' +
                '<input id="exciseNotIncP-' + data.AnNo + '" value="' + data.NotIncBaseP + '" hidden />' +
                '<input id="priceCurrency-' + data.AnNo + '" value="' + data.PriceCurrency + '" hidden />'
            );
            $actionsTd.append('<button type="button" id="identRemove-' + data.AnNo + '" onclick="deletePosition(' + data.AnNo + ')" class="btn btn-outline editableInput table-input-2"><span class="far fa-trash-alt"></span></button>');

            $actionsTable.append($actionsTd);
            $actions.append($actionsTable);
            $row.append($actions);

            $element.append($row);
            $('#measurementUnit-' + data.AnNo).val(data.MeasurementUnit);
            selectedInvoiceItem = null;
        }

        function onSaveClick(option, printType = null){
            if ($("#AcKey").val() && $("#Status").val() === "@VerifyStatus.Confirmed"){
                let isFormClean = $("#PriceChangeForm").customDirtyChecker("check");
                if (isFormClean) {
                    save(option, printType);
                    return;
                }

                $().customModal({
                        title: "",
                        destroyOnClose: true,
                        showCloseButton: true,
                        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 () {
                                    $("#PriceChangeForm").customDirtyChecker();
                                    save(option, printType);
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            }
            else {
                save(option, printType);
            }
        }

        var printWindow;
        function save(option, printType = null) {
            if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
                printWindow = createPrintWindow(printWindow);
            }

            if (checkFormEditable() === false && option) {
                print(option, printType);
                return;
            } else if (checkFormEditable() === false)
                return;

            swapLoadingIcon(true, "saveButton");

            var formData = $("#PriceChangeForm").serializeArray();
            formData.push({ name: 'ItemsJsonString', value: JSON.stringify(invoiceItems) });
            formData = changeFormDataValue(formData, 'Note', encodeURIComponent($("#Note").val()));

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

            $.post(url, formData)
                .done(function (response) {
                    if (response.Success) {
                        if (!$("#AcKey").val()) {
                            $("#AcKey").val(response.data.AcKey);
                            refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
                            $("#Referent").val(response.data.Referent);
                            $("#DocTypeSelect").attr("disabled", true);
                            $("#confirmButton").attr("disabled", false);
                            $("#deleteButton").removeClass("hidden");
                            $("#newButton").removeClass("hidden");
                            window.history.pushState({}, null, "@Url.Action("Edit", "PriceChange")?id=" + response.data.AcKey);
                            clearValidationErrors();
                        }

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

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

                        addIdent();

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

                        clearValidationErrors();
                        displayErrors(response);

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }
                    swapLoadingIcon(false, "saveButton");
                });
        }

        function print(option, printType) {
            printPAAS(printType, false, false);
        }

        function displayResponseValidationErrors(response) {
            for (var i = 0; i < response.errors.length; i++) {
                var span = document.getElementById(response.errors[i].Key + "-validation");
                errorText = document.createTextNode(response.errors[i].Value);
                if (span)
                    span.appendChild(errorText);
            }
        }

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

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

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

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

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

        function addIdent() {
            if (selectedInvoiceItem != null) {
                swapLoadingIcon(true, "add-position");

                $.post('@Url.Action("CreateItem", "PriceChange")', {
                    AcKey: $("#AcKey").val(),
                    Ident: selectedInvoiceItem.id,
                    Quantity: 1,
                    AnNo: invoiceItems.length + 1
                }).done(function (response) {
                    if (response.Success) {
                        invoiceItems.push(response.ident);
                        appendIdentToTable(response.ident);
                        updatePriceTable();
                    } else {
                    }
                    swapLoadingIcon(false, "add-position");
                });
            }
        }

        function savePosition(anNo) {
            swapLoadingIcon(true, "save-" + anNo);
            $.post('@Url.Action("UpdateInvoiceItem", "MoveItem")', getIdentData(anNo))
                .done(function (response) {
                    updatePriceTable();
                    swapLoadingIcon(false, "save-" + anNo);
                });
        }

        function getIdentData(anNo) {
            var ident = {
                AnNo: anNo,
                AcKey: $("#acKey-" + anNo).val(),
                Price: toNumber($("#price-" + anNo).val()),
                Note: $("#note-" + anNo).val(),
                Name: $("#name-" + anNo).val(),
                Ident: $("#id-" + anNo).val(),
                MeasurementUnit: $("#measurementUnit-" + anNo + " option:selected").val(),
                VAT: toNumber($("#vat-" + anNo).val()),
                Stock: toNumber($("#stock-" + anNo).val()),

                RetailPrice: toNumber($("#retailPrice-" + anNo).val()),
                NewRetailPrice: toNumber($("#newRetailPrice-" + anNo).val()),
                RabateRetail: toNumber($("#rabateRetail-" + anNo).val()),

                SalePrice: toNumber($("#salePrice-" + anNo).val()),
                NewSalePrice: toNumber($("#newSalePrice-" + anNo).val()),
                RabateSale: toNumber($("#rabateSale-" + anNo).val()),
            };

            invoiceItems[getInvoiceItemIndex(anNo)] = ident;
            return ident;
        }

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

        function updatePriceTable() {
            var totalPC = 0;
            var totalMPC = 0;

            for (var i = 0; i < invoiceItems.length; i++) {
                totalPC += toNumber(invoiceItems[i].RabateSale) * toNumber(invoiceItems[i].Stock);
                totalMPC += toNumber(invoiceItems[i].RabateRetail) * toNumber(invoiceItems[i].Stock);
            }

            $("#TotalPC").val(isNaN(totalPC) ? 0 : totalPC);
            $("#TotalMPC").val(isNaN(totalMPC) ? 0 : totalMPC);

            initializeNumberInputs();
        }

        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 deletePosition(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 () {
                            swapLoadingIcon(true, "add-position");
                            $.post('@Url.Action("RemoveInvoiceItem", "MoveItem")', { AcKey: $("#AcKey").val(), AnNo: anNo })
                                .done(function (response) {
                                    invoiceItems.splice(getInvoiceItemIndex(anNo), 1);
                                    $("#position-" + anNo).remove();
                                    updatePriceTable();

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

                                    swapLoadingIcon(false, "add-position");
                                });
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function clearValidationErrors() {
            $(".field-validation-valid").text(' ');
        }

        function confirm() {
            swapLoadingIcon(true, "confirmButton");
            $.post('@Url.Action("Validate", "PriceChange")', { id: $("#AcKey").val() })
                .done(function (response) {
                    if (response.Success) {
                        confirmPriceChange();
                    } else {
                        $("#errorModalMessage").text(response.response.Error);
                        $("#errorModal").modal('show');
                    }

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

        function openWarehouseSelect() {
            $("#warehousesModal").modal('show');
        }

        function warehousesSelectionChanged(cb) {
            if (cb.checked) {
                selectedWarehouses.push(cb.value);
            } else {
                var index = selectedWarehouses.indexOf(cb.value);
                if (index !== -1)
                    selectedWarehouses.splice(index, 1);
            }
        }

        function confirmWarehousesSelection() {
            if (warehousesWithoutDocTypeExist === true) {
                $().customModal({
                    title: "",
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "confirmWarehouseAlertModal",
                    type: "question",
                    text: "@Loc.ForWarehousesWithoutDocTypePriceChangeWillNotBeCreated",
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: '@Loc.No',
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: '@Loc.Yes',
                            action: async function () {
                                confirmPriceChange();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else
                confirmPriceChange();
        }

        function confirmPriceChange() {
            swapLoadingIcon(true, "confirmButton");
            $.post('@Url.Action("Confirm", "PriceChange")', { id: $("#AcKey").val() })
                .done(function (response) {
                    var modalMsg;
                    if (response.Success) {
                        $("#Status").val("@VerifyStatus.Confirmed");
                        modalMsg = "@Loc.PriceChangeSuccess";
                    } else {
                        modalMsg = "@Loc.PriceChangeFailed";
                    }

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

                    checkFormEditable();
                    swapLoadingIcon(false, "confirmButton");
                });
        }

        function checkFormEditable() {
            $("#printButton").prop("disabled", false);
            $("#printButton + button").prop("disabled", false);

            if ($("#AcKey").val() && $("#Status").val() === "@VerifyStatus.Confirmed") {
                $("#confirmButton").prop("disabled", true);
                return true;
            } else {
                return true;
            }
        }

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

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

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

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

            getIdentData(selectedItemAnNo);
        }

        function openInvoiceNoteModal() {
            $("#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" : "");
        }
</script>
}