@model NorthwindAPI.ViewModels.ProductsViewModel
@{
    ViewBag.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/Delete/';
 
        // clears all fields before showing a dialog for an add operation.
        function addItem() {
            clearFields();
            resetValidationErrors();
            showHideItem(null);
            $('#productID').attr('disabled'true);
 
            urlAndMethod = '/Products/ListCrud?inputSubmit=Add';
        }
 
        // clears all fields before assigning controls the values that can be updated.
        function editItem(productID, productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued) {
            clearFields();
            resetValidationErrors();
            showHideItem(productID);
 
            urlAndMethod = '/Products/ListCrud?inputSubmit=Update';
 
            $('#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();
 
            // set jqrid properties
            $('#list-grid').jqGrid({
                url: '/Products/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,
                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 });
                    }
                }
            });
        });
    </script> 
}
 
<h2>@ViewBag.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="ProductsModel.ProductID"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="ProductsModel.ProductID" id="productID" readonly="readonly" /></td>
                    <td class="editor-field"></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.ProductName"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="ProductsModel.ProductName" id="productName" /></td>
                    <td class="editor-field"><span id="productNameValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.SupplierID"></label>:</td>
                    <td></td>
                    <td class="editor-field"><select id="supplierID" asp-for="ProductsModel.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="ProductsModel.CategoryID"></label>:</td>
                    <td></td>
                    <td class="editor-field"><select id="categoryID" asp-for="ProductsModel.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="ProductsModel.QuantityPerUnit"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="ProductsModel.QuantityPerUnit" id="quantityPerUnit" /></td>
                    <td class="editor-field"><span id="quantityPerUnitValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.UnitPrice"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="ProductsModel.UnitPrice" id="unitPrice" /></td>
                    <td class="editor-field"><span id="unitPriceValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.UnitsInStockHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="ProductsModel.UnitsInStockHidden" id="unitsInStock" /></td>
                    <td class="editor-field"><span id="unitsInStockValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.UnitsOnOrderHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="ProductsModel.UnitsOnOrderHidden" id="unitsOnOrder" /></td>
                    <td class="editor-field"><span id="unitsOnOrderValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.ReorderLevelHidden"></label>:</td>
                    <td></td>
                    <td class="editor-field"><input asp-for="ProductsModel.ReorderLevelHidden" id="reorderLevel" /></td>
                    <td class="editor-field"><span id="reorderLevelValidation" style="colorred;"></span></td>
                </tr>
                <tr>
                    <td class="editor-label"><label asp-for="ProductsModel.Discontinued"></label>:</td>
                    <td><span style="colorred;">*</span></td>
                    <td class="editor-field"><input asp-for="ProductsModel.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="saveItem()" />
                        <input id="inputUpdate" name="inputUpdate" type="button" value="Update" class="button-150" onclick="saveItem()" />
                        <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>