<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="eDocument.Server.Administrator.edoc_designer.Index" MasterPageFile="~/Site.Master" %>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
	<!-- content you want in the head -->
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">

    <script>
        //Redirect to new designer page
        if (typeof window !== 'undefined') {
            const newDesignerUrl = "<%= ResolveUrl("~") %>page/designer";
            const url = new URL(location.href);
            const testParam = url.searchParams.get('test');

            //Redirect if testparameter is not set.
            if(testParam !== 'OldFormsOverview') location.href = newDesignerUrl;
        }
    </script>


    <div id="divNoLicense" runat="server" style="border: 2px; border-style: solid; border-color: red">
        OBS: organisasjonen har ikke lisens for bruk av designer.
    </div>

    <!--Du har tilgang på følgende variable:<br/>
    InstallUrl, hentes fra config: <%= InstallUrl %><br/>
    EdocVersion: <%= EdocVersion %><br/>
    CustomerUsername: <%= CustomerUsername %><br/>
    ID:    <%= CurrentAdministratorId %>
    ApiUrl: <%= ApiUrl %><br/>-->

    <div class="skjema-admin__designer" id="root" runat="server">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <h1 class="skjema-admin__designer__title skjema-admin__mb-20">Velg skjema</h1>

					<!-- Header -->
                    <div class="d-flex justify-content-between align-items-center skjema-admin__mb-20">
                        <div class="skjema-admin__table-search-input-container" >
                            <!-- Search-icon -->
							<span class="icon-search">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M15.755 14.256h-.79l-.28-.27a6.471 6.471 0 0 0 1.57-4.23 6.5 6.5 0 1 0-6.5 6.5c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99 1.49-1.49-4.99-5zm-6 0c-2.49 0-4.5-2.01-4.5-4.5s2.01-4.5 4.5-4.5 4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5z" fill="#000" fill-opacity=".6"/>
                                </svg>
							</span>

							<!-- Search-field -->
                            <input 
								id="designer-form-overview-search-input"
								class="skjema-admin__table-search-input" 
								style="width: unset; border: none;" 
								type="text" 
								data-jscomponent="tableFilter" 
								placeholder="Søk i skjema" 
							/>

							<!-- Clear-button -->
                            <button
								id="designer-form-overview-clear-search-button"
								class="skjema-admin__table-search-clear-button" 
								type="button" 
								data-jscomponent="tableFilterClear" 
								style="border: none; background-color: transparent; visibility:hidden;"
							>
                                <span 
									class="budicon budicon-cross-ui" 
									style="top: 5px; font-size: 24px; position: relative;"
								></span>
                            </button>
                        </div>

						<!-- Clear-search-button script -->
                        <script defer>
                            const clearButton = document.querySelector('#designer-form-overview-clear-search-button');
                            const inputField = document.querySelector('#designer-form-overview-search-input');

                            inputField.addEventListener('input', () => {
                                if (inputField.value) clearButton.style.visibility = 'visible';
                                else clearButton.style.visibility = 'hidden';
                            });
                        </script>

						<!-- Header-buttons -->
                        <div class="skjema-admin__header_buttons">

                            <%--Help button--%>
                            <%-- Help button is disabled since it does not have any functionality yet.
                            <button 
                                class="skjema-admin__designer__search-button" 
                                type="button" 
                                onclick="window.open('./usermanualdesigner.aspx');"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48">
                                    <g>
                                        <path d="M431-330q1-72 16.5-105t58.5-72q42-38 64.5-70.5T593-647q0-45-30-75t-84-30q-52 0-80 29.5T358-661l-84-37q22-59 74.5-100.5T479-840q100 0 154 55.5T687-651q0 48-20.5 87T601-482q-49 47-59 72t-11 80H431Zm48 250q-29 0-49.5-20.5T409-150q0-29 20.5-49.5T479-220q29 0 49.5 20.5T549-150q0 29-20.5 49.5T479-80Z" />
                                    </g>
                                </svg>
                            </button>

                            --%>

                            <%--Create-form button--%>
                            <button 
                                class="skjema-admin__designer__button skjema-admin__designer__button--primary" 
                                type="button" 
                                data-jsid="createFormButton"
                            >
                                Opprett nytt skjema
                            </button>
                        </div>
                    </div>

					<%--Forms-count--%>
					<div id="formsCountContainer" class="skjema-admin__mb-50">
						Viser 
						<span id="formsCount" style="counter-reset: variable var(--formsCount, 0); content: counter(variable);"></span>
						skjema<span id="plural" class="d-none">er</span> 
						<span id="linkClearFilter" data-jscomponent="tableFilterClear" style="text-decoration: underline; cursor: pointer;" class="d-none">
							Nullstill søk
						</span>
					</div>
				   

					<%--SUPER-ADMIN SECTION--%>
					<% if(IsSuperAdmin) 
					{ %>
						<div class="skjema-admin__forSuperAdmin">
							<%--Filters--%>
							<div class="forSuperAdmin_filters">

								<%--Filter-headline--%>
								<h3 id="forSuperAdmin">
									For SuperAdmin:
								</h3>

								<%--Filter-selector--%>
								<asp:RadioButtonList ID="rblFilterTable" runat="server" AutoPostBack="True" OnSelectedIndexChanged="rbl_SelectedIndexChanged">
									<asp:ListItem Value="all" Selected="True">Alle</asp:ListItem>
									<asp:ListItem Value="customer">Kunde</asp:ListItem>
									<asp:ListItem Value="superAdmin">SuperAdmin</asp:ListItem>
								</asp:RadioButtonList>
							</div>
					
                            <div id="for_super_admin_options" class="superAdminOptions">
							    <asp:HiddenField ID="hiddenCount" runat="server" Value="0" />
							    <asp:Label ID="lblChoosen" runat="server" Text="" class="selected_count" />

							    <%--Dropdown-actions--%>
							    <asp:DropDownList 
                                    ID="ddlGiveAccess" 
                                    runat="server" 
                                    class="forSuperAdmin_dropdown"  
                                    onchange="handleAdminLockCheckbox(this)"
                                    style="min-width:200px;"
                                >
								    <asp:ListItem Value="">Velg handling</asp:ListItem>
								    <asp:ListItem Value=false>Vis for kunde</asp:ListItem>
								    <asp:ListItem Value=true>Skjul fra kunde</asp:ListItem>
							    </asp:DropDownList>
                            </div>
						</div>
					<% } %>

					<%--FORMS TABLE--%>
                    <table 
                        class="
                            skjema-admin__designer__table 
                            skjema-admin__table__sort-icon-2 
                            skjema-admin__table__sort-icon-3
                            skjema-admin__table__sort-icon-4 
                            skjema-admin__table__sort-icon-5
                            skjema-admin__table__sort-icon-6
                            skjema-admin__table__sort-icon-7
                            jsFilterTable
                        "
                        data-jsid="tableOfFormsDesigner"
                    >
                        <%--Table-header--%>
                        <thead>
                            <tr>
                                <% if (IsSuperAdmin)
                                   { %>
                                    <th>
                                        <input type="checkbox" id="checkAll" />
                                    </th>
                                <% } %>
                                <th>ID</th>
                                <th></th>
                                <th>Tittel</th>
                                <th>Status</th>
                                <th>Sist endret</th>
                                <!--th>Endret av</!--th>
                                <th>Aktivert av</th-->
                                <th aria-label="Lås status"></th>
                                <th aria-label="Menyer"></th>
                            </tr>
                        </thead>

                        <%--Table-body--%>
                        <tbody>
                            <asp:Repeater ID="repTemplate" runat="server">
                                <ItemTemplate>
                                    <tr 
                                        data-templateid="<%# Eval("ID") %>" 
                                        data-formid="<%# Eval("Formid") %>" 
                                        data-title="<%# Eval("Title") %>" 
                                        data-status="<%# Eval("status") %>" 
                                        data-shared="<%# Eval("Visibility") %>" 
                                        data-version="<%# Eval("Version") %>" 
                                        data-islocked="<%# Eval("IsLockedByCurrentUser") %>" 
                                        <%# Eval("IsLockedByCurrentUser").ToString().ToLower() == "true" ? "style='background-color:#fb75752b;'" : "" %> 
                                        data-createdraft="<%# Eval("CreateDraft") %>" 
                                        data-isFromCatalog="<%# Eval("IsFromCatalog") %>" 
                                        <%# Eval("IsFromCatalog").ToString() == "True" ? "style='background-color:#33FFF5;'" : "" %>
                                        data-islockedbysuperadmin="<%# Eval("IsLockedBySuperAdmin").ToString().ToLower() %>"
                                        <%# Eval("IsLockedBySuperAdmin").ToString().ToLower() == "true" ? "title='Låst av admin. SSP'" : "" %>
                                    >

                                        <%--Super-admin checkbox--%>
                                        <% if (IsSuperAdmin)
                                            { %>
                                            <td>
                                                <asp:CheckBox ID="CheckBox1" runat="server" onclick="updateCount()" />
                                            </td>
                                        <% } %>

                                        <%--Form-id--%>
                                        <td data-jsid="<%# Eval("RowAction") %>"><%# Eval("Formid") %></td>
                                       
                                        <%--Designer-origin--%>
                                        <%-- %>
                                        <%# Eval("IsMaintainedInWebDesigner").ToString().ToLower() == "false" 
                                                ? "<td data-jsid=\"convertToWebDesigner\" style=\"padding-inline:0;width:35px;\"><span class='font-italic font-weight-bold'>edoc</span></td>" 
                                                : "<td data-jsid=\"openFormInDesigner\">&nbsp;</td>" 
                                        %>
                                        --%>

                                        <td data-jsid="convertToWebDesigner" style="padding-inline:0;width:35px;">
                                            <span class='font-italic font-weight-bold'>
                                                <%# Eval("IsMaintainedInWebDesigner").ToString().ToLower() == "false" ? "edoc" : "" %>
                                            </span>
                                        </td>


                                        <%--Form-title--%>
                                        <td data-jsid="<%# Eval("RowAction") %>"><%# Eval("Title") %></td>
                                        
                                        <%--Form-status--%>
                                        <td data-jsid="<%# Eval("RowAction") %>">
                                            <div class="d-flex align-items-center position-relative">
                                                <div class="skjema-admin__designer__status-circle  <%# Eval("Status").ToString() == "Aktiv" ? "skjema-admin__designer__status-circle--active":"" %> <%# Eval("Status").ToString() == "Endret" ? "skjema-admin__designer__status-circle--changed":"" %> <%# Eval("Status").ToString() == "Inaktiv" ? "skjema-admin__designer__status-circle--inactive":"" %> skjema-admin__mr-10"></div>
                                                <span id="<%# Eval("ID") %>_status-text" class="font-italic" aria-describedby="<%# Eval("ID") %>_tooltip-status" tabindex="0" data-jsid="versionStatusText"><%# Eval("Status") %></span>
                                                <div id="<%# Eval("ID") %>_tooltip-status" class="skjema-admin__designer__tooltip d-none" aria-hidden="true">Versjon <%# Eval("Version")%> <%# Eval("LastChangedBy") != null ? "- sist endret av " + Eval("LastChangedBy") : ""%><%# Eval("ActivatedBy") != null ? " og aktivert av " + Eval("ActivatedBy") : ""%><%# Eval("IsLockedBySuperAdmin").ToString() != "False" ? "<br>Låst av admin. (SSP)" : "" %></div>
                                            </div>
                                        </td>
                                        
                                        <%--Last changed--%>
                                        <td data-jsid="<%# Eval("RowAction") %>"><%# Eval("LastChanged") %></td>
                                        
                                        <%-- Lock-icon --%>
                                        <td class="locked_by_admin" data-jsid="<%# Eval("RowAction") %>" >
                                            <span style="display:none;" data-type="sort-element">"<%# Eval("IsLockedBySuperAdmin").ToString().ToLower() %>"</span>
                                            <span data-type="hover-element"></span>
                                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path 
                                                    d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6zm9 14H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"
                                                    fill="#000"
                                                    fill-opacity=".6"
                                                />
                                            </svg>
                                        </td>
                                        
                                        <%--Action-menu--%>
                                        <td>
                                            <button class="skjema-admin__designer__more" type="button" data-jsid="toggleMoreMenu">
                                                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="21" viewBox="0 0 20 21">
                                                    <defs>
                                                        <path id="ya10eox7ka_<%# Eval("Formid") %>" d="M5 8.333c-.917 0-1.667.75-1.667 1.667s.75 1.667 1.667 1.667 1.667-.75 1.667-1.667S5.917 8.333 5 8.333zm10 0c-.917 0-1.667.75-1.667 1.667s.75 1.667 1.667 1.667 1.667-.75 1.667-1.667-.75-1.667-1.667-1.667zm-5 0c-.917 0-1.667.75-1.667 1.667s.75 1.667 1.667 1.667 1.667-.75 1.667-1.667-.75-1.667-1.667-1.667z" />
                                                    </defs>
                                                    <g fill="none" fill-rule="evenodd">
                                                        <g>
                                                            <g>
                                                                <g>
                                                                    <g transform="translate(-1123.000000, -812.000000) translate(271.000000, 801.500000) translate(847.000000, 6.000000) translate(5.000000, 5.000000)">
                                                                        <mask id="wslnul3f6b_<%# Eval("Formid") %>" fill="#fff">
                                                                            <use xlink:href="#ya10eox7ka_<%# Eval("Formid") %>" />
                                                                        </mask>
                                                                        <g fill="#000" mask="url(#wslnul3f6b_<%# Eval("Formid") %>)">
                                                                            <path d="M0 0H41.667V41.667H0z" transform="translate(-10.833333, -10.833333)" />
                                                                        </g>top
                                                                    </g>
                                                                </g>
                                                            </g>
                                                        </g>
                                                    </g>
                                                </svg>
                                            </button>

                                            <%-- Action-menu-content --%>
                                            <div class="skjema-admin__designer__popup-menu d-none" data-jsid="moreMenu">
                                                
                                                <%--Make-copy button--%>
                                                <button class="skjema-admin__designer__popup-choice" type="button" data-jsid="copyFormButton">
                                                    Lag kopi
                                                </button>

                                                <%--Get-versions button--%>
                                                <button class="skjema-admin__designer__popup-choice" type="button" data-jsid="versionsFormButton">
                                                    Hent tidligere versjon
                                                </button>

                                                <%--Share button--%>
                                                <button runat="server" visible="<%# IsSharingEnabledForCustomer %>" class="skjema-admin__designer__popup-choice" type="button" data-jsid="shareFormButton">
                                                    <%# Eval("shareMenuText") %>
                                                </button>

                                                <%--Unlock user-lock button--%>
                                                <%# Eval("IsLockedByCurrentUser").ToString() == "True" 
													? "<button class='skjema-admin__designer__popup-choice' type='button' data-jsid='unlockFormButton' >Lås opp</button>" 
													: "" 
                                                %>

                                                <%--Delete button--%>
                                                <button
                                                    class="skjema-admin__designer__popup-choice"
                                                    type="button"
                                                    data-jsid="deleteFormButton"
                                                    data-version="<%# Eval("Version") %>"
                                                >
                                                    Slett
                                                </button>

												<span runat="server" visible="<%# IsSuperAdmin %>" style="display: flex;" >
													<hr style="border: solid 1px lightgray; width: 25%" />
													<p style="font-size: 12px; color: lightgray; padding: 0 4px; white-space: nowrap;">Super-Admin</p>
													<hr style="border: solid 1px lightgray; width: 25%" />
												</span>

												<%--Super-admin-lock button--%>
                                                <button
													runat="server" 
                                                    class='skjema-admin__designer__popup-choice' 
													visible='<%# !Convert.ToBoolean(Eval("IsFromCatalog")) && IsSuperAdmin %>'
                                                    type='button' 
                                                    data-jsid='setAccessButton'
                                                    data-islocked='<%# Eval("IsLockedBySuperAdmin").ToString().ToLower() %>'
                                                    onclick="handleAdminLockButton(this)"
                                                >
                                                    <%# Eval("IsLockedBySuperAdmin").ToString().ToLower() == "true" 
														? "Vis for kunde" 
														: "Skjul fra kunde" 
                                                    %>
                                                </button>

												<button 
													runat="server" 
													visible=<%# Convert.ToBoolean(Eval("IsFromCatalog")) %> 
													class='skjema-admin__designer__popup-choice' 
													type='button' 
													data-jsid='moveFormButton'
												>
                                                    Flytt til kunde
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </ItemTemplate>
                            </asp:Repeater>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

	<!-- Create-template form popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="createFormMenu">
        <div class="skjema-admin__designer__modal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk</span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30">Opprett nytt skjema
            </h2>

            <div class="skjema-admin__mb-20">
                <label class="skjema-admin__designer__modal-label" for="createFormTitleInput">Tittel *</label>
                <input id="createFormTitleInput" class="skjema-admin__designer__modal-input" type="text" placeholder="Tittel" data-jsid="createFormTitle" />
                <div class="d-flex align-items-center">
                    <div class="skjema-admin__designer__input-error d-none" data-jsid="createFormTitleErrorMessage">
                        Du må fylle inn tittel.
                    </div>
                </div>
            </div>

            <div class="skjema-admin__mb-20">
                <div>
                    <label class="skjema-admin__designer__modal-label" for="createFormIdInput">ID *</label>
                    <input id="createFormIdInput" class="skjema-admin__designer__modal-input" type="text" placeholder="ID" data-jsid="createFormId" />
                </div>
                <div>
                    <div class="d-flex align-items-center">
                        <div class="skjema-admin__designer__input-error d-none" data-jsid="createFormIdErrorMessage">
                            Du må fylle inn ID.
                        </div>
                    </div>
                </div>
            </div>

            <div class="skjema-admin__mb-20">
                <div data-jsid="createFormCategorySelectContent">
                    <div class="d-flex align-items-center">
                        <div>
                            <label class="skjema-admin__designer__modal-label" for="formCategorySelect">
                                Kategori *
                            </label>
                            <select id="formCategorySelect" class="skjema-admin__designer__modal-select skjema-admin__designer__modal-select--short skjema-admin__mr-10" data-jsid="createFormCategoriesSelect">
                                <option value="">- - -</option>
                            </select>

                            <div class="text-left">
                                <div class="skjema-admin__designer__input-error d-none" data-jsid="createFormCategoryErrorMessage">
                                    Du må velge kategori
                                </div>
                            </div>

                            <div class="skjema-admin__designer__modal-input__helper-text" data-jsid="createFormCanChangeAdminHelperText">
                                Kan endres i administrator
                            </div>
                        </div>

                        <div>
                            <button class="skjema-admin__designer__plus-button" type="button" data-jsid="createFormToggleCreateCategory">
                                + Opprett kategori
                            </button>
                        </div>
                    </div>
                </div>

                <div class="d-none" data-jsid="createFormCategoryAddContent">
                    <div class="d-flex justify-content-between">
                        <div>
                            <label class="skjema-admin__designer__modal-label" for="createFormCategoryInput">
                                Navn på ny kategori
                            </label>
                            <input id="createFormCategoryInput" class="skjema-admin__designer__modal-input skjema-admin__designer__modal-input--half skjema-admin__mr-10" type="text" data-jsid="createFormCategoryInput" placeholder="Kategori" />
                            <div class="skjema-admin__designer__modal-input__helper-text">
                                Kan endres i administrator
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center" style="width: 170px; padding-top: 3px;">
                            <button class="skjema-admin__designer__button skjema-admin__designer__button--max-height skjema-admin__designer__button--small skjema-admin__designer__button--secondary" type="button" data-jsid="createFormCancelCategoryAdd">
                                Avbryt
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="skjema-admin__mb-30 d-flex">
                <div>
                    <div>
                        <label class="skjema-admin__designer__modal-label" for="createFormSecuritySelect">Sikkerhetsnivå *</label>
                    </div>
                    <select id="createFormSecuritySelect" class="skjema-admin__designer__modal-select" data-jsid="createFormSecurityLevelSelect">
                        <option value="0">Ikke krev pålogging
                        </option>

                        <option value="1">Pålogging med Feide
                        </option>

                        <option value="3">Pålogging med MinID
                        </option>

                        <option value="4">Pålogging med BankID/Buypass
                        </option>
                    </select>
                    <div class="skjema-admin__designer__modal-input__helper-text">
                        Kan endres i administrator
                    </div>
                </div>
            </div>

            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="createNewFormSubmit">
                Opprett skjema
            </button>
        </div>
    </div>


	<!-- Copy-template form popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="createCopyFormMenu">
        <div class="skjema-admin__designer__modal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk</span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30">Lag kopi
            </h2>

            <div class="skjema-admin__mb-20">
                <label class="skjema-admin__designer__modal-label" for="copyFormTitleInput">Tittel *</label>
                <input id="copyFormTitleInput" class="skjema-admin__designer__modal-input" type="text" placeholder="Tittel" data-jsid="copyFormTitle" />
                <div class="d-flex align-items-center">
                    <div class="skjema-admin__designer__input-error d-none" data-jsid="copyFormTitleErrorMessage">
                        Du må fylle inn tittel.
                    </div>
                </div>
            </div>

            <div class="skjema-admin__mb-20">
                <div>
                    <label class="skjema-admin__designer__modal-label" for="copyFormIdInput">ID *</label>
                    <input id="copyFormIdInput" class="skjema-admin__designer__modal-input" type="text" placeholder="ID" data-jsid="copyFormId" />
                </div>
                <div>
                    <div class="d-flex align-items-center">
                        <div class="skjema-admin__designer__input-error d-none" data-jsid="copyFormIdErrorMessage">
                            Du må fylle inn ID.
                        </div>
                    </div>
                </div>
            </div>

            <div class="skjema-admin__mb-20">
                <div data-jsid="copyFormCategorySelectContent">
                    <div class="d-flex align-items-center">
                        <div>
                            <label class="skjema-admin__designer__modal-label" for="formCategorySelect">
                                Kategori *
                            </label>
                            <select id="copyFormCategorySelect" class="skjema-admin__designer__modal-select skjema-admin__designer__modal-select--short skjema-admin__mr-10" data-jsid="copyFormCategoriesSelect">
                                <option value="">- - -</option>
                            </select>

                            <div class="text-left">
                                <div class="skjema-admin__designer__input-error d-none" data-jsid="copyFormCategoryErrorMessage">
                                    Du må velge kategori
                                </div>
                            </div>

                            <div class="skjema-admin__designer__modal-input__helper-text" data-jsid="copyFormCanChangeAdminHelperText">
                                Kan endres i administrator
                            </div>
                        </div>

                        <div>
                            <button class="skjema-admin__designer__plus-button" type="button" data-jsid="copyFormToggleCreateCategory">
                                + Opprett kategori
                            </button>
                        </div>
                    </div>
                </div>

                <div class="d-none" data-jsid="copyFormCategoryAddContent">
                    <div class="d-flex justify-content-between">
                        <div>
                            <label class="skjema-admin__designer__modal-label" for="copyFormCategoryInput">
                                Navn på ny kategori
                            </label>
                            <input id="copyFormCategoryInput" class="skjema-admin__designer__modal-input skjema-admin__designer__modal-input--half skjema-admin__mr-10" type="text" data-jsid="copyFormCategoryInput" placeholder="Kategori" />
                            <div class="skjema-admin__designer__modal-input__helper-text">
                                Kan endres i administrator
                            </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center" style="width: 170px; padding-top: 3px;">
                            <button class="skjema-admin__designer__button skjema-admin__designer__button--max-height skjema-admin__designer__button--small skjema-admin__designer__button--secondary" type="button" data-jsid="copyFormCancelCategoryAdd">
                                Avbryt
                            </button>
                        </div>
                    </div>
                </div>

                <div class="skjema-admin__mb-30 d-flex">
                    <div>
                        <div>
                            <label class="skjema-admin__designer__modal-label" for="copyFormSecuritySelect">Sikkerhetsnivå *</label>
                        </div>
                        <select id="copyFormSecuritySelect" class="skjema-admin__designer__modal-select" data-jsid="copyFormSecurityLevelSelect">
                            <option value="0">Ikke krev pålogging
                            </option>

                            <option value="1">Pålogging med Feide
                            </option>

                            <option value="3">Pålogging med MinID
                            </option>

                            <option value="4">Pålogging med BankID/Buypass
                            </option>
                        </select>
                        <div class="skjema-admin__designer__modal-input__helper-text">
                            Kan endres i administrator
                        </div>
                    </div>
                </div>
            </div>


            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="copyFormSubmit">
                Opprett kopi av skjema
            </button>
        </div>
    </div>

	<!-- Delete-template confirmation popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="deleteFormMenu">
        <div class="skjema-admin__designer__modal" data-jsid="deleteFormModal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk
                </span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30" data-jsid="deleteModalTitle">Er du sikker på at du vil slette?
            </h2>

            <div class="skjema-admin__mb-40 skjema-admin__designer__popup-text">
                <span class="font-italic" data-jsid="deleteTitle"></span>
                <span data-jsid="deleteDescription">vil ikke kunne gjennopprettes.
                </span>
            </div>

            <button class="skjema-admin__designer__button mr-4" type="button" data-jsid="closeFormMenuCross">
                Avbryt
            </button>

            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="deleteDeleteFormSubmit">
                Slett
            </button>
        </div>
    </div>


	<!-- Convert-template popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="convertFormMenu">
        <div class="skjema-admin__designer__modal" data-jsid="convertFormModal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk
                </span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30" data-jsid="convertModalTitle">Skjemaet er klar for konvertering
            </h2>

            <div class="skjema-admin__mb-40 skjema-admin__designer__popup-text" >
                <span class="font-italic" data-jsid="convertTitle"></span>
                <span data-jsid="convertDescription" style="text-align:left;">Skjemaet <span class="skjema-admin__designer__italic" data-jsid="convertFormMenuText"></span>kan konverteres og vedlikeholdes i webdesigner.
                </span>
            </div>
            <div class="skjema-admin__designer__input-error mt-3 d-none" data-jsid="convertFormErrorMessage">
            </div>

            <button class="skjema-admin__designer__button mr-4" type="button" data-jsid="closeFormMenuCross">
                Avbryt
            </button>

            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="convertFormSubmit">
                Konverter
            </button>

        </div>
    </div>


	<!-- Version-selector popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="versionsModal">
        <div class="skjema-admin__designer__modal skjema-admin__designer__modal--wide">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk</span>
            </button>

            <div class="pl-5 pr-5">
                <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30">Versjoner
                </h2>

                <div class="skjema-admin__mb-30" data-jsid="versionTitle">
                </div>

                <table class="skjema-admin__designer__table skjema-admin__designer__table--modal" data-jsid="versionTable">
                    <thead>
                        <tr>
                            <th>Versjon
                            </th>

                            <th>Sist endret
                            </th>

                            <th>Sist endret av
                            </th>

                            <th>Aktivert av
                            </th>

                            <th>Kommentar
                            </th>

                            <th></th>
                        </tr>
                    </thead>

                    <tbody data-jsid="versionsTbody">
                    </tbody>
                </table>

            </div>
        </div>
    </div>

	<!-- Template-already-in-use error popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="designerInEditModal">
        <div class="skjema-admin__designer__modal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk</span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30">Skjemaet redigeres av en annen person</h2>

            <div class="skjema-admin__designer__modal__content">
                <div class="skjema-admin__mb-20">
                    Skjemaet <span class="skjema-admin__designer__italic" data-jsid="designerInEditModalText"></span>redigeres av <a href="#" data-jsid="designerInEditModalMail"></a>.
                </div>

                <div class="skjema-admin__mb-30">
                    Et skjema kan ikke redigeres av mer enn én person samtidig.
                </div>
            </div>

            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="closeFormMenuCross">
                Ok
            </button>
        </div>
    </div>


	<!-- Wrong-text error popup -->
    <div class="skjema-admin__designer__underlay d-none" data-jsid="errorModalMessage">
        <div class="skjema-admin__designer__modal">
            <button class="skjema-admin__designer__popup-close skjema-admin__designer__cross-icon-filled" type="button" data-jsid="closeFormMenuCross">
                <span class="d-none">Lukk</span>
            </button>

            <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-30" data-jsid="errorModalMessageTitle">Feil
            </h2>

            <div class="skjema-admin__mb-30">
                <div data-jsid="errorModalMessageText">
                    Feil Tekst her
                </div>
            </div>

            <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="closeFormMenuCross">
                Ok
            </button>
        </div>
    </div>


    <%-- ***** SCRIPTS ***** --%>
    <script>
        const regexAllowTitle = /^[a-zA-Z\d\s\æøåÆØÅ.,\/()\-é–]$/;
        const regexReplaceTitle = /[^a-zA-Z0-9æøåÆØÅ., \/()\-é–]/gi;
        const regexAllowFormId = /^[a-zA-Z\d\-_]$/;
        const regexReplaceFormId = /[^a-zA-Z0-9\-_]/gi;

        const table = document.querySelector("[data-jsid='tableOfFormsDesigner']");

        var createFormTitle = document.querySelector("[data-jsid='createFormTitle']");
        createFormTitle.addEventListener("keypress", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        createFormTitle.addEventListener("beforeinput", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        createFormTitle.addEventListener("paste", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        createFormTitle.addEventListener("change", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);

        var createFormId = document.querySelector("[data-jsid='createFormId']");
        createFormId.addEventListener("keypress", (event) => { allowedCharacters(event, regexAllowFormId, regexReplaceFormId) }, false);
        createFormId.addEventListener("beforeinput", (event) => { allowedCharacters(event, regexAllowId, regexReplaceTitle) }, false);
        createFormId.addEventListener("paste", (event) => { allowedCharacters(event, regexAllowFormId, regexReplaceFormId) }, false);

        var copyFormTitle = document.querySelector("[data-jsid='copyFormTitle']");
        copyFormTitle.addEventListener("keypress", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        copyFormTitle.addEventListener("beforeinput", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        copyFormTitle.addEventListener("paste", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);
        copyFormTitle.addEventListener("change", (event) => { allowedCharacters(event, regexAllowTitle, regexReplaceTitle) }, false);

        var copyFormId = document.querySelector("[data-jsid='copyFormId']");
        copyFormId.addEventListener("keypress", (event) => { allowedCharacters(event, regexAllowFormId, regexReplaceFormId) }, false);
        copyFormId.addEventListener("beforeinput", (event) => { allowedCharacters(event, regexAllowId, regexReplaceTitle) }, false);
        copyFormId.addEventListener("paste", (event) => { allowedCharacters(event, regexAllowFormId, regexReplaceFormId) }, false);
        copyFormId.addEventListener("change", (event) => { allowedCharacters(event, regexAllowId, regexReplaceTitle) }, false);

        function allowedCharacters(event, regexAllow, regexReplace) {
            if (event.type == "paste") {

                let clipboardData = event.clipboardData || window.clipboardData;
                let pastedData = clipboardData.getData('Text');

                var desired = pastedData.replace(regexReplace, '');

                event.preventDefault();
                if (document.queryCommandSupported('insertText')) {
                    document.execCommand('insertText', false, desired);
                }
                else {
                    document.execCommand('paste', false, desired);
                }
            } else if (event.type == "beforeinput" || event.type == "change") {
                if (event.data != null && !regexAllow.test(event.data)) { //added ekstra check because of bug in safari (mac)
                    event.preventDefault();
                }
            } else {

                var key = event.key;
                if (!regexAllow.test(key)) {
                    event.preventDefault();
                }
            }

        }



        /**
         * Event for handling toggling admin-lock via checkboxes
         * @param {HTMLSelectElement} target The triggered select-element
         * @returns {void}
         */
        function handleAdminLockCheckbox(target = {}) {
            const isLocking = target.value === 'true';
            const checkboxes = table?.querySelectorAll('input[type="checkbox"]');
            const selectedRows = [];

            checkboxes?.forEach?.((checkbox) => {
                if(checkbox.checked) {
                    const row = checkbox.closest('tr');
                    selectedRows.push(row);
                }
            });

            if(selectedRows.length) toggleAdminLock(selectedRows, isLocking);
            target.selectedIndex = 0;
        }


        /**
         * Event for handling toggling admin-lock via menu-button
         * @param {HTMLButtonElement} target The clicked button-element
         * @returns {void}
         */
        function handleAdminLockButton(target = {}) {
            const row = target.closest('tr');
            if (!row) return;
            const isLocking = row.dataset.islockedbysuperadmin === 'false';
            target.innerHTML = isLocking ? "Vis for kunde" : "Skjul fra kunde";
            toggleAdminLock([row], isLocking);
        }


        /**
         * Function for toggling admin-lock.
         * @param {HTMLTableRowElement[]} rows Array of table-rows to manipulate
         * @return {void}
         */
        function toggleAdminLock(rows, isLocking) {

            if(!rows?.length) return;
            rows.forEach((row) => {
      
                const formId = row.getAttribute("data-formid");
                row.dataset.islockedbysuperadmin = isLocking;
                row.setAttribute('title', isLocking ? 'Låst av admin. (SSP)' : '');
                const tooltipText = `<br>Låst av admin. (SSP)`

                const tooltip = row.querySelector(".skjema-admin__designer__tooltip");
                const existingTooltipText = tooltip?.innerHTML || '';
                tooltip.innerHTML = isLocking
                    ? existingTooltipText + tooltipText
                    : existingTooltipText.replace(tooltipText, '');

                try {
                    admin.setAdminAccess(
                        "<%= ApiUrl %>",
                        "<%= CustomerUsername %>",
                        formId,
                        isLocking,
                        () => {},
                        (errorText) => displayError("Feil ved opplåsing av skjema: ", errorText),
                    );
                } catch (error) {
                    console.error('Error during API call:', error);
                }
            });
        }


        document.addEventListener("DOMContentLoaded", function () {
            var SkjemaAdmin = admin;
            var root = document.documentElement;
            root.style.setProperty("--global-bg-color", "#f4f7fb");

            var table = document.querySelector("[data-jsid='tableOfFormsDesigner']");
            var cleanTable = (function () {
                return table.cloneNode(true);
            })();
            var cleanTbody = (function () {
                var tableClone = table.cloneNode(true);
                return tableClone.querySelector("tbody").cloneNode(true);
            })();

            window.cloneTest = cleanTbody;

            var apiUrl = "<%= ApiUrl %>/<%= CustomerUsername %>/designer";

            var createFormButton = document.querySelector("[data-jsid='createFormButton']");
            var createFormMenu = document.querySelector("[data-jsid='createFormMenu']");
            var closeFormMenuesCross = document.querySelectorAll("[data-jsid='closeFormMenuCross']");
            var createNewFormSubmit = document.querySelector("[data-jsid='createNewFormSubmit']");
            var createFormTitle = document.querySelector("[data-jsid='createFormTitle']");
            var createFormId = document.querySelector("[data-jsid='createFormId']");
            var createFormIdErrorMessage = document.querySelector("[data-jsid='createFormIdErrorMessage']");
            var createFormTitleErrorMessage = document.querySelector("[data-jsid='createFormTitleErrorMessage']");
            var createFormCategoriesSelect = document.querySelector("[data-jsid='createFormCategoriesSelect']");
            var createFormCategoryErrorMessage = document.querySelector("[data-jsid='createFormCategoryErrorMessage']");
            var createFormCanChangeAdminHelperText = document.querySelector("[data-jsid='createFormCanChangeAdminHelperText']");
            var createFormSecurityLevelSelect = document.querySelector("[data-jsid='createFormSecurityLevelSelect']");
            var createFormCategoryInput = document.querySelector("[data-jsid='createFormCategoryInput']");
            var createFormToggleCreateCategory = document.querySelector("[data-jsid='createFormToggleCreateCategory']");
            var createFormCategoryAddContent = document.querySelector("[data-jsid='createFormCategoryAddContent']");
            var createFormCategorySelectContent = document.querySelector("[data-jsid='createFormCategorySelectContent']");
            var createFormCancelCategoryAdd = document.querySelector("[data-jsid='createFormCancelCategoryAdd']");

            var copyFormModal = document.querySelector("[data-jsid='createCopyFormMenu']");
            var copyFormTitle = document.querySelector("[data-jsid='copyFormTitle']");
            var copyFormId = document.querySelector("[data-jsid='copyFormId']");
            var copyFormSubmit = document.querySelector("[data-jsid='copyFormSubmit']");
            var copyFormIdErrorMessage = document.querySelector("[data-jsid='copyFormIdErrorMessage']");
            var copyFormTitleErrorMessage = document.querySelector("[data-jsid='copyFormTitleErrorMessage']");
            var copyFormCategoriesSelect = document.querySelector("[data-jsid='copyFormCategoriesSelect']");
            var copyFormToggleCreateCategory = document.querySelector("[data-jsid='copyFormToggleCreateCategory']");
            var copyFormCategoryErrorMessage = document.querySelector("[data-jsid='copyFormCategoryErrorMessage']");
            var copyFormCanChangeAdminHelperText = document.querySelector("[data-jsid='copyFormCanChangeAdminHelperText']");
            var copyFormSecurityLevelSelect = document.querySelector("[data-jsid='copyFormSecurityLevelSelect']");
            var copyFormCategoryInput = document.querySelector("[data-jsid='copyFormCategoryInput']");
            var copyFormToggleCreateCategory = document.querySelector("[data-jsid='copyFormToggleCreateCategory']");
            var copyFormCategoryAddContent = document.querySelector("[data-jsid='copyFormCategoryAddContent']");
            var copyFormCategorySelectContent = document.querySelector("[data-jsid='copyFormCategorySelectContent']");
            var copyFormCancelCategoryAdd = document.querySelector("[data-jsid='copyFormCancelCategoryAdd']");

            var deleteFormMenu = document.querySelector("[data-jsid='deleteFormMenu']");
            var deleteFormSubmit = document.querySelector("[data-jsid='deleteDeleteFormSubmit']");
            var deleteTitle = document.querySelector("[data-jsid='deleteTitle']");

            var convertFormModal = document.querySelector("[data-jsid='convertFormModal']");
            var convertFormMenu = document.querySelector("[data-jsid='convertFormMenu']");
            var convertFormSubmit = document.querySelector("[data-jsid='convertFormSubmit']");
            var convertModalTitle = document.querySelector("[data-jsid='convertModalTitle']");
            var convertDescription = document.querySelector("[data-jsid='convertDescription']");
            var convertFormErrorMessage = document.querySelector("[data-jsid='convertFormErrorMessage']");

            var errorFormModal = document.querySelector("[data-jsid='errorModalMessage']");
            var errorFormModalTitle = document.querySelector("[data-jsid='errorModalMessageTitle']");
            var errorFormModalText = document.querySelector("[data-jsid='errorModalMessageText']");

            var designerInUseModal = document.querySelector("[data-jsid='designerInEditModal']");
            var designerInUseModalText = document.querySelector("[data-jsid='designerInEditModalText']");
            var designerInUseModalMail = document.querySelector("[data-jsid='designerInEditModalMail']");

            var formFilter = document.querySelector("[data-jsid='formFilter']");
            var formFilterSubmit = document.querySelector("[data-jsid='formFilterSubmit']");

            var versionsModal = document.querySelector("[data-jsid='versionsModal']");
            var versionsTbody = document.querySelector("[data-jsid='versionsTbody']");
            var versionTable = document.querySelector("[data-jsid='versionTable']");
            var versionTitle = document.querySelector("[data-jsid='versionTitle']");

            function displayError(title, message) {
                errorFormModal.classList.remove("d-none");
                errorFormModalTitle.innerHTML = title;
                errorFormModalText.innerHTML = message;
            }

            var versionStatusTexts = Array.from(document.querySelectorAll("[data-jsid='versionStatusText']"));

            var isCreateFormValid = function () {
                var isValid = true;

                if (createFormCategoriesSelect.value.trim().length === 0) {
                    createFormCategoryErrorMessage.classList.remove("d-none");
                    createFormCanChangeAdminHelperText.classList.add("d-none");
                    isValid = false;
                } else {
                    createFormCategoryErrorMessage.classList.add("d-none");
                    createFormCanChangeAdminHelperText.classList.remove("d-none");
                }
                if (createFormId.value.trim().length === 0) {
                    createFormIdErrorMessage.classList.remove("d-none");
                    isValid = false;
                } else {
                    createFormIdErrorMessage.classList.add("d-none");
                }
                if (createFormTitle.value.trim().length === 0) {
                    createFormTitleErrorMessage.classList.remove("d-none");
                    isValid = false;
                } else {
                    createFormTitleErrorMessage.classList.add("d-none");
                }

                return isValid;
            };

            var isCopyFormValid = function () {
                var isValid = true;

                if (copyFormCategoriesSelect.value.trim().length === 0) {
                    copyFormCategoryErrorMessage.classList.remove("d-none");
                    copyFormCanChangeAdminHelperText.classList.add("d-none");
                    isValid = false;
                } else {
                    copyFormCategoryErrorMessage.classList.add("d-none");
                    copyFormCanChangeAdminHelperText.classList.remove("d-none");
                }
                if (copyFormId.value.trim().length === 0) {
                    copyFormIdErrorMessage.classList.remove("d-none");
                    isValid = false;
                } else {
                    copyFormIdErrorMessage.classList.add("d-none");
                }
                if (copyFormTitle.value.trim().length === 0) {
                    copyFormTitleErrorMessage.classList.remove("d-none");
                    isValid = false;
                } else {
                    copyFormTitleErrorMessage.classList.add("d-none");
                }

                return isValid;
            };

            var addEventListeners = function (table) {
                if (table) {
                    Array.from(table.querySelectorAll("[data-jsid='toggleMoreMenu']")).forEach(function (toggleElement) {
                        toggleElement.addEventListener("click", function (event) {
                            var contextMenu = event.currentTarget.nextElementSibling;
                            // Close all other menues
                            const menues = document.querySelectorAll("[data-jsid='moreMenu']");
                            menues.forEach((menu) => {
                                menu.classList.add("d-none");
                                menu.closest("tr").classList.remove("skjema-admin__designer__table__marked-row");
                            });

                            contextMenu.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");
                            if (contextMenu.classList.contains("d-none")) {
                                tr.classList.remove("skjema-admin__designer__table__marked-row");
                            } else {
                                tr.classList.add("skjema-admin__designer__table__marked-row");
                                const outsideClickListener = (event) => {
                                    const outsideClick = event.target.contains(contextMenu) && event.target !== contextMenu;// !contextMenu.contains(event.target);
                                    if (outsideClick) {
                                        contextMenu.classList.add("d-none");
                                        tr.classList.remove("skjema-admin__designer__table__marked-row");
                                        document.removeEventListener('click', outsideClickListener);
                                    }
                                }
                                document.addEventListener('click', outsideClickListener, true);
                            }
                        });
                    });

                    Array.from(table.querySelectorAll("[data-jsid='closeMoreMenu']")).forEach(function (closeElement) {
                        closeElement.addEventListener("click", function (event) {
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");
                            var contextMenu = event.currentTarget.closest("[data-jsid='moreMenu']");

                            if (contextMenu.classList.contains("d-none")) {
                                tr.classList.remove("skjema-admin__designer__table__marked-row"); copyFormButton
                            } else {
                                tr.classList.add("skjema-admin__designer__table__marked-row");
                            }
                        });
                    });

                    // Copy form
                    Array.from(table.querySelectorAll("[data-jsid='copyFormButton']")).forEach(function (toggleElement) {
                        toggleElement.addEventListener("click", function (event) {
                            copyFormModal.classList.toggle("d-none");
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");
                            copyFormSubmit.setAttribute("data-id", tr.getAttribute("data-formid"));
                        });
                    });

                    // Move form
                    Array.from(table.querySelectorAll("[data-jsid='moveFormButton']")).forEach(function (toggleElement) {
                        toggleElement.addEventListener("click", function (event) {
                            /*    moveFormModal.classList.toggle("d-none");*/
                            var tr = event.currentTarget.closest("tr");
                            var formId = tr.getAttribute("data-formid");
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            SkjemaAdmin.getMoveDesignerForm(" <%= ApiUrl %>",
                                "<%= CustomerUsername %>",
                                formId,
                                //moveFormCategoriesSelect.value,
                                //moveFormSecurityLevelSelect.value,
                                '','',
                                function (templateId) {
                                    //let designerUrl = `designer.aspx?id=${templateId}&createDraft=true`;
                                    //window.open(designerUrl);
                                    setTimeout(function () {
                                        location.reload();
                                    }, 1000);
                                }, function (status, statusText, resText) {
                                    var parsedText = JSON.parse(resText);
                                    displayError("Feil ved flytting av skjema ", parsedText);
                                });
                        });
                    });

                    //Version
                    Array.from(table.querySelectorAll("[data-jsid='versionsFormButton']")).forEach(function (toggleElement) {
                        toggleElement.addEventListener("click", function (event) {
                            versionsModal.classList.toggle("d-none");
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");

                            var versionFormId = tr.getAttribute("data-formid");
                            var versionFormTitle = tr.getAttribute("data-title");
                            const templateID = tr.getAttribute("data-templateid");

                            SkjemaAdmin.getVersions("<%= ApiUrl %>","<%= CustomerUsername %>", versionFormId, function (data) {
                                var frag = SkjemaAdmin.getVersionsTbody(templateID, data);

                                versionsTbody.innerHTML = "";
                                versionsTbody.appendChild(frag);
                                versionTitle.innerHTML = versionFormId + " " + versionFormTitle;
                            }, function (status, statusText, resText) {
                                displayError("Feil ved henting av versjon: ", resText);
                            });
                        });
                    });

                    //Share
                    Array.from(table.querySelectorAll("[data-jsid='shareFormButton']")).forEach(function (shareElement) {
                        shareElement.addEventListener("click", function (event) {
                            //event.currentTarget.parentElement.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");
                            tr.classList.remove("skjema-admin__designer__table__marked-row");

                            var formId = tr.getAttribute("data-formid");
                            const isShared = tr.getAttribute("data-shared") == "0" ? true : false;

                            SkjemaAdmin.setShareForm("<%= ApiUrl %>", "<%= CustomerUsername %>", formId, isShared, function () {
                                shareElement.innerHTML = isShared == false ? "Del skjema" : "Stopp deling";
                                tr.dataset.shared = isShared ? 2 : 0;
                                //setTimeout(function () {
                                //    location.reload();
                                //}, 1000);
                            }, function (status, statusText, resText) {
                                displayError("Feil ved deling av skjema: ", resText);
                            });
                        });
                    });

                    //Delete
                    Array.from(table.querySelectorAll("[data-jsid='deleteFormButton']")).forEach(function (closeElement) {
                        closeElement.addEventListener("click", function (event) {
                            var tr = event.currentTarget.closest("tr");
                            var version = event.currentTarget.getAttribute("data-version");
                            var title = tr.getAttribute("data-title");
                            var modalTitle = deleteFormMenu.querySelector("[data-jsid='deleteModalTitle']");
                            var modalDeleteDescription = deleteFormMenu.querySelector("[data-jsid='deleteDescription']");
                            var deleteFormModal = deleteFormMenu.querySelector("[data-jsid='deleteFormModal']");

                            modalTitle.innerHTML = "Er du sikker på at du vil slette?";
                            modalDeleteDescription.innerHTML = "vil ikke kunne gjennopprettes.";
                            deleteTitle.innerHTML = tr.getAttribute("data-formid") + " " + tr.getAttribute("data-title");
                            deleteFormModal.removeAttribute("style");

                            deleteFormMenu.classList.toggle("d-none");
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            deleteFormSubmit.setAttribute("data-id", tr.getAttribute("data-formid"));
                        });
                    });

                    //Unlock
                    Array.from(table.querySelectorAll("[data-jsid='unlockFormButton']")).forEach(function (unlockElement) {
                        unlockElement.addEventListener("click", function (event) {
                            event.currentTarget.parentElement.classList.toggle("d-none");
                            var tr = event.currentTarget.closest("tr");
                            var formId = tr.getAttribute("data-formid");
                            SkjemaAdmin.setUnlockDesignerForm("<%= ApiUrl %>", "<%= CustomerUsername %>", formId, function () {
                                setTimeout(function () {
                                    location.reload();
                                }, 1000);
                            }, function (status, statusText, resText) {
                                displayError("Feil ved opplåsing av skjema: ", resText);
                            });
                        });
                    });


                    //Convert to web designer convertToWebDesigner
                    Array.from(table.querySelectorAll("[data-jsid='convertToWebDesigner']")).forEach(function (openconvertToWebDesigner) {
                        openconvertToWebDesigner.addEventListener("click", function (event) {
                            event.preventDefault();
                            var tr = event.currentTarget.closest("tr");
                            var formTitle = tr.getAttribute("data-title");
                            var formId = tr.getAttribute("data-formid");
                            convertFormSubmit.setAttribute("data-templateid", tr.getAttribute("data-templateid"));
                            convertFormSubmit.setAttribute("data-id", formId);
                            convertFormSubmit.setAttribute("data-version", tr.getAttribute("data-version"));
                            SkjemaAdmin.getCheckIfFormIsConvertible("<%= ApiUrl %>", "<%= CustomerUsername %>", formId, function (data) {
                                if (data.isSuccess) {
                                    // Om skjema kan konverteres
                                    convertModalTitle.innerHTML = 'Skjema kan konverteres';
                                    convertFormSubmit.classList.remove("d-none");

                                    var changeList = '<br/><p>' + data.changes.reduce((html, item) => {
                                        return html + "" + item + "<br/><br/>";
                                    }, "") + '</p>';

                                    convertDescription.innerHTML = `Skjemaet <span class="skjema-admin__designer__italic" data-jsid="convertFormMenuText">"${formTitle}"</span> kan konverteres og vedlikeholdes i webdesigner.<br/>`;
                                    convertDescription.innerHTML += changeList.replace('.:', ':<br/>');

                                } else {
                                    // hvis ikke
                                    convertModalTitle.innerHTML = 'Skjema kan ikke konverteres';
                                    var errorList = '<br/>' + data.errors.reduce((html, item) => {
                                        return html + "" + item + "<br/><br/>";
                                    }, "") + '</p>';
                                    convertFormSubmit.classList.add("d-none");
                                    convertDescription.innerHTML = `Skjemaet <span class="skjema-admin__designer__italic" data-jsid="convertFormMenuText">${formTitle}</span> inneholder funksonalitet som ikke støttes av denne versjonen av designer og kan ikke konverteres.<br/>`;
                                    convertDescription.innerHTML += errorList;
                                }
                                convertFormMenu.classList.toggle("d-none");
                            });
                        });
                    });

                    //Open designer
                    Array.from(table.querySelectorAll("[data-jsid='openFormInDesigner']")).forEach(function (openDesignerAnchor) {
                        openDesignerAnchor.addEventListener("click", function (e) {
                            e.preventDefault();

                            var tr = e.currentTarget.closest("tr");
                            var templateid = tr.getAttribute("data-templateid");
                            var formId = tr.getAttribute("data-formid");
                            var formTitle = tr.getAttribute("data-title");
                            var formStatus = tr.getAttribute("data-status");
                            var createDraft = tr.getAttribute("data-createDraft").toString().toLowerCase();
                            var version = tr.getAttribute("data-version");
                            var adminLock = tr.getAttribute("data-islockedbysuperadmin");

                            SkjemaAdmin.getIsFormInEditMode("<%= ApiUrl %>", "<%= CustomerUsername %>", formId, function (data) {
                                var currentAdminId = "<%= CurrentAdministratorId %>";

                                if (data.id === null || data.id === "<%= CurrentAdministratorId %>") {
                                    let designerUrl = `designer.aspx?id=${templateid}&createDraft=${createDraft}&version=${version}`;
                                    window.open(designerUrl);
                                } else {
                                    designerInUseModalText.innerHTML = "«" + formId + " " + formTitle + "»";
                                    designerInUseModalMail.innerHTML = data.displayName;
                                    designerInUseModalMail.href = "mailto:" + data.email;

                                    designerInUseModal.classList.remove("d-none");
                                }
                            }, function (status, statusText, resText) {
                                //displayError("Feil ved åpning av designer: ", resText);
                                var redirectUrl = "<%=ForbiddenUrl%>";
                                window.location.href = redirectUrl;
                            });
                        });
                    });

                    versionStatusTexts.forEach(function (statusTextElement) {

                        var displayToolTip = function (toggleOn) {
                            var statusTextId = statusTextElement.getAttribute("aria-describedby");
                            var toolTipElement = document.getElementById(statusTextId);

                            if (toggleOn) {
                                toolTipElement.classList.remove("d-none");
                                toolTipElement.setAttribute("aria-hidden", "false");
                            } else {
                                toolTipElement.classList.add("d-none");
                                toolTipElement.setAttribute("aria-hidden", "true");
                            }
                        }

                        statusTextElement.addEventListener("focus", function () {
                            displayToolTip(true);
                        });

                        statusTextElement.addEventListener("blur", function () {
                            displayToolTip(false);
                        });

                        statusTextElement.addEventListener("mouseover", function () {
                            displayToolTip(true);
                        });

                        statusTextElement.addEventListener("mouseout", function () {
                            displayToolTip(false);
                        });
                    });
                }

                if (createFormToggleCreateCategory && createFormCategorySelectContent) {
                    createFormToggleCreateCategory.addEventListener("click", function () {
                        createFormCategoryAddContent.classList.remove("d-none");
                        createFormCategorySelectContent.classList.add("d-none");
                    });
                }
                if (copyFormToggleCreateCategory && copyFormCategorySelectContent) {
                    copyFormToggleCreateCategory.addEventListener("click", function () {
                        copyFormCategoryAddContent.classList.remove("d-none");
                        copyFormCategorySelectContent.classList.add("d-none");
                    });
                }

                if (createFormCancelCategoryAdd) {
                    createFormCancelCategoryAdd.addEventListener("click", function () {
                        createFormCategoryAddContent.classList.add("d-none");
                        createFormCategorySelectContent.classList.remove("d-none");
                        createFormCategoryInput.value = "";
                    });
                }
                if (copyFormCancelCategoryAdd) {
                    copyFormCancelCategoryAdd.addEventListener("click", function () {
                        copyFormCategoryAddContent.classList.add("d-none");
                        copyFormCategorySelectContent.classList.remove("d-none");
                        copyFormCategoryInput.value = "";
                    });
                }

                if (createFormCancelCategoryAdd) {
                    createFormCancelCategoryAdd.addEventListener("click", function () {
                        createFormCategoryAddContent.classList.add("d-none");
                        createFormCategorySelectContent.classList.remove("d-none");
                        createFormCategoryInput.value = "";
                    });
                }
                if (copyFormCancelCategoryAdd) {
                    copyFormCancelCategoryAdd.addEventListener("click", function () {
                        copyFormCategoryAddContent.classList.add("d-none");
                        copyFormCategorySelectContent.classList.remove("d-none");
                        copyFormCategoryInput.value = "";
                    });
                }
            }

            if (createFormCategoriesSelect) {
                SkjemaAdmin.getCategories(apiUrl, function (categories) {
                    var frag = document.createDocumentFragment();
                    categories.forEach(function (category) {
                        var option = document.createElement("option");
                        option.value = category.eDocumentTemplateCategoryID;
                        option.innerHTML = category.name;

                        frag.appendChild(option);
                    });

                    createFormCategoriesSelect.appendChild(frag);
                });
            }
            if (copyFormCategoriesSelect) {
                SkjemaAdmin.getCategories(apiUrl, function (categories) {
                    var frag = document.createDocumentFragment();
                    categories.forEach(function (category) {
                        var option = document.createElement("option");
                        option.value = category.eDocumentTemplateCategoryID;
                        option.innerHTML = category.name;

                        frag.appendChild(option);
                    });

                    copyFormCategoriesSelect.appendChild(frag);
                });
            }

            if (createFormButton && createFormMenu && closeFormMenuesCross && createNewFormSubmit && deleteFormSubmit && copyFormSubmit && versionTable) {
                createFormButton.addEventListener("click", function () {
                    createFormMenu.classList.remove("d-none");
                });

                Array.from(closeFormMenuesCross).forEach(function (closeButton) {
                    closeButton.addEventListener("click", function (event) {
                        closeButton.parentElement.parentElement.classList.add("d-none");
                    });
                });



                createFormId.addEventListener("keyup", function () {
                    if (createFormId.value.trim().length === 0) {
                        createFormIdErrorMessage.classList.remove("d-none");
                    }
                    else {
                        createFormIdErrorMessage.classList.add("d-none");
                    }
                });
                copyFormId.addEventListener("keyup", function () {
                    if (copyFormId.value.trim().length === 0) {
                        copyFormIdErrorMessage.classList.remove("d-none");
                    }
                    else {
                        copyFormIdErrorMessage.classList.add("d-none");
                    }
                });

                createFormTitle.addEventListener("keyup", function () {
                    if (createFormTitle.value.trim().length === 0) {
                        createFormTitleErrorMessage.classList.remove("d-none");
                    }
                    else {
                        createFormTitleErrorMessage.classList.add("d-none");
                    }
                });
                copyFormTitle.addEventListener("keyup", function () {
                    if (copyFormTitle.value.trim().length === 0) {
                        copyFormTitleErrorMessage.classList.remove("d-none");
                    }
                    else {
                        copyFormTitleErrorMessage.classList.add("d-none");
                    }
                });

                createFormCategoriesSelect.addEventListener("change", function () {
                    if (createFormCategoriesSelect.value.trim().length === 0) {
                        createFormCategoryErrorMessage.classList.remove("d-none");
                        createFormCanChangeAdminHelperText.classList.add("d-none");
                    }
                    else {
                        createFormCategoryErrorMessage.classList.add("d-none");
                        createFormCanChangeAdminHelperText.classList.remove("d-none");
                    }
                });
                copyFormCategoriesSelect.addEventListener("change", function () {
                    if (copyFormCategoriesSelect.value.trim().length === 0) {
                        copyFormCategoryErrorMessage.classList.remove("d-none");
                        copyFormCanChangeAdminHelperText.classList.add("d-none");
                    }
                    else {
                        copyFormCategoryErrorMessage.classList.add("d-none");
                        copyFormCanChangeAdminHelperText.classList.remove("d-none");
                    }
                });

                createNewFormSubmit.addEventListener("click", function () {

                    var option = document.createElement("option");
                    option.value = createFormCategoryInput.value.trim();
                    option.innerHTML = createFormCategoryInput.value.trim();

                    if (option.value != "") {
                        var hasValue = Array.from(createFormCategoriesSelect.children).some(function (option) {
                            return option.value === createFormCategoryInput.value.trim();
                        });

                        if (!hasValue) {
                            createFormCategoriesSelect.appendChild(option);
                            createFormCategoryInput.value = "";
                        }

                        createFormCategoriesSelect.value = option.value;
                    }

                    if (!isCreateFormValid(true)) {
                        return;
                    }

                    SkjemaAdmin.getCreateDesignerForm(apiUrl,
                        createFormId.value,
                        createFormTitle.value,
                        createFormCategoriesSelect.value,
                        createFormSecurityLevelSelect.value,
                        function (status, statusText, resText) {
                            var parsedText = JSON.parse(resText);
                            displayError("Duplikat", parsedText.errorMessage);
                        },
                        function (createdData) {
                            setTimeout(function () {
                                createFormMenu.classList.add("d-none");
                                var createdUrl = location.protocol + "//" + location.host + location.pathname.toLowerCase().replace("index.aspx", "designer.aspx") + "?" + "id=" + createdData.eDocumentTemplateID + "&createDraft=False" + "&version=0";
                                window.open(createdUrl);
                                location.reload();
                            }, 1000);
                        }
                    );
                });

                deleteFormSubmit.addEventListener("click", function () {
                    deleteFormMenu.classList.toggle("d-none");
                    var formId = deleteFormSubmit.getAttribute("data-id");

                    SkjemaAdmin.getDeleteDesignerFormVersion(

						" <%= ApiUrl %>","<%= CustomerUsername %>",
                        formId,
                        () => setTimeout(() => location.reload(), 1000),
                        (status, statusText, resText) => displayError("Feil ved sletting av skjema", resText));
                });

                copyFormSubmit.addEventListener("click", function () {
                    var oldFormId = copyFormSubmit.getAttribute("data-id");

                    var option = document.createElement("option");
                    option.value = copyFormCategoryInput.value.trim();
                    option.innerHTML = copyFormCategoryInput.value.trim();

                    if (option.value != "") {
                        var hasValue = Array.from(copyFormCategoriesSelect.children).some(function (option) {
                            return option.value === copyFormCategoryInput.value.trim();
                        });

                        if (!hasValue) {
                            copyFormCategoriesSelect.appendChild(option);
                            copyFormCategoryInput.value = "";
                        }

                        copyFormCategoriesSelect.value = option.value;
                    }

                    if (!isCopyFormValid(true)) {
                        return;
                    }

                    SkjemaAdmin.getCopyDesignerForm(" <%= ApiUrl %>",
                        "<%= CustomerUsername %>", oldFormId, copyFormId.value,
                        copyFormTitle.value,
                        copyFormCategoriesSelect.value,
                        copyFormSecurityLevelSelect.value,
                        function (templateId) {
                            let designerUrl = `designer.aspx?id=${templateId}&createDraft=true`;
                            window.open(designerUrl);
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }, function (status, statusText, resText) {
                            var parsedText = JSON.parse(resText);
                            displayError("Feil ved kopiering av skjema ", parsedText);
                        });

                });

                convertFormSubmit.addEventListener("click", function () {
                    var formId = convertFormSubmit.getAttribute("data-id");
                    var templateid = convertFormSubmit.getAttribute("data-templateid");
                    var version = convertFormSubmit.getAttribute("data-version") == null ? 0 : convertFormSubmit.getAttribute("data-version");
                    if (formId.trim().length > 0) {
                        convertFormErrorMessage.classList.add("d-none");
                        convertFormModal.classList.toggle("d-none");
                        SkjemaAdmin.getConvertDesignerForm(" <%= ApiUrl %>", "<%= CustomerUsername %>", formId, function (data) {
                                let designerUrl = `designer.aspx?id=${templateid}&createDraft=false&version=${version}`;
                                window.open(designerUrl);
                                setTimeout(function () {
                                    location.reload();
                                }, 1000);
                            }, function (status, statusText, resText) {
                                displayError("Feil ved konvertering av skjema: ", resText);
                            });
                        } else {
                            convertFormErrorMessage.classList.remove("d-none");
                        }
                    });

                versionTable.addEventListener("click", function (event) {
                    if (event.target.getAttribute("data-jsid") === "getFormVersionButton") {
                        const version = event.target.getAttribute("data-version");
                        const templateId = event.target.getAttribute("data-templateId");
                        let designerUrl = `designer.aspx?id=${templateId}&createDraft=true&version=${version}`;
                        window.open(designerUrl);
                        document.location.reload();
                    }
                });
            }

            //Setup for jQuery Table-sorter
            $("[data-jsid='tableOfFormsDesigner']").tablesorter({
                headers: {
                    0: { sorter: false },
                    1: { sorter: "text" },
                    2: { sorter: "digit", empty: "sort" },
                    5: { sorter: "shortDate", dateFormat: "ddmmyyyy" },
                    7: { sorter: false },
                }
            });

            var clearFilterInput = document.querySelectorAll("[data-jscomponent=tableFilterClear]");

            for (let i = 0; i < clearFilterInput.length; i++) {
                clearFilterInput[i].addEventListener("click", function () {
                    const tableFilterInput = document.querySelector('input[data-jscomponent=tableFilter]')
                    tableFilterInput.value = '';
                    const rows = Array.from(table.querySelectorAll("tr"));
                    rows.slice(1).forEach((row) => row.classList.remove("d-none"));

                    document.getElementById('formsCount').innerText = (rows.length - 1).toString();

                    if ((rows.length - 1) == 1) {
                        document.getElementById("plural").classList.add("d-none");
                    } else {
                        document.getElementById("plural").classList.remove("d-none");
                    }
                    document.getElementById('linkClearFilter').classList.add("d-none");
                });
            }

            addEventListeners(table);

            // Change active in starttab
            Array.from(document.querySelectorAll(".skjema-admin__start-bar__anchor")).forEach(function (link) {
                link.classList.remove("skjema-admin__start-bar__anchor--active");
                if (link.innerHTML.indexOf("Designer") !== -1) {
                    link.classList.add("skjema-admin__start-bar__anchor--active");
                }
            });

            document.getElementById('formsCount').innerText = (Array.from(table.querySelectorAll("tr")).length - 1).toString();

        });


        /**
         * Function for counting number of checked checkboxes, and displaying the result.
         * @return {void}
         */
        function updateCount() {
            //Get elements
            const superAdminSection = document.querySelector('#for_super_admin_options');
            const checkboxes = document.querySelectorAll('input[name^="ctl00$MainContent$repTemplate$ctl"][type="checkbox"]');
            const hiddencountInput = document.querySelector('#<%= hiddenCount.ClientID %>');
            const countTextElement = document.querySelector('#<%= lblChoosen.ClientID %>');

            //Count number of checked checkboxes
            let count = 0;
            checkboxes.forEach((checkbox) => {
                if (checkbox.checked) count++;
            });

            //Make text to display
            const display = count ? 'flex' : 'none';
            let formWord = 'skjemaer';
            if (count === 1) formWord = 'skjema';
            let countText = `${count} ${formWord} valgt`;
            if (!count) countText = '';

            //Update input and text
            hiddencountInput.value = count;
            countTextElement.innerText = countText;
            superAdminSection.style.display = display;
        }


        /**
         * Function for counting number of checked checkboxes, and displaying the result.
         * @return {void}
         */
        function updateCount() {
            //Get elements
            const superAdminSection = document.querySelector('#for_super_admin_options');
            const checkboxes = document.querySelectorAll('input[name^="ctl00$MainContent$repTemplate$ctl"][type="checkbox"]');
            const hiddencountInput = document.querySelector('#<%= hiddenCount.ClientID %>');
            const countTextElement = document.querySelector('#<%= lblChoosen.ClientID %>');

            //Count number of checked checkboxes
            let count = 0;
            checkboxes.forEach((checkbox) => {
                if (checkbox.checked) count++;
            });

            //Make text to display
            const display = count ? 'flex' : 'none';

            let formWord = 'skjemaer';
            if (count === 1) formWord = 'skjema';
            let countText = `${count} ${formWord} valgt`;
            if (!count) countText = '';

            //Update input and text
            hiddencountInput.value = count;
            countTextElement.innerText = countText;
            superAdminSection.style.display = display;
        }

        window.onload = function () {
			const clientElement = document.getElementById('<%= ddlGiveAccess.ClientID %>');
			if(clientElement) clientElement.selectedIndex = 0;

            document.getElementById('checkAll').addEventListener('change', function () {
                var checkboxes = document.querySelectorAll('input[name^="ctl00$MainContent$repTemplate$ctl"][type="checkbox"]');
                for (var i = 0; i < checkboxes.length; i++) {
                    checkboxes[i].checked = this.checked;
                    // Finn nærmeste 'tr'-element
                    var tr = checkboxes[i].closest('tr');
                    // Oppdater data-islockedbysuperadmin-attributtet basert på om sjekkboksen er avkrysset

                    //tr.setAttribute('data-islockedbysuperadmin', this.checked ? 'true' : 'false'); //This caused weird behaviour when checkbox was checked.
                }
                updateCount();
            });
        }

    </script>
</asp:Content>
