@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Helpers
@using PantheonRA.BackOffice.Models
@model PantheonRA.BackOffice.Models.StockGridFilterModel
@{
    ViewBag.Title = Loc.Stock;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_ReportsTabNavigation")
        <div class="row buttons-tabbed">
            @Html.Partial("~/Views/Shared/Components/_PrintMenuButton.cshtml", new PantheonRA.BackOffice.Models.PrintMenuDropdownViewModel
            {
                PrintButtonGroup = ReportsHelper.FormatReportTree(
                    Model.ReportTreeStock,
                    "printStock('{0}')",
                    null
                ),
                PrintType = ReportFormName.Stock,
                PrintButtonId = "printButton",
            })

            @Html.Partial("~/Views/Shared/Components/_PrintMenuButton.cshtml", new PantheonRA.BackOffice.Models.PrintMenuDropdownViewModel
            {
                PrintButtonGroup = ReportsHelper.FormatReportTree(
                    Model.ReportTreeStockCard,
                    "printStock('{0}')",
                    null
                ),
                PrintType = ReportFormName.StockCard,
                PrintButtonId = "printButton1"
            })

            @Html.Partial("~/Views/Shared/Components/_PrintMenuButton.cshtml", new PantheonRA.BackOffice.Models.PrintMenuDropdownViewModel
            {
                PrintButtonGroup = ReportsHelper.FormatReportTree(
                    Model.ReportTreeSerialNumbers,
                    "printStock('{0}')",
                    null
                ),
                PrintType = ReportFormName.SerialNumbers,
                PrintButtonId = "printButton2"
            })

            @Html.Partial("_FormButtons", new FormButtonsViewModel
            {
                ShowCloseBtn = false,
                IsWizardVisible = true,
                WizardButtonGroup = new FormButtonGroup
                {
                    Buttons = new List<FormButton>
                    {
                        new FormButton { Text = Loc.StockRecalc, Icon = "", OnClick = "openStockRecalc()", IsHidden = true },
                        new FormButton { Text = Loc.StockRecalc, Icon = "", OnClick = "openStockRecalc()" },
                    }
                }
            })
        </div>

        <div class="tab-content">
            @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
            @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
            <div class="row document-head">
                <div class="col-md-2 col-xs-6">
                    <div class="form-group">
                        @Html.Label(Loc.TypeOfView, new { @class = "control-label" })
                        <select id="stockCategory" class="form-control custom-select">
                            <option value="@StockPrintType.StockOverview" data-helpurl="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ReportsStock)">@Loc.CurrentStockOverview</option>
                            <option value="@StockPrintType.StockCard" data-helpurl="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ReportsStockCard)">@Loc.StockCard</option>
                            <option value="@StockPrintType.SerialNumbers" data-helpurl="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ReportsStockCard)">@Loc.SerialNumberReview</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-2 col-xs-6">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Warehouse, Loc.Warehouse, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            @Html.DropDownListFor(model => model.Warehouse,
                                new SelectList(ViewBag.Departments != null ? ViewBag.Departments : new List<string>(), "Id", "Name"), Loc.Warehouse,
                                HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Warehouse", false, Loc.Warehouse, true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All }))
                        </div>
                    </div>
                </div>
                <div class="col-md-2 col-xs-6">
                    <div class="form-group">
                        @Html.LabelFor(model => model.SetOfItem, Loc.AccountingType, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            @Html.DropDownListFor(model => model.SetOfItem,
                                new SelectList(ViewBag.Types != null ? ViewBag.Types : new List<string>(), "Id", "Name"), Loc.ItemType,
                                HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "SetOfItem", false, Loc.AccountingTypes, true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All }))
                        </div>
                    </div>
                </div>
                <div class="col-md-2 col-xs-6" id="docTypeContainer" hidden>
                    <div class="form-group">
                        @Html.LabelFor(model => model.DocType, Loc.DocumentTypes, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            @Html.DropDownListFor(model => model.DocType,
                                new SelectList(ViewBag.DocTypes != null ? ViewBag.DocTypes : new List<string>(), "Id", "Value"), Loc.DocumentTypes,
                                HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "DocType", false, Loc.DocumentTypes, true, new { @multiple = "multiple", @title = Loc.All }))
                        </div>
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-6">
                    <div class="form-group typeahead-ident-filter">
                        @Html.Label(Loc.Product, new { @class = "control-label" })
                        <input type="hidden" id="productPlaceholder" title="@Loc.Product" />
                        <input type="text" class="typeahead_3 form-control" id="IdentFilterSearch" dataUrl="@Url.Action("SearchIdents", "SetItem")"
                               placeholder="@Loc.EnterIdentProduct" autocomplete="off" />
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-6" id="subjectFilterContainer">
                    <div class="form-group typeahead-ident-filter">
                        @Html.Label(Loc.Partner, new { @class = "control-label" })
                        <input type="hidden" id="partnerPlaceholder" title="@Loc.Partner" />
                        <input type="text" class="typeahead_3 form-control" id="SubjectFilterSearch" dataUrl="@Url.Action("SearchSubjects", "Reports")"
                               placeholder="@Loc.Partner" autocomplete="off" />
                    </div>
                </div>
                <div class="col-lg-2 col-md-2 col-xs-6 serialNumberFiltersContainer">
                    <div class="form-group">
                        @Html.Label(Loc.EnterSerialNumber, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            <select id="EnterSerialNumber" class="form-control selectpicker" multiple="multiple" title="@Loc.All">
                                <option value="">@Loc.All</option>
                                <option value="N">N - @Loc.NoManagement</option>
                                <option value="S">S - @Loc.SerialNumberS</option>
                                <option value="K">K - @Loc.SerialNumberK</option>
                                <option value="P">P - @Loc.SerialNumberP</option>
                                <option value="E">E - @Loc.SerialNumberE</option>
                                <option value="O">O - @Loc.SerialNumberO</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-lg-2 col-md-2 col-xs-6 serialNumberFiltersContainer">
                    <div class="form-group">
                        <label class="control-label">@Loc.SerialNumber</label>
                        @Html.TextBox("SerialNumberFilter", null, new { @id = "SerialNumberFilter", @class = "form-control", @placeholder = Loc.SerialNumber, autocomplete = "off" })
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-6">
                    <div class="form-group">
                        @Html.LabelFor(model => model.DateFrom, Loc.StockForDay, new { @class = "control-label", @id = "dateFromLabel" })
                        <div class="date">
                            @Html.TextBoxFor(m => m.DateFrom, "{0:" + Loc.DateFormat + "}", new
                            {
                                @class = "form-control datepicker hidden",
                                @autocomplete = "off"
                            })
                            @Html.TextBox("DateFromToday", DateTime.Now.ToString(Loc.DateFormat), new
                            {
                                @class = "form-control datepicker",
                                @autocomplete = "off"
                            })
                        </div>
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-6" id="dateToContainer" hidden>
                    <div class="form-group">
                        @Html.LabelFor(model => model.DateTo, Loc.DateTo, new { @class = "control-label" })
                        <div class="date">
                            @Html.TextBoxFor(m => m.DateTo, "{0:" + Loc.DateFormat + "}", new { @class = "form-control datepicker", @autocomplete = "off" })
                        </div>
                    </div>
                </div>
                <div class="col-lg-2 col-md-2 col-xs-6" id="priceTypeContainer" hidden>
                    <div class="form-group">
                        @Html.LabelFor(model => model.PriceType, Loc.PriceType, new { @class = "control-label" })
                        @Html.DropDownListFor(model => model.PriceType, new List<SelectListItem>
                        {
                           new SelectListItem{ Text=Loc.PriceForEvaluation, Value = PriceType.PriceForEvaluation },
                           new SelectListItem{ Text=Loc.RetailPriceLong, Value = PriceType.RetailPriceLong },
                           new SelectListItem{ Text=Loc.SellingPrice, Value = PriceType.SellingPrice },
                           new SelectListItem{ Text=Loc.WholesalePrice1Short, Value = PriceType.WholesalePrice1Short },
                           new SelectListItem{ Text=Loc.WholesalePrice2Short, Value = PriceType.WholesalePrice2Short }
                        }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "PriceType", false, Loc.PriceType))
                    </div>
                </div>
            </div>

            <input id="filterColumn" hidden />
            <input id="filterCriteria" hidden />
            <input id="filterValue" hidden />
            <input id="filterValue2" hidden />
            <div class="project-list reportStockTableContainer">
                <div id="stockTable" class="document-list absoluteTableContainer">
                    <table id="stockGrid" data-grid-id="stock" class="list-table">
                        <thead>
                            <tr>
                                <th width="20%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Ident</th>
                                <th width="25%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Name</th>
                                <th width="15%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Warehouse</th>
                                <th width="10%" class="dt-head-right">@Loc.Stock</th>
                                <th width="5%">@Loc.MeasUnit</th>
                                <th width="10%" class="dt-head-right">@Loc.Price</th>
                                <th width="10%" class="dt-head-right">@Loc.Value</th>
                                <th width="5%">@Loc.Currency</th>
                            </tr>
                        </thead>
                    </table>
                </div>

                <div id="stockCardTable" class="document-list absoluteTableContainer invisible">
                    <table id="stockCardGrid" data-grid-id="stock-card" class="list-table">
                        <thead>
                            <tr>
                                <th width="3%" data-function="openPdfPreview('@Url.Action("PrintInvoicePdf", "CashRegister")?paperSize=printer_A4&id={0}')"
                                    data-function-I="openPdfPreview('@Url.Action("WholesalePdf", "Wholesale")?paperSize=printer_A4&id={0}')"
                                    data-function-P="openPdfPreview('@Url.Action("ReceivedBillPdf", "ReceivedBills")?paperSize=printer_A4&id={0}')">
                                </th>
                                <th width="8%" data-url="@Url.Action("PrintPreview", "CashRegister")?returnUrl=@(Url.Action("Stock", "Reports"))&id="
                                    data-url-I="@Url.Action("Edit", "Wholesale")?returnUrl=@(Url.Action("Stock", "Reports"))&id="
                                    data-url-P="@Url.Action("Edit", "ReceivedBills")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">
                                    @Loc.Document
                                </th>
                                <th width="7%">@Loc.Date</th>
                                <th width="13%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Warehouse</th>
                                <th width="10%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Ident</th>
                                <th width="13%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Name</th>
                                <th width="10%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Subject</th>
                                <th width="7%">@Loc.Receive</th>
                                <th width="7%">@Loc.Issue</th>
                                <th width="5%">@Loc.Stock</th>
                                <th width="5%">@Loc.MeasUnit</th>
                                <th width="5%" class="dt-head-right">@Loc.Price</th>
                                <th width="7%" class="dt-head-right">@Loc.Value</th>
                            </tr>
                        </thead>
                    </table>
                </div>

                <div id="serialNumbersTable" class="document-list absoluteTableContainer invisible">
                    <table id="serialNumbersGrid" data-grid-id="serial-numbers" class="list-table">
                        <thead>
                            <tr>
                                <th width="20%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Ident</th>
                                <th width="20%" data-url="@Url.Action("Edit", "Products")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Name</th>
                                <th width="20%">@Loc.ProductMenuSerialNumbersTitle</th>
                                <th width="20%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Stock", "Reports"))&id=">@Loc.Warehouse</th>
                                <th width="10%" class="dt-head-right">@Loc.Stock</th>
                                <th width="10%">@Loc.MeasUnit</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@Html.Partial("~/Views/Shared/Components/_sidePanel.cshtml", new PantheonRA.BackOffice.Models.SidePanelViewModel { Id = "pdfPanel" })

<div class="modal inmodal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm" 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="stockRecalcModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-stock-recalc" role="document">
        <div class="modal-content partialStockRecalcModalContent">
            <div class="modal-header padding-bottom-none">
                <div class="tabs-container" id="stockRecalcModalTabs">
                    <ul class="nav nav-tabs horizontal-menu">
                        <li class="active"><a class="local-tab" data-toggle="tab" href="#stockRecalcTab">@Loc.StockRecalc</a></li>
                        <li><a class="local-tab" data-toggle="tab" href="#stockRecalcErrorsTab">@Loc.Errors</a></li>
                        <li class="pull-right flex-pull-right"><button type="button" class="btn-transparent m-r-xxs" onclick="openStockRecalcHelp()"><i class="fas fa-question clickable-icon"></i></button></li>
                        <li class="pull-right m-r-md m-t-xxs"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></li>
                    </ul>
                </div>
            </div>
            <div class="modal-body stockRecalcModalBody">
                @{Html.RenderPartial("~/Views/Reports/_StockRecalcPartial.cshtml",
                            new StockRecalcModel()
                            {
                                StockRecalcDate = Model.MoveOpenDate
                            });
                }
            </div>
            <div class="modal-footer" id="stockRecalcModalFooter">
                <button type="button" class="btn btn-link" data-dismiss="modal"><i class="fa fa-times m-r-xs text-primary"></i>@Loc.Cancel</button>
                <button type="button" class="btn btn-primary" id="stockRecalcBtn" onclick="stockRecalc()"><i class="fa fa-check m-r-xs"></i>@Loc.Recovery</button>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="RepeatAnimation" value="@Url.Content("~/Content/Animations/DocumentLoading.gif")" />
<input type="hidden" id="LoadingDocumentLoc" value="@Loc.LoadingDocument" />
<input type="hidden" id="ConfirmLoc" value="@Loc.Confirm" />

@section pageScripts{
    <script>
        $(document).ready(function () {
            $("#printButton").prop("disabled", false);
            $("#printButton + button").prop("disabled", false);
            $("#printButton1").prop("disabled", false);
            $("#printButton1 + button").prop("disabled", false);
            $("#printButton1").parent().addClass("hidden");
            $("#printButton2").prop("disabled", false);
            $("#printButton2 + button").prop("disabled", false);
            $("#printButton2").parent().addClass("hidden");

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

            initializeIdentBasicTypeahead($('#IdentFilterSearch').attr('dataUrl'), $('#IdentFilterSearch'), $('#IdentFilterSearch'), { item: '@Loc.Item', name: '@Loc.Name' }, null, function (item) {
                $("#productPlaceholder").val(item.id);
                $("#IdentFilterSearch").val(item.id);
                $.fn.dataTable.reload($dataTable);
                return { selected: true, value: item.id };
            });

            initializeBasicPartnerTypeahead($('#SubjectFilterSearch').attr('dataUrl'), $('#SubjectFilterSearch'), $("#SubjectFilterSearch"), function (item) {
                $("#partnerPlaceholder").val(item.value);
                $("#SubjectFilterSearch").val(item.value);
                $.fn.dataTable.reload($dataTable);
                return { selected: true, value: item.value };
            });

            $("#SubjectFilterSearch").on("change", function () {
                if ($("#SubjectFilterSearch").val() === "")
                    $.fn.dataTable.reload($dataTable);
            });

            $("#IdentFilterSearch").on("change", function () {
                if ($("#IdentFilterSearch").val() === "")
                    $.fn.dataTable.reload($dataTable);
            });

            $("#SerialNumberFilter").on("change", function () {
                $.fn.dataTable.reload($dataTable);
            });

            if (!localStorage.stockCategory) {
                initializeStockOverview();
            }

            $(".dropdown-select").off("change");
            $(".dropdown-select").on("change", function () {
                $.fn.dataTable.reload($dataTable);
            });

            $(".selectpicker-container").on("hide.bs.dropdown", function () {
                $.fn.dataTable.reload($dataTable);
            });

            var typingTimer;
            var doneTypingInterval = 600;
            $('#Keywords').off('keyup');
            $('#Keywords').on('keyup', function () {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
            });

            $('.selectpicker').val('default').selectpicker('refresh');
            $('#stockCategory').on("change", function () {
                if ($(this).val() == '@StockPrintType.StockOverview') {
                    if ($('#stockCardGrid').hasClass("dataTable")) {
                        let stockCardGrid = $('#stockCardGrid').DataTable();
                        $(".filter-icon").remove();
                        stockCardGrid.destroy();
                    }
                    initializeStockOverview();
                } else if ($(this).val() == '@StockPrintType.SerialNumbers') {
                    if ($('#serialNumbersGrid').hasClass("dataTable")) {
                        let serialNumbersGrid = $('#serialNumbersGrid').DataTable();
                        $(".filter-icon").remove();
                        serialNumbersGrid.destroy();
                    }
                    initializeSerialNumbers();
                } else {
                    if ($('#stockGrid').hasClass("dataTable")) {
                        let stockGrid = $('#stockGrid').DataTable();
                        $(".filter-icon").remove();
                        stockGrid.destroy();
                    }
                    initializeStockCard();
                }

                changeCategory();
            });

            if (localStorage.stockCategory) {
                $("#stockCategory").val(localStorage.stockCategory);
                $('#stockCategory').trigger("change");
            }

            $('#PriceType').on("change", function () {
                if ($('#stockCategory').val() === '@StockPrintType.StockOverview') {
                    $.fn.dataTable.reload($dataTable);

                }
            });
        });

        function format(item) {
            return item.Text;
        }

        let printWindow;
        function printStock(reportCode) {
            swapLoadingIcon(true, "printButton", "far fa-print");

            var url;
            if ($("#stockCategory option:selected").val() === "@StockPrintType.StockOverview")
                url = "@Url.Action("StockPrint", "Reports")" + "?DateFrom=" + reformatDate($("#DateFromToday").val());
            else if ($("#stockCategory option:selected").val() === "@StockPrintType.SerialNumbers")
                url = "@Url.Action("SerialNumbersPrint", "Reports")" + "?DateFrom=" + reformatDate($("#DateFromToday").val());
            else {
                url = "@Url.Action("StockCardPrint", "Reports")" + "?DateFrom=" + reformatDate($("#DateFrom").val());

                if ($("#DateTo").val())
                    url = url + "&DateTo=" + reformatDate($("#DateTo").val());
            }

            var subject = $("#SubjectFilterSearch").val();
            var ident = $("#IdentFilterSearch").val();
            var warehouse = $("#Warehouse").val();
            var priceType = $("#PriceType").val();
            var serialNumberFilter = $("#SerialNumberFilter").val();
            var docType = $("#DocType").val() ? $("#DocType").val().toString() : null;
            var setOfItem = $("#SetOfItem").val() ? $("#SetOfItem").val().toString() : null;
            var enterSerialNumber = $("#EnterSerialNumber").val() ? $("#EnterSerialNumber").val().toString() : null;

            if (docType)
                url = url + "&DocType=" + docType;
            if (setOfItem)
                url = url + "&SetOfItem=" + setOfItem;
            if (warehouse)
                url = url + "&Warehouse=" + warehouse;
            if (ident)
                url = url + "&Ident=" + ident;
            if (subject)
                url = url + "&Subject=" + subject;
            if (priceType)
                url = url + "&PriceType=" + priceType;
            if (serialNumberFilter)
                url = url + "&SerialNumber=" + serialNumberFilter;
            if (enterSerialNumber)
                url = url + "&EnterSerialNumber=" + enterSerialNumber;
            if (reportCode)
                url = url + "&ReportType=" + reportCode;

            url = url + "&filterColumn=" + $("#filterColumn").val()
                + "&filterCriteria=" + $("#filterCriteria").val()
                + "&filterValue=" + $("#filterValue").val()
                + "&filterValue2=" + $("#filterValue2").val()

            printWindow = window.open();
            printWindow.document.write(generatePrintingPage());
            printPAAS("", false, false, url, false);
            swapLoadingIcon(false, "printButton", "far fa-print");
        }

        function changeCategory() {
            let helpUrl = $("#stockCategory option:selected").attr("data-helpurl");
            setGlobalHelpUrl(helpUrl);

            if ($("#stockCategory option:selected").val() === "@StockPrintType.StockOverview") {
                $("#stockTable").removeClass("hidden");
                $("#stockCardTable").addClass("invisible");
                $("#serialNumbersTable").addClass("invisible");
                $('#DateFrom').addClass("hidden");
                $('#DateFromToday').removeClass("hidden");
                $('#DateFromToday').datepicker("setDate", Date.now.toString('MM/DD/YYYY'));
                $("#dateFromLabel").text("@Loc.StockForDay");
                $("#dateToContainer").attr("hidden", true);
                $("#docTypeContainer").attr("hidden", true);
                $("#priceTypeContainer").attr("hidden", false);
                $("#subjectFilterContainer").attr("hidden", false);
                $(".serialNumberFiltersContainer").attr("hidden", true);
                $("#printButton1").parent().addClass("hidden");
                $("#printButton2").parent().addClass("hidden");
                $("#printButton").parent().removeClass("hidden");
                $("#PrintType").val("@ReportFormName.Stock");
            } else if ($("#stockCategory option:selected").val() === "@StockPrintType.StockCard") {
                $("#stockTable").addClass("hidden", true);
                $("#stockCardTable").removeClass("invisible");
                $("#serialNumbersTable").addClass("invisible");
                $('#DateFrom').removeClass("hidden");
                $('#DateFromToday').addClass("hidden");
                $("#dateFromLabel").text("@Loc.DateFrom");
                $("#dateToContainer").attr("hidden", false);
                $("#docTypeContainer").attr("hidden", false);
                $("#priceTypeContainer").attr("hidden", true);
                $(".serialNumberFiltersContainer").attr("hidden", true);
                $("#subjectFilterContainer").attr("hidden", false);
                $("#printButton").parent().addClass("hidden");
                $("#printButton1").parent().removeClass("hidden");
                $("#printButton2").parent().addClass("hidden");
                $("#PrintType").val("@ReportFormName.StockCard");
            } else {
                $("#stockTable").addClass("hidden", true);
                $("#stockCardTable").addClass("invisible");
                $("#serialNumbersTable").removeClass("invisible");
                $('#DateFrom').addClass("hidden");
                $('#DateFromToday').removeClass("hidden");
                $('#DateFromToday').datepicker("setDate", "");
                $("#dateFromLabel").text("@Loc.StockForDay");
                $("#dateToContainer").attr("hidden", true);
                $("#docTypeContainer").attr("hidden", true);
                $("#priceTypeContainer").attr("hidden", true);
                $(".serialNumberFiltersContainer").attr("hidden", false);
                $("#subjectFilterContainer").attr("hidden", true);
                $("#printButton").parent().addClass("hidden");
                $("#printButton1").parent().addClass("hidden");
                $("#printButton2").parent().removeClass("hidden");
                $("#PrintType").val("@ReportFormName.SerialNumbers");
            }

            localStorage.stockCategory = $("#stockCategory option:selected").val();
        }

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

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

        function openPdfPreview(url) {
            loadPdfPanelContent($("#pdfPanel"), url, true);
        }

        function initializeStockOverview() {
            $("#stockGrid").attr("data-url", "@Url.Action("StockData", "Reports")")
            $dataTable = $('#stockGrid');

            if ($.fn.dataTable.isDataTable('#stockGrid'))
                $dataTable.DataTable().destroy();

            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        // TODO: When dates are available - currently readonly
                        d.DateFrom = reformatDate($("#DateFromToday").val());
                        //d.DateTo = reformatDate($("#DateTo").val());
                        d.DocType = $("#DocType").val() ? $("#DocType").val().toString() : "";
                        d.Ident = $("#IdentFilterSearch").val();
                        d.SetOfItem = $("#SetOfItem").val() ? $("#SetOfItem").val().toString() : "";
                        d.Subject = $("#SubjectFilterSearch").val();
                        d.Warehouse = $("#Warehouse").val() ? $("#Warehouse").val().toString() : "";
                    }
                },
                columns: [
                    { data: "Ident", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
                    { data: "Name", name: "AcIdentNavigation.AcName", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
                    { data: "Warehouse", name: "AcWarehouse", filtertype: "text", render: $.fn.dataTable.render.link("Warehouse") },
                    { data: "Stock", name: "AnStockQty", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
                    { data: "Unit", name: "AcIdentNavigation.AcUm", filtertype: "text" },
                    {
                        data: "LastPrice", name: "AnLastPrice", filtertype: "number", className: 'dt-body-right', render: function (data, type, full) {
                            if (type === 'display') {
                                var displayPrice;
                                switch ($("#PriceType").val()) {
                                    case '@PriceType.PriceForEvaluation': displayPrice = data; break;
                                    case '@PriceType.RetailPriceLong': displayPrice = full.SalePrice; break;
                                    case '@PriceType.SellingPrice': displayPrice = full.RetailPrice; break;
                                    case '@PriceType.WholesalePrice1Short': displayPrice = full.WsPrice; break;
                                    case '@PriceType.WholesalePrice2Short': displayPrice = full.WsPrice2; break;
                                    default: displayPrice = data; break;
                                }

                                return formatDisplay($("#DefaultDecimalPlacesPrice").val(), displayPrice);
                            }

                            return formatDisplay($("#DefaultDecimalPlacesPrice").val(), data);
                        }
                    },
                    { data: "SellingPrice", name: "AnValue", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()) },
                    { data: "Currency", name: "AcCurrency", filtertype: "text" },
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.CanceledInvoice) {
                        $(row).addClass('danger');
                    }
                },
                drawCallback: function (settings) {
                    closeSidePanel($("#pdfPanel"));
                }
            });
        }

        function initializeStockCard() {
            $("#stockCardGrid").attr("data-url", "@Url.Action("StockCardData", "Reports")")
            $dataTable = $('#stockCardGrid');

            if ($.fn.dataTable.isDataTable('#stockCardGrid'))
                $dataTable.DataTable().destroy();

            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        d.DateFrom = reformatDate($("#DateFrom").val());
                        d.DateTo = reformatDate($("#DateTo").val());
                        d.DocType = $("#DocType").val() ? $("#DocType").val().toString() : "";
                        d.Ident = $("#IdentFilterSearch").val();
                        d.SetOfItem = $("#SetOfItem").val() ? $("#SetOfItem").val().toString() : "";
                        d.Subject = $("#SubjectFilterSearch").val();
                        d.Warehouse = $("#Warehouse").val() ? $("#Warehouse").val().toString() : "";
                    }
                },
                columns: [
                    { data: "AcKey", name: "AcKey", render: $.fn.dataTable.render.previewByDocType("AcKey"), className: 'dt-body-center' },
                    { data: "AcKeyView", name: "AcKeyView", render: $.fn.dataTable.render.linkByDocType("AcKey", false), filtertype: "text" },
                    { data: "Date", name: "AdDate", filtertype: "dateTime" },
                    { data: "Warehouse", name: "AcWarehouse", filtertype: "text", render: $.fn.dataTable.render.link("Warehouse") },
                    { data: "Ident", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
                    { data: "Name", name: "AcIdentName", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
                    { data: "Subject", name: "AcSubject", filtertype: "text", render: $.fn.dataTable.render.link("SubjectId") },
                    { data: "Takeover", name: "Takeover", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
                    { data: "Issue", name: "Issue", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
                    { data: "Stock", name: "AcStockEndValue", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
                    { data: "Unit", name: "AcUM", filtertype: "text" },
                    { data: "RetailPrice", name: "AnPrice", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()) },
                    { data: "SellingPrice", name: "AnValue", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()) }
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.CanceledInvoice) {
                        $(row).addClass('danger');
                    }
                },
                drawCallback: function (settings) {
                    closeSidePanel($("#pdfPanel"));
                }
            });
        }

        function initializeSerialNumbers() {
            $("#serialNumbersGrid").attr("data-url", "@Url.Action("SerialNumbersData", "Reports")")
            $dataTable = $('#serialNumbersGrid');

            if ($.fn.dataTable.isDataTable('#serialNumbersGrid'))
                $dataTable.DataTable().destroy();

            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        d.DateFrom = reformatDate($("#DateFrom").val());
                        d.Ident = $("#IdentFilterSearch").val();
                        d.SetOfItem = $("#SetOfItem").val() ? $("#SetOfItem").val().toString() : "";
                        d.SerialNumber = $("#SerialNumberFilter").val();
                        d.Warehouse = $("#Warehouse").val() ? $("#Warehouse").val().toString() : "";
                        d.EnterSerialNumber = $("#EnterSerialNumber").val() ? $("#EnterSerialNumber").val().toString() : "";
                    }
                },
                columns: [
                    { data: "AcIdent", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("AcIdent") },
                    { data: "AcName", name: "AcName", filtertype: "text", render: $.fn.dataTable.render.link("AcIdent") },
                    { data: "AcSerialNo", name: "AcSerialNo", filtertype: "text", render: $.fn.dataTable.render.ellipsis(40) },
                    { data: "AcWarehouse", name: "AcWarehouse", filtertype: "text", render: $.fn.dataTable.render.link("AcWarehouse") },
                    { data: "AnStock", name: "AnStock", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
                    { data: "AcUM", name: "AcUM", filtertype: "text" },
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.CanceledInvoice) {
                        $(row).addClass('danger');
                    }
                },
                drawCallback: function (settings) {
                    closeSidePanel($("#pdfPanel"));
                }
            });
        }

        function openStockRecalc() {
            $('[href="#stockRecalcTab"]').tab('show');
            $("#stockRecalcModal").modal("show");
        }

        function openStockRecalcHelp() {
            window.open('@PantheonRA.BackOffice.Helpers.SiteHelpAttributeHelper.GetHelpUrl(HelpIds.StockRecalc)', '_blank');
        }
    </script>
}