<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master"
	AutoEventWireup="true" CodeBehind="Testing.aspx.cs"
	Inherits="GridView_RowsSample.Testing" %>

<%@ Register Assembly="C1.Web.Wijmo.Controls.48"
	Namespace="C1.Web.Wijmo.Controls.C1GridView" TagPrefix="wijmo" %>

<%@ Register Src="~/FaultyControl.ascx" TagName="FaultyControl" TagPrefix="uc2" %>

<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");
			return;

			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
		}

    </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>

			<uc2:FaultyControl ID="FaultyControl1" runat="server" />


		</ContentTemplate>
	</asp:UpdatePanel>



	<asp:UpdatePanel ID="UpdatePanelInPlaceTotalsGrid" runat="server" UpdateMode="Conditional">
		<ContentTemplate>

			<script type="text/javascript">                            

				function InPlaceTotalsGrid_OnClientGroupAggregate(sender, args) {
					var CurrencySymbol = '€';

                    let sum = 0;
                    let grid = $(sender.target);
                    let data = grid.c1gridview('dataView');

                    if (!data) { return; }

                    var totalItems = data.totalItemCount();
                    var startIndex = args.groupingStart;
                    var endIndex = args.groupingEnd;

                    // Clamp indices (equivalente al bucle for del servidor: StartItemIndex → EndItemIndex)
                    if (startIndex < 0) { startIndex = 0; }
                    if (endIndex >= totalItems) { endIndex = totalItems - 1; }

                    for (var i = startIndex; i <= endIndex; i++) {
                        let row = data.item(i);
                        if (!row) { continue; }

                        let amountText = row[args.column.dataIndex];
                        if (amountText) {
                            sum += typeof value === "string" ? parseLocaleNumber(amountText) : amountText;
                        }
                    }

					// Format c0: integer, locale es-ES (without decimal places)
					// Equivalente a string.Format("{0:C}", sum) con cultura es-ES
					let formattedSum = sum.toLocaleString('es-ES', {
						minimumFractionDigits: 0,
						maximumFractionDigits: 0
					});

					args.text = CurrencySymbol +
						"<span style='max-width:85px;display:inline-block;overflow:hidden'>" + formattedSum + "</span>";
				}
            </script>

			<wijmo:C1GridView ID="InPlaceTotalsGrid" runat="server"
				AllowPaging="false"
				AutogenerateColumns="False"
				DataKeyNames="ID"
				Width="100%"
				callbackoptions="All"
				OnDataBound="InPlaceTotalsGrid_DataBound"
				OnClientGroupAggregate="InPlaceTotalsGrid_OnClientGroupAggregate">
				<Columns>
					<wijmo:C1TemplateField Visible="false">
						<GroupInfo FooterText="Total" Position="Footer" GroupSingleRow="True">
							<%--                                    <FooterStyle Width="0px" BackColor="#0050A6" ForeColor="White" Font-Bold="True" />
                                    <HeaderStyle BackColor="#0050A6" />--%>
						</GroupInfo>
						<ItemStyle Width="0px" />
					</wijmo:C1TemplateField>
					<wijmo:C1BoundField DataField="DESCRIPTION"
						HeaderText="&nbsp;">
						<ItemStyle CssClass="GridText" />
					</wijmo:C1BoundField>
					<wijmo:C1BoundField
						DataField="AMOUNT"
						HeaderText="&nbsp;"
						DataFormatString="c0"
						NullDisplayText="0,00"
						Aggregate="Custom">
						<ItemStyle CssClass="GridNumber" />
					</wijmo:C1BoundField>
				</Columns>
			</wijmo:C1GridView>
		</ContentTemplate>
	</asp:UpdatePanel>







</asp:Content>
