<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="GridView_RowsSample._Default" %>
<%@ Register Assembly="C1.Web.Wijmo.Controls.48" 
    Namespace="C1.Web.Wijmo.Controls.C1GridView" TagPrefix="wijmo" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <script>
        var grid;

        // Register once, handles all future partial postbacks
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
            ReadRows();
        });

        function ReadRows() {
            console.log("ReadRows called");

            grid = $("#<%=C1GridView1.ClientID%>");

            if (!grid || grid.length === 0) {
                console.log("ReadRows: grid not found");
                return;
            }

            let dataView = null;
            try {
                dataView = grid.c1gridview('dataView');
            } catch (e) {
                console.error("ReadRows: c1gridview not initialized yet — " + e.message);
                document.getElementById("statusLabel").innerText =
                    "ERROR (postback): " + e.message;
                return;
            }

            const numRows = dataView.totalItemCount();
            console.log("ReadRows: numRows = " + numRows);
            document.getElementById("statusLabel").innerText =
                "ReadRows OK — rows: " + numRows;
        }

        // ---- Replicates search button client click handler ----
        function OnBtnSearchClick() {
            console.log("Search clicked — postback starting");
            // let the postback proceed naturally
        }

        // ---- Your existing test functions below ----
        function GetGridRows() {
            grid = "#<%=C1GridView1.ClientID%>";
            var numRows = $(grid).c1gridview('dataView').totalItemCount();
            alert('rows count is ' + numRows);
        }

        function TestRowIteration() {
            var grid = "#<%=C1GridView1.ClientID%>";
            var numRows = $(grid).c1gridview('dataView').totalItemCount();
            for (var i = 0; i < numRows; i++) {
                var rowEl = $(grid).find('tr.wijmo-wijgrid-row').eq(i)[0];
                var dataItem = $(grid).c1gridview('dataView').item(i);
                var rowKey = dataItem[0];
                var cell1 = $(rowEl).find('td.wijgridtd').eq(1)[0];
                cell1.setAttribute('style', 'cursor:pointer; background:yellow');
                var cellText = $(cell1).find('.wijmo-wijgrid-innercell').text();
                console.log('key:', rowKey, '| cell[1]:', cellText);
                var tripJson = rowEl.getAttribute('trip');
                var trip = JSON.parse(tripJson);
                console.log('key:', rowKey, '| trip:', trip);
            }
        }

        function TestCheckboxAccess() {
            var grid = "#<%=C1GridView1.ClientID%>";
            var numRows = $(grid).c1gridview('dataView').totalItemCount();
            for (var i = 0; i < numRows; i++) {
                var rowEl = $(grid).find('tr.wijmo-wijgrid-row').eq(i)[0];
                var dataItem = $(grid).c1gridview('dataView').item(i);
                var rowKey = dataItem[0];
                var checkboxEl = $(rowEl).find('input[type="checkbox"]').first()[0];
                if (checkboxEl) {
                    console.log('row key:', rowKey, '| checkbox id:', checkboxEl.id,
                        '| checked:', checkboxEl.checked);
                    checkboxEl.onkeydown = (function (key) {
                        return function (event) {
                            if (event.keyCode === 13) {
                                console.log('Enter pressed on row key:', key);
                                return false;
                            }
                        };
                    })(rowKey);
                } else {
                    console.warn('No checkbox found in row', i);
                }
            }
            alert('Checkbox access test complete — check browser console.');
        }
    </script>

    <%-- Status display --%>
    <div style="margin-bottom:10px; padding:8px; background:#f0f0f0; font-weight:bold;">
        ReadRows status: <span id="statusLabel">not yet run</span>
    </div>

    <%-- Buttons outside UpdatePanel (manual JS calls — always work) --%>
    <button type="button" class="btn btn-primary" onclick="GetGridRows()">Get Grid Rows Count</button>
    <button type="button" class="btn btn-secondary" onclick="TestRowIteration()">Test Row Iteration</button>
    <button type="button" class="btn btn-primary" onclick="TestCheckboxAccess()">Test Checkbox Access</button>
    <hr />

    <%-- UpdatePanel — replicates Enrique's structure --%>
    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" />

    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>

          <div style="margin-bottom:8px;">
      <asp:TextBox ID="TextBoxFilter" runat="server" placeholder="Filter name..." />
      <asp:Button ID="btnSearch" runat="server" Text="Search (Partial Postback)"
          CssClass="btn btn-warning"
          OnClick="btnSearch_Click"
          OnClientClick="OnBtnSearchClick();" />
  </div>

        </ContentTemplate>
    </asp:UpdatePanel>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
          
            <wijmo:C1GridView ID="C1GridView1" runat="server"
                OnRowDataBound="C1GridView1_RowDataBound"
                AllowClientEditing="true">
            </wijmo:C1GridView>

        </ContentTemplate>
    </asp:UpdatePanel>


</asp:Content>
