@page
@model NorthwindRazor.Pages.Products_ListCrudModel
@{
    ViewData["Title"] = "List of Products";
}
 
@section AdditionalCss {
    <link rel="stylesheet" href="~/css/ui.jqgrid.min.css" />
}
 
@section AdditionalJavaScript {
    <script src="~/js/jqgrid-i18n/grid.locale-en.min.js" asp-append-version="true"></script>
    <script src="~/js/jquery-jqgrid-4.13.2.min.js" asp-append-version="true"></script>
    @await Html.PartialAsync("_ValidationScriptsPartial")
    <script src="~/js/jqgrid-listcrud.js" asp-append-version="true"></script>
 
    <script type="text/javascript">
        var addEditTitle = 'Products';
        var urlAndMethod = '/Products/Products_ListCrud';
 
        // clears all fields before showing a dialog for an add operation.
        function addItem() {
            clearFields();
            resetValidationErrors();
            showHideItem(null);
            $('#productID').attr('disabled'true);
        }
 
        // clears all fields before assigning controls the values that can be updated.
        function editItem(productIDproductNamesupplierIDcategoryIDquantityPerUnitunitPriceunitsInStockunitsOnOrderreorderLeveldiscontinued) {
            clearFields();
            resetValidationErrors();
            showHideItem(productID);
 
            $('#productID').attr('disabled'false);
            $('#productID').val(productID);
            $('#productName').val(productName.replace(/~APOS/g"'").replace(/~QUOT/g'"').replace(/~NEWL/g'\n'));
            $('#supplierID').val(supplierID);
            $('#categoryID').val(categoryID);
            $('#quantityPerUnit').val(quantityPerUnit.replace(/~APOS/g"'").replace(/~QUOT/g'"').replace(/~NEWL/g'\n'));
            $('#unitPrice').val(unitPrice);
            $('#unitsInStock').val(unitsInStock);
            $('#unitsOnOrder').val(unitsOnOrder);
            $('#reorderLevel').val(reorderLevel);
 
            if (discontinued.toLowerCase() == "yes")
                $('#discontinued').prop('checked'true);
            else
                $('#discontinued').prop('checked'false);
 
            return false;
        }
 
        // clears the values of all fields
        function clearFields() {
            $('#productID').val('');
            $('#productName').val('');
            $('#supplierID').val('');
            $('#categoryID').val('');
            $('#quantityPerUnit').val('');
            $('#unitPrice').val('');
            $('#unitsInStock').val('');
            $('#unitsOnOrder').val('');
            $('#reorderLevel').val('');
            $('#discontinued').removeAttr('checked');
        }
 
        // sets up data in json format minus the open and closed {}.
        function getSerializedData() {
            // get id/primary key values.
            var productID = $('#productID').val();
 
            // set a minimum value when id(s)/primary key(s) has no value.
            if (productID == '')
                productID = '-1';
 
            var serializedData =
                "'ProductID':'" + productID + "'," +
                "'ProductName':'" + $('#productName').val().replace(/~APOS/g"'").replace(/~QUOT/g'"').replace(/~NEWL/g'\n').replace(/'/g"\\'") + "'," +
                "'SupplierID':'" + $('#supplierID').val() + "'," +
                "'CategoryID':'" + $('#categoryID').val() + "'," +
                "'QuantityPerUnit':'" + $('#quantityPerUnit').val().replace(/~APOS/g"'").replace(/~QUOT/g'"').replace(/~NEWL/g'\n').replace(/'/g"\\'") + "'," +
                "'UnitPrice':'" + $('#unitPrice').val() + "'," +
                "'UnitsInStock':'" + $('#unitsInStock').val() + "'," +
                "'UnitsOnOrder':'" + $('#unitsOnOrder').val() + "'," +
                "'ReorderLevel':'" + $('#reorderLevel').val() + "'," +
                "'Discontinued':'" + $('#discontinued').is(':checked') + "'";
 
            return serializedData;
        }
 
        // validates data.
        // returns true when all data is valid, otherwise false.
        function isDataValid() {
            var isValid = true;
 
            // get item values that needs to be validated
            var productName = $('#productName').val();
            var quantityPerUnit = $('#quantityPerUnit').val();
            var unitPrice = $('#unitPrice').val();
            var unitsInStock = $('#unitsInStock').val();
            var unitsOnOrder = $('#unitsOnOrder').val();
            var reorderLevel = $('#reorderLevel').val();
 
            // clear all validation messages
            $('#productNameValidation').text('');
            $('#quantityPerUnitValidation').text('');
            $('#unitPriceValidation').text('');
            $('#unitsInStockValidation').text('');
            $('#unitsOnOrderValidation').text('');
            $('#reorderLevelValidation').text('');
 
            // validation
            if (productName == '') { isValid = false; $("#productNameValidation").text('Product Name is required.'); }
            if (productName.length > 40) { isValid = false; $("#productNameValidation").text('Product Name must be 40 characters or less.'); }
            if (quantityPerUnit.length > 20) { isValid = false; $("#quantityPerUnitValidation").text('Quantity Per Unit must be 20 characters or less.'); }
            if (unitPrice != '' && !isDecimal(unitPrice)) { isValid = false; $("#unitPriceValidation").text('Unit Price must be a decimal.'); }
            if (unitPrice != '' && isDecimal(unitPrice) && !isWithinMoneyRange(unitPrice)) { isValid = false; $("#unitPriceValidation").text('Unit Price must be a valid decimal.'); }
            if (unitsInStock != '' && !isNumeric(unitsInStock)) { isValid = false; $("#unitsInStockValidation").text('Units In Stock must be an integer.'); }
            if (unitsInStock != '' && isNumeric(unitsInStock) && !isWithinInt16Range(unitsInStock)) { isValid = false; $("#unitsInStockValidation").text('Units In Stock must be between -32768 and 32767.'); }
            if (unitsOnOrder != '' && !isNumeric(unitsOnOrder)) { isValid = false; $("#unitsOnOrderValidation").text('Units On Order must be an integer.'); }
            if (unitsOnOrder != '' && isNumeric(unitsOnOrder) && !isWithinInt16Range(unitsOnOrder)) { isValid = false; $("#unitsOnOrderValidation").text('Units On Order must be between -32768 and 32767.'); }
            if (reorderLevel != '' && !isNumeric(reorderLevel)) { isValid = false; $("#reorderLevelValidation").text('Reorder Level must be an integer.'); }
            if (reorderLevel != '' && isNumeric(reorderLevel) && !isWithinInt16Range(reorderLevel)) { isValid = false; $("#reorderLevelValidation").text('Reorder Level must be between -32768 and 32767.'); }
 
            if (isValid)
                return true;
            else
                return false;
        }
 
        $(function () {
            // set the initial values for the add or update record dialog.
            InitializeAddUpdateRecordDialog();
 
            $('#list-grid').jqGrid({
                url: '/Products/Products_ListCrud?handler=GridData',
                datatype: 'json',
                mtype: 'GET',
                colNames: ['Product ID','Product Name','Supplier ID','Category ID','Quantity Per Unit','Unit Price','Units In Stock','Units On Order','Reorder Level','Discontinued'''''],
                colModel: [
                    { name: 'ProductID', index: 'ProductID', align: 'right' },
                    { name: 'ProductName', index: 'ProductName', align: 'left' },
                    { name: 'SupplierID', index: 'SupplierID', align: 'right' },
                    { name: 'CategoryID', index: 'CategoryID', align: 'right' },
                    { name: 'QuantityPerUnit', index: 'QuantityPerUnit', align: 'left' },
                    { name: 'UnitPrice', index: 'UnitPrice', align: 'right', formatter: 'currency', formatoptions: { decimalPlaces: 2, prefix: "$"} },
                    { name: 'UnitsInStock', index: 'UnitsInStock', align: 'right', formatter: 'integer' },
                    { name: 'UnitsOnOrder', index: 'UnitsOnOrder', align: 'right', formatter: 'integer' },
                    { name: 'ReorderLevel', index: 'ReorderLevel', align: 'right', formatter: 'integer' },
                    { name: 'Discontinued', index: 'Discontinued', align: 'center', formatter: 'checkbox' },
                    { name: 'editoperation', index: 'editoperation', align: 'center', width: 40, sortable: false, title: false },
                    { name: 'deleteoperation', index: 'deleteoperation', align: 'center', width: 40, sortable: false, title: false }
                ],
                pager: $('#list-pager'),
                rowNum: 10,
                pageable: true,
                jsonReader:
                {
                    page: "d.page"
                },
                rowList: [5, 10, 20, 50],
                sortname: 'ProductID',
                sortorder: "asc",
                viewrecords: true,
                caption: 'List of Products',
                height: '100%',
                width: '1200',
                gridComplete: function () {
                    // get all the ids into an array
                    var ids = $('#list-grid').jqGrid('getDataIDs');
 
                    for (var i = 0; i < ids.length; i++) {
                        // id/primary key
                        var currentid = ids[i];
 
                        // get the field values to be edited/updated
                        var productID = $('#list-grid').jqGrid('getCell', ids[i], 'ProductID');
                        var productName = $('#list-grid').jqGrid('getCell', ids[i], 'ProductName').replace(/'/g'~APOS').replace(/"/g'~QUOT').replace(/\n/g'~NEWL');
                        var supplierID = $('#list-grid').jqGrid('getCell', ids[i], 'SupplierID');
                        var categoryID = $('#list-grid').jqGrid('getCell', ids[i], 'CategoryID');
                        var quantityPerUnit = $('#list-grid').jqGrid('getCell', ids[i], 'QuantityPerUnit').replace(/'/g'~APOS').replace(/"/g'~QUOT').replace(/\n/g'~NEWL');
                        var unitPrice = $('#list-grid').jqGrid('getCell', ids[i], 'UnitPrice');
                        var unitsInStock = $('#list-grid').jqGrid('getCell', ids[i], 'UnitsInStock');
                        var unitsOnOrder = $('#list-grid').jqGrid('getCell', ids[i], 'UnitsOnOrder');
                        var reorderLevel = $('#list-grid').jqGrid('getCell', ids[i], 'ReorderLevel');
                        var discontinued = $('#list-grid').jqGrid('getCell', ids[i], 'Discontinued');
 
                        // edit link (pencil icon)
                        editLink = "<a href='#' onclick=\"editItem('" + productID + "','" + productName + "','" + supplierID + "','" + categoryID + "','" + quantityPerUnit + "','" + unitPrice + "','" + unitsInStock + "','" + unitsOnOrder + "','" + reorderLevel + "','" + discontinued + "')\"><img src='/images/Edit.gif' style='border:none;' /></a>";
 
                        // delete link (trash icon)
                        deleteLink = "<a href='#' onclick=\"deleteItem('" + currentid + "', '/Products/Delete/')\"><img src='/images/Delete.png' style='border:none;' /></a>";
 
                        // assign the editLink to the editoperation located in the jqgrid's colModel
                        $('#list-grid').jqGrid('setRowData', ids[i], { editoperation: editLink });
 
                        // assign the deleteLink to the deleteoperation located in the jqgrid's colModel
                        $('#list-grid').jqGrid('setRowData', ids[i], { deleteoperation: deleteLink });
                    }
                }
            });
        });
 
        // rename the page parameter to _page because asp.net core razor's page model
        // does not recognize the page parameter when passed
        $.extend(jQuery.jgrid.defaults, {
            prmNames: {
                page: "_page"
            }
        });
    </script> 
}
 
<h2>@ViewData["Title"]</h2>
<br /><br />
<div id="addUpdateRecordDialog" title="Add New Products">
    <div>
        <fieldset>
            <legend></legend>
            <table>
                <tr id="trPrimaryKey">
                    <td class="editor-label"><label asp-for="Products.ProductID"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="Products.ProductID" id="productID" readonly="readonly" /></td>
                    <td class="editor-field"></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.ProductName"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="Products.ProductName" id="productName" /></td>
                    <td class="editor-field"><span id="productNameValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.SupplierID"></label>:</td>
                    <td></td>
                    <td class="editor-field"><select id="supplierID" asp-for="Products.SupplierID" asp-items="@(new SelectList(Model.SuppliersDropDownListData, "SupplierID""CompanyName"))"><option value="">Select One</option></select></td>
                    <td class="editor-field"><span id="supplierIDValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.CategoryID"></label>:</td>
                    <td></td>
                    <td class="editor-field"><select id="categoryID" asp-for="Products.CategoryID" asp-items="@(new SelectList(Model.CategoriesDropDownListData, "CategoryID""CategoryName"))"><option value="">Select One</option></select></td>
                    <td class="editor-field"><span id="categoryIDValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.QuantityPerUnit"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="Products.QuantityPerUnit" id="quantityPerUnit" /></td>
                    <td class="editor-field"><span id="quantityPerUnitValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.UnitPrice"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="Products.UnitPrice" id="unitPrice" /></td>
                    <td class="editor-field"><span id="unitPriceValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.UnitsInStockHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="Products.UnitsInStockHidden" id="unitsInStock" /></td>
                    <td class="editor-field"><span id="unitsInStockValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.UnitsOnOrderHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="Products.UnitsOnOrderHidden" id="unitsOnOrder" /></td>
                    <td class="editor-field"><span id="unitsOnOrderValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.ReorderLevelHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="Products.ReorderLevelHidden" id="reorderLevel" /></td>
                    <td class="editor-field"><span id="reorderLevelValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="Products.Discontinued"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="Products.Discontinued" type="checkbox" id="discontinued" /></td>
                    <td class="editor-field"></td>
                </tr>
                <tr>
                    <td colspan="2"></td>
                    <td colspan="2">
                        <br />
                        <input id="inputAdd" name="inputAdd" type="button" value="Add" class="button-150" onclick="addNewItem()" />
                        <input id="inputUpdate" name="inputUpdate" type="button" value="Update" class="button-150" onclick="updateCurrentItem()" />
                        <input type="button" value="Cancel" onclick="closeDialog(); return false;" class="button-100" />
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
</div>
 
<div id="errorConfirmationDialog"></div>
<div id="errorDialog"></div>
 
<a href="#" onclick="addItem()"><img src="@Url.Content("~/images/Add.gif")" alt="Add New Products" style="bordernone;" /></a>&nbsp;<a href="#" onclick="addItem()">Add New Products</a>
<br /><br />
 
<table id="list-grid"></table>
<div id="list-pager"></div>