<%@ Page Language="c#" CodeBehind="List.aspx.cs" AutoEventWireup="True" Inherits="eDocument.Server.Administrator.eDocumentTemplate.List" MasterPageFile="~/Site.Master" %>

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

    <style type="text/css">
        .Hide
        {
            display: none;
        }
    </style>
    <h1 class="skjema-admin__page-title">
        Oversikt
    </h1>
    
    <%--<asp:Button runat="server" id="btnSync" CssClass="skjema-admin__button mb-5" OnClick="btnSync_OnClick" Text="Synkroniser"/>--%>

    <p class="skjema-admin__mb-40 skjema-admin__fs-18">
        Her kan du se alle skjema som er tilgjengelige for deg eller din organisasjon.<br />
    </p>
    
    <div class="skjema-admin__table__filter-container">
        <div class="d-flex align-items-center">
            <div class="skjema-admin__table-search-input-container" style="">
                <span class="budicon budicon-search"></span>

                <input class="skjema-admin__table-search-input" style="width: unset; border: none;" type="text" data-jscomponent="tableFilter" placeholder="Søk i skjema" />
                <!-- button class="skjema-admin__table-search-button" type="button" data-jscomponent="tableFilterSubmit">
                    <span class="budicon budicon-search"></span>test
                </button -->
                <button class="skjema-admin__table-search-clear-button" type="button" data-jscomponent="tableFilterClear" style="border: none; background-color: transparent;">
                    <span class="budicon budicon-cross-ui" style="top: 5px; font-size: 24px; position: relative;"></span>
                </button>
            </div>
        </div>

        <div class="d-flex">
            <div class="mt-3">
                <div class="ml-0 skjema-admin__table__filter-label">
                    Status
                </div>

                <asp:DropDownList 
                    ID="ddlFilterStatus" 
                    CssClass="skjema-admin__form__select skjema-admin__form__select--thin skjema-admin__mr-20"
                    OnSelectedIndexChanged="ddlFilterStatus_OnSelectedIndexChanged" 
                    AutoPostBack="True" 
                    Width="240"
                    runat="server" />
            </div>

            <div class="mt-3">
                <div class="ml-0 skjema-admin__table__filter-label">
                    Katalog
                </div>

                <asp:DropDownList 
                    ID="ddlFilterKatalog" 
                    OnSelectedIndexChanged="ddlFilterKatalog_SelectedIndexChanged" 
                    CssClass="skjema-admin__form__select skjema-admin__form__select--thin"
                    AutoPostBack="True" 
                    Width="240"
                    runat="server" />
            </div>

        </div>
    </div>
    <div id="formsCountContainer">Viser <span id="formsCount"></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>

    <div class="d-flex skjema-admin__mb-20">
        <div class="d-flex align-items-center skjema-admin__italic skjema-admin__mr-30" data-js="countText">
        </div>

        <div class="d-none" data-js="evenMoreSelect">
            <div class="d-flex align-items-center">
                <div class="skjema-admin__form__round-select">
                    <asp:DropDownList 
                        ID="ddlBulkChange" 
                        data-js="bulkSelect"
                        OnSelectedIndexChanged="ddlBulkChange_OnSelectedIndexChanged" 
                        AutoPostBack="True" 
                        Width="240"
                        runat="server" />
                </div>
            </div>
        </div>
    </div>
    
    <asp:GridView
        ID="gvMyTemplates"
        runat="server"
        AutoGenerateColumns="False"
        Width="100%"
        Border="0"
        data-jsid="tableOfForms"
        CssClass="skjema-admin__table 
        skjema-admin__table--min-width-3-n 
        skjema-admin__table--min-width-4 
        skjema-admin__table--min-width-6 
        skjema-admin__table--min-width-8
        skjema-admin__table--min-width-9
        skjema-admin__table--min-width-last
        skjema-admin__table__sort-icon-4
        skjema-admin__table__sort-icon-5
        skjema-admin__table__sort-icon-7
        skjema-admin__table__sort-icon-9
        jsTableCheckAll jsFilterTable"
        OnRowDataBound="gvMyTemplates_OnRowDataBound">

        <HeaderStyle CssClass="skjema-admin__table__header"></HeaderStyle>

        <Columns>
            <asp:BoundField DataField="TemplateId" HeaderText="Skjema ID" ItemStyle-CssClass="Hide" HeaderStyle-CssClass="Hide"></asp:BoundField>
            <asp:BoundField DataField="SubscriptionId" HeaderText="SubscriptionId" ItemStyle-CssClass="Hide" HeaderStyle-CssClass="Hide"></asp:BoundField>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="gvMyTemplates_chkAll" CssClass="jsAllCheck" AutoPostBack="false" runat="server" />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="gvMyTemplates_chkRow" 
                        CssClass="jsSingleCheck" 
                        runat="server" 
                        data-formid='<%# Eval("Formid") %>'
                        data-title='<%# Eval("Name") %>'
                        data-status='<%# Eval("Status") %>'
                        data-isformactive='<%# Eval("IsActive") %>'
                        data-templateversionid='<%# Eval("TemplateVersionId") %>'
                        data-templateid='<%# Eval("TemplateId") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="FormId" HeaderText="ID" />
            <asp:HyperLinkField DataTextField="Name" HeaderText="Tittel" DataNavigateUrlFields="TemplateId" DataNavigateUrlFormatString="~/eDocumentTemplate/Edit.aspx?eDocumentTemplateID={0}" />
            <asp:TemplateField ItemStyle-CssClass="text-center">
                <HeaderTemplate>
                    Tidsbestemt
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:LinkButton
                        ID="gvMyTemplates_calendar" 
                        CssClass="skjema-admin__table__calendar-icon" 
                        runat="server" 
                        OnClick="gvMyTemplates_calendar_onClick" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <HeaderTemplate>
                    Status
                </HeaderTemplate>
                <ItemTemplate>

                    <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("FormId") %>_status-text" class="font-italic" aria-describedby="<%# Eval("FormId") %>_tooltip-status" tabindex="0" data-jsid="versionStatusText">
                            <%# Eval("Status") %>
                            </span>

                        <div id="<%# Eval("FormId") %>_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") : ""%>
                        </div>
                    </div>


                    <!--
                    <asp:Panel runat="server">
                         <asp:Panel 
                            ID="activeIcon" 
                            runat="server" 
                            Visible="true"
                            class='skjema-admin__table__active-icon'>
                        </asp:Panel>

                        <asp:Panel 
                            ID="errorIcon" 
                            runat="server" 
                            Visible="false"
                            class='skjema-admin__table__error-icon'>
                        </asp:Panel>
                    </asp:Panel>
                    -->
                    <!--
                    <asp:Label ID="lblStatus" CssClass="skjema-admin__table" Text="" runat="server" />
                    -->
                </ItemTemplate>
            </asp:TemplateField>

            <asp:HyperLinkField 
                ControlStyle-CssClass="skjema-admin__table__pen-icon"
                Text="" 
                HeaderText="Feltverdi" 
                Visible="True" 
                DataNavigateUrlFields="TemplateId, SubscriptionId, Name" 
                ItemStyle-CssClass="text-center"
                DataNavigateUrlFormatString="~/Tjenestetorget.Administrator/SelectFieldRelation.aspx?eDocumentTemplateID={0}&SubscriptionID={1}&Name={2}" />

            <asp:BoundField DataField="TemplateCreatedByCustomerName" ItemStyle-CssClass="text-nowrap" HeaderText="Katalog"></asp:BoundField>
            
            <%--<!-- Pulldown-menu -->--%>
            <asp:TemplateField>
                <HeaderTemplate>
                    <span class='skjema-admin__table__config-icon' title="Flere valg"></span>
                </HeaderTemplate>

                <ItemTemplate>

                    <!-- Menu-button -->
                    <button class="skjema-admin__button-toggle" type="button" data-jsid="toggleMoreMenu">
                    </button>

                    <!-- Menu-items -->
                    <asp:Panel ID="panelOfToggles" CssClass="skjema-admin__designer__popup-menu d-none" runat="server" style="width:150px;">
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    
    <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>

    <!-- Modal for Time-based publishing -->
    <asp:Panel ID="pnlSetDate" Visible="False" runat="server" CssClass="skjema-admin__modal" data-jscomponent="modal">
        <div class="skjema-admin__modal__window">

            <button class="skjema-admin__modal__close" type="button" data-jscomponent="modalClose">
            </button>

            <asp:Label CssClass="skjema-admin__modal__title" Text="Tidsbestemt publisering" runat="server" />

            <div>
                <asp:Label ID="lblInfo" runat="server" />
            </div>
            
            <div class="skjema-admin__modal__input-container">
                <div>
                    <asp:Label CssClass="skjema-admin__modal__label" ID="lblFromDate" Text="Fra og med" runat="server" />
                    <asp:TextBox id="txtFromDate" class="datepick" runat="server" autocomplete="off"></asp:TextBox>
                    <asp:CompareValidator 
                        ID="CompareValidatorFromDate"
                        runat="server"
                        ControlToValidate="txtFromDate"
                        ErrorMessage="Feil datoformat, riktig format er dd.mm.åååå"
                        Operator="DataTypeCheck"
                        ForeColor="Red"
                        Display="Dynamic"
                        Type="Date">
                    </asp:CompareValidator>
                </div>

                <div>
                    <asp:Label ID="lblToDate" CssClass="skjema-admin__modal__label" Text="Til og med" runat="server" />
                    <asp:TextBox  ID="txtToDate" class="datepick" runat="server" autocomplete="off"></asp:TextBox>
                    <asp:CompareValidator 
                        ID="CompareValidatorToDate"
                        runat="server"
                        ControlToValidate="txtToDate"
                        ErrorMessage="Feil datoformat, riktig format er dd.mm.åååå"
                        Operator="DataTypeCheck"
                        ForeColor="Red"
                        Display="Dynamic"
                        Type="Date">
                    </asp:CompareValidator>
                </div>
            </div>

            <div>
                <asp:Button CssClass="skjema-admin__button skjema-admin__button--primary" runat="server" id="btnSetDate" OnClick="btnSetDate_OnClick" Text="Lagre"/>
            </div>
        </div>
    </asp:Panel>


	<!-- ACTIVATE-MODAL -->
    <div class="skjema-admin__modal" data-jscomponent="modal" data-jsid="activateModal" style="display:none;">
        <div class="skjema-admin__modal__window">
            <button class="skjema-admin__modal__close" type="button" data-jscomponent="modalClose"></button>

            <div class="skjema-admin__designer__modal__content">
                <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-40">
                    Aktiver skjema
                </h2>

                <p class="skjema-admin__mb-40 text-center" data-jsid="modalTitle">
                </p>

                <div class="skjema-admin__mb-20">
                    <input class="skjema-admin__designer__modal-input" type="text" placeholder="Endringskommentar" data-jsid="modalComment" />
                    <div class="skjema-admin__designer__modal-input__helper-text">
                        Spesifiser eventuelle endringer
                    </div>
                </div>

                <div class="skjema-admin__mb-40 text-center font-italic" data-jsid="modalVersion">
                </div>

                <div class="d-flex justify-content-center">
                   <button class="skjema-admin__designer__button skjema-admin__mr-20" type="button" data-jsid="modalCancel">
                       Avbryt
                   </button>

                    <button class="skjema-admin__designer__button skjema-admin__designer__button--primary" type="button" data-jsid="modalSave">
                       Aktiver
                   </button>
                </div>
            </div>
        </div>
    </div>

	<!--*** Delete template modal ***-->
	<div class="skjema-admin__modal" data-jscomponent="modal" data-jsid="deleteModal" style="display:none;">
        <div class="skjema-admin__modal__window">
            <button class="skjema-admin__modal__close" type="button" data-jscomponent="modalClose"></button>

            <div class="skjema-admin__designer__modal__content">
                <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-40">
                    Slett skjema
                </h2>

                <p class="skjema-admin__mb-40 text-center" data-jsid="modalTitle">
					Er du sikker p&aring; at du vil slette dette skjemaet?
                </p>

                <div class="d-flex justify-content-center">
                   <button class="skjema-admin__designer__button skjema-admin__mr-20" type="button" data-jscomponent="modalClose">
                       Avbryt
                   </button>

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


	<!--*** Error modal ***-->
	<div class="skjema-admin__modal" data-jscomponent="modal" data-jsid="errorModal" style="display:none;">
        <div class="skjema-admin__modal__window">
            <button class="skjema-admin__modal__close" type="button" data-jscomponent="modalClose"></button>

            <div class="skjema-admin__designer__modal__content">
                <h2 class="skjema-admin__designer__modal-title skjema-admin__mb-40">
                    Feil!
                </h2>

                <p class="skjema-admin__mb-40 text-center" id="errorText"></p>

                <div class="d-flex justify-content-center">
                   <button class="skjema-admin__designer__button skjema-admin__mr-20" type="button" data-jscomponent="modalClose">
                       Lukk
                   </button>
                </div>
            </div>
        </div>
    </div>


	<!-- JavaScript -->
    <script type="text/javascript">

		/*** Global variables ***/
		const STATUS_INPROGRESS = "I arbeid";
		const STATUS_CHANGED = "Endret";
		const STATUS_ACTIVE = "Aktiv";
		const STATUS_INACTIVE = "Inaktiv";

		
		/*** Functions ***/

        /**
         * Checks if a value is a string or not.
         * @param {unknown} value The value to check
         * @returns {boolean} True if string
         */
        function isString(value) {
            return typeof value === 'string';
        }

        /**
         * If value is not string, returns empty string. If not, returns value.
         * @param {string} value Value to check
         * @returns {string}
         */
        function safeString(value) {
            if (!isString(value)) return '';
            return value;
        }

        /**
         * Safe version of strings trim-method. If value is not string, just returns empty string.
         * @param {string} text String to trim
         * @returns {string}
         */
        function trim(text) {
            const newText = safeString(text);
            const trimmedText = newText.trim();
            return trimmedText;
        }

		/**
		 * Removes slash from end of url
		 * @param {string} url Urls to remove slash from
		 * @returns {string}
		 */
		function noPostSlash(url = '') {
			const trimmedUrl = trim(url);
			if(!trimmedUrl.endsWith('/')) return trimmedUrl;
			const noPostSlashUrl = trimmedUrl.slice(0, -1);
			return noPostSlashUrl;
		}


		/**
		 * Removes slash from beginning of an url
		 * @param {string} url Url to remove slash from.
		 * @returns {string}
		 */
		function noPreSlash(url = '') {
			const trimmedUrl = trim(url);
			if(!trimmedUrl.startsWith('/')) return trimmedUrl;
			const noPreSlashUrl = trimmedUrl.slice(1, trimmedUrl.length);
			return noPreSlashUrl;
		}


		/**
		 * Removes slash from start and end of url
		 * @param {string} url Url to remove slashes from
		 * @returns {string}
		 */
		function noWrappingSlash(url = '') {
			const noWrappedSlashUrl = noPreSlash(noPostSlash(url));
			return noWrappedSlashUrl;
		}


		/**
		 * Checks if data is text. If so, tries to parse it. If successful, returns result, otherwise returns data;
		 * @param {T} data Data to parse
		 * @returns {T}
		 */
		function parseIfText(data)  {
			if(typeof data !== 'string') return data;

			const result = parseJson(data);
			if(isError(result)) return data;
			return result;
		}

		/**
		 * Function for parsing a string to JSON.
		 * @param {string?} data Data to parse
		 * @returns {T}
		 */
		function parseJson(data) {
			if(!data) return {};
			const result = tryCatch(() => JSON.parse(data));
			if(isError(result)) return result;
			return result;
		}


		/**
		 * Wrapping a function in a try-catch
		 * @param {FFunction} action Function to run in try-catch
		 * @returns {T}
		 */
		function tryCatch(action) {
			try {
				const result = action();
				return result;
			} catch(error) {
				return error;
			}
		}


		/**
		 * Checks if a value is an error
		 * @param {unknown} value Value to check
		 * @returns {boolean} True if error, false if not.
		 */
		function isError(value) {
			return value instanceof Error;
		}


		/**
		 * Gets prettified message for predefined errors.
		 * @param {Error | string} error Error to get message from
		 */
		function getErrorMessage(error) {
            if (!error) return 'Mottok feil uten feilmelding';

			if(error.message) error = error.message;
			if(typeof error !== 'string') error = error.toString?.() || '';

			if(error.includes('Det finnes ingen template med templateId')) {
				return 'Skjema ble ikke slettet, fordi skjema er opprettet av en annen organisasjon.';
			}
			
			return error || 'Ukjent feil';
		}


		/**
		 * Closes all dropdowns
		 * @return {void}
		 */
		function closeAllDropdowns() {
			const allDropdowns = document.querySelectorAll("[data-jsid='toggleMoreMenu']");
			allDropdowns.forEach((toggleElement) => closeDropDown(toggleElement.nextElementSibling));
		}

		/**
		 * Closes a dropdown
		 * @param {HTMLElement} dropdownElement Dropdown-element to close
		 * @return {void}
		 */
		function closeDropDown(dropdownElement) {
			dropdownElement.classList.add("d-none");
			const tr = dropdownElement.closest("tr");
			tr.classList.remove("context-menu-open");
		}


		/**
		 * Shows a dropdown
		 * @param {HTMLElement} dropdownElement Dropdown-element to show
		 * @return {void}
		 */
		function showDropdown(dropdownElement) {
			dropdownElement.classList.remove("d-none");
			const tr = dropdownElement.closest("tr");
			tr.classList.add("context-menu-open");
		}


		/**
		 * Function for removing quotation marks from a string
		 * @param {string} text Text to remove quotation marks from
		 * @returns {string}
		 */
		function removeQuotationMark(text) {
			if(typeof text !== 'string') return '';
			if(text.startsWith('"') && text.endsWith('"')) return text.slice(1, -1);
			return text;
		}


		/**
		 * Function for activating a template
		 * @param {string} templateVersionId Id of template version to activate
		 * @param {string} formId Id of form to activate
		 * @param {string} comment Comment to add to activation
		 * @param {string} status Current status of template
		 * @returns {Promise<void>}
		 */
			async function publishUrlPost(templateVersionId, formId, comment, status) {
			const body = {comment};

			const apiUrl = createPublishUrl(templateVersionId, formId, status);

			const response = await fetch(apiUrl, {
				method: "post",
				headers: {"Content-Type": "application/json"},
				credentials: "include",
				body: JSON.stringify(body)
			});

			const result = removeQuotationMark(await response.text());
			if(!response.ok) return Error(result);
		};


		/**
		 * Function for activating several templates at once
		 * @param {Array} items Array of items to activate
		 * @returns {Promise<{results: Array, error: string}>}
		 */
		async function bulkPublishPost(items = [], comment = '') {
			const results = [];
			const errors = [];
			let error = '';

			for(const item of items) {
				const {templateVersionId, formId, status} = item;
				const result = await publishUrlPost(templateVersionId, formId, comment, status);
				if(isError(result)) errors.push(result);
				else results.push(result);
			}

			if(errors.length) {
				const errorMessages = errors.map((error) => getErrorMessage(error));
				error = errorMessages.join('\n');
			}

			return {results, error};
		}


		/**
		 * Creates a publish-url
		 * @param {string} templateVersionId The template-version-id
		 * @param {string} formId The form-id
		 * @param {string} status The status
		 * @return {string} The url
		 */
		function createPublishUrl(templateVersionId, formId, status) {
			return "<%= ApiUrl %>" + "/" + "<%= CustomerUsername %>" + 
				"/designer/publishExistingVersion?templateVersionId=" + templateVersionId + "&formid=" + formId + 
				"&status=" + status;
		}


		/**
		 * Creates an unpublish-url
		 * @param {string} templateId The template-id
		 * @return {string} The url
		 */
		function createUnpublishUrl(templateId) {
			return "<%= ApiUrl %>" + "/" + "<%= CustomerUsername %>" + "/designer/unpublish?templateId=" + templateId;
		}


		/**
		 * Deactivates a form
		 * @param {string} unpublishUrl The url to unpublish
		 * @return {Promise} The fetch-promise
		 */
		async function deactivateForm(unpublishUrl) {
			return fetch(unpublishUrl, {
				method: "post",
				headers: {
					"Content-Type": "application/json",
				},
				credentials: "include",
			});
		}


		/**
		 * Handles click on activate-button
		 * @param {Event} event The event-object
		 * @return {void}
		 */
		async function handleActivateForm(event) {
			event.preventDefault();
			const button = event.target;

			const modal = document.querySelector("[data-jsid='activateModal']");
			const modalTitle = document.querySelector("[data-jsid='modalTitle']");
			const modalVersion = document.querySelector("[data-jsid='modalVersion']");
			const status = button.getAttribute("data-status");
			const templateVersionId = button.getAttribute("data-templateversionid");
			const formId = button.getAttribute("data-formid");
			const versionString = button.getAttribute("data-version");	
			const version = parseInt(versionString);
			const title = button.getAttribute("data-title");

			if(status === STATUS_INACTIVE) {
				const result = await publishUrlPost(templateVersionId, formId, '', status);
				if(isError(result)) return showErrorMessage(result.message);
				location.reload();
			} else if (status === STATUS_INPROGRESS || status === STATUS_CHANGED) {
				modalTitle.innerHTML = formId + " " + title;
				modalVersion.innerHTML = "Versjon " + version;
				modal.removeAttribute("style");
				modal.setAttribute("data-templateversionid", templateVersionId);
				modal.setAttribute("data-formid", formId);
				modal.setAttribute("data-status", status);
			}
		}


		/**
		 * Handles the click on deactivate-button
		 * @param {Event} event The event-object
		 * @return {void}
		 */
		async function handleDeactivateForm(event) {
			event.preventDefault();
			const button = event.target;
			const templateId = button.getAttribute("data-templateid");
			const unpublishUrl = createUnpublishUrl(templateId);

			const result = await deactivateForm(unpublishUrl);
			if(isError(result)) return showErrorMessage(result.message);
			location.reload();
		}


		/**
		 * Method for deleting a template
		 * @param {string?} templateId Id of template to delete.
		 * @returns {TObject}
		 */
		async function deleteTemplate(templateId) {
			if(!templateId) return Error('Id må oppgis for å slette skjema');

			const apiUrl = noWrappingSlash("<%= ApiUrl %>");
			const customerId = noWrappingSlash("<%= CustomerUsername %>");
			const url = `${apiUrl}/${customerId}/designer/deletetemplate`;
			const params = `?templateid=${templateId}`;

			let error = '';
			let result = '';
			let response = {};
			try {
				response = await fetch(
					url + params,
					{method: 'POST', credentials: "include"},
				).catch((error) => error);

				const {status, ok} = response || {};

				if(response instanceof Error) error = response.message;
				else if(!ok) error = (await response.text()) || response.statusText || 'Feilet med kode: ' + status;
				else result = await response.text();

			} catch (catchError) {
				error = catchError;
			}

			if(error) error = parseIfText(error);
			if(result) result = parseIfText(result);
			if(result?.message) error = result.message;
			if(result?.Message) error = result.Message;

			if(error) return Error(error);

			return {ok: response.ok};
		}


		/**
		 * Method for showing an error message
		 * @param {string} message Message to show
		 * @returns {void}
		 */
		async function showErrorMessage(message) {
			const errorModal = document.querySelector('[data-jsid="errorModal"]');
			const errorText = errorModal.querySelector('#errorText');
			errorText.innerText = message;
			errorModal.removeAttribute("style", "display:none;");
		}


		/**
		 * Runs when page loads
		 * @param {Event} event The event-object
		 * @return {void}
		 */
		function runOnLoad(table) {
			/*** Handle sorting ***/
            $('#' + '<%= gvMyTemplates.ClientID %>').tablesorter({
                headers: {
                    2: { sorter: false },
                    5: { sorter: false }, 
                    6: { sorter: true },
                    7: { sorter: false },
                    9: { sorter: false },
                } 
            });

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

			/*** Handle date-picker ***/
			$('.datepick').each(function () {
				$(this).datepicker({
					dateFormat: 'dd.mm.yy',
					firstDay: 1
				});
			});
		}


		/*** Runs on load ***/
        $(document).ready(function () {

			/*** Variables ***/
			const table = document.getElementById("<%= gvMyTemplates.ClientID %>");
            const selectWrapper = document.querySelector("[data-js='evenMoreSelect']");
            const countElement = document.querySelector("[data-js='countText']");
            const bulkSelect = document.querySelector("[data-js='bulkSelect']");
			const modal = document.querySelector("[data-jsid='activateModal']");
			const modalTitle = document.querySelector("[data-jsid='modalTitle']");
			const modalVersion = document.querySelector("[data-jsid='modalVersion']");
			const modalCancel = document.querySelector("[data-jsid='modalCancel']");
			const modalClose = document.querySelector("[data-jscomponent='modalClose']");
			const modalSave = document.querySelector("[data-jsid='modalSave']");
			const modalInput = document.querySelector("[data-jsid='modalComment']");
			const activateButtons = table.querySelectorAll("[data-jsid=activateButton]");
			const deactivateButtons = table.querySelectorAll("[data-jsid=deactivateButton]");
			const itemsToPublish = {
				shouldShowModal: false,
				items:[]
			}
			
            if(!table) return;

			runOnLoad(table);


			/*** Handle drop-down ***/

			//Make sure that the dropdowns are closed when clicking outside
			const background = document.querySelector("[data-js=mainPageContent]");
			background.addEventListener("click", closeAllDropdowns, true);

			//Add event-listeners to all dropdown-buttons
			const allDropdownButtons = table.querySelectorAll("[data-jsid='toggleMoreMenu']");
			allDropdownButtons.forEach((toggleElement) => {
				toggleElement.addEventListener("click", (event) => {
					const target = event.target;
					const menu = target.nextElementSibling;
					const isOpen = !menu.classList.contains('d-none');

					closeAllDropdowns(menu);
					if(!isOpen) showDropdown(menu);
				});
			});

			//Add event-listener to activate-buttons.
			activateButtons.forEach(function (button) {
				button.addEventListener("click", handleActivateForm);
			});

			//Add event-listener to deactivate-buttons.
			deactivateButtons.forEach(function (button) {
				button.addEventListener("click", handleDeactivateForm);
			});


			/*** Handles filtering ***/
			const 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");
				});
			}

			/*** Handles checkboxes ***/
			table.addEventListener("change", function () {
				const arr = Array.prototype.slice.call(table.querySelectorAll("input[type='checkbox']"));
				const isSomeChecked = arr.some(function (checkbox) {
					return checkbox.checked;
				});

				const checkedBox = arr.filter(function (checkbox) {
					return checkbox.checked && checkbox.parentElement.classList.contains("jsSingleCheck");
				});

				if (checkedBox.length > 0) {
					countElement.innerHTML = checkedBox.length + " valgt";
				} else {
					countElement.innerHTML = "";
				}

				if (isSomeChecked) {
					selectWrapper.classList.remove("d-none");
				} else {
					selectWrapper.classList.add("d-none");
				}
			});
			
			//Handle delete-buttons
			const deleteTemplateModal = document.querySelector('[data-jsid="deleteModal"]');
			const deleteButtons = Array.from(document.querySelectorAll('[data-jsid="deleteTemplate"]'));

			deleteButtons.forEach(function (deleteButton) {
				deleteButton?.addEventListener('click', async (event) => {
					event.preventDefault();
					deleteTemplateModal.removeAttribute("style", "display:none;");
					const templateId = deleteButton.getAttribute('data-templateid');
					
					const deleteAction = deleteTemplateModal.querySelector('[data-jsid="deleteTemplateAction"]');

					//Handle delete-action in delete-modal
					deleteAction.onclick = async (event) => {
						event.preventDefault();
						const response = await deleteTemplate(templateId);
						deleteTemplateModal.setAttribute("style", "display:none;");
						deleteAction.onclick = null;

						if(isError(response)) {
							return showErrorMessage(getErrorMessage(response) || 'Feil ved sletting av skjema');
						}

						if(response.ok) return location.reload(); 
						showErrorMessage('Fant ingen response fra server!');
					};
				});
			});

			//Canceling modal
			modalCancel.addEventListener("click", () => {
				modal.setAttribute("style", "display:none;");
				modalSave.removeAttribute("data-isbulk");
				bulkSelect.value = "";

				itemsToPublish.shouldShowModal = false;
				itemsToPublish.items = [];
			});

			//Closing modal
			modalClose.addEventListener("click", () => {
				modalSave.removeAttribute("data-isbulk");
				bulkSelect.value = "";

				itemsToPublish.shouldShowModal = false;
				itemsToPublish.items = [];
			});

			//Publish from modal
			modalSave.addEventListener("click", async () => {
				const comment = modalInput.value;

				if(modalSave.getAttribute("data-isbulk")) {
					const {results, error} = await bulkPublishPost(itemsToPublish.items, comment);
					modal.setAttribute("style", "display:none;");
					if(error) return showErrorMessage(error);

					location.reload();
				} 

				const templateVersionId = modal.getAttribute("data-templateversionid");
				const formId = modal.getAttribute("data-formid");
				const status = modal.getAttribute("data-status");
				const result = await publishUrlPost(templateVersionId, formId, comment, status);
				modal.setAttribute("style", "display:none;");

				if(isError(result)) {
					return showErrorMessage(getErrorMessage(result) || 'Feil ved publisering av skjema');
				}

				location.reload();
			});

			const versionStatusTexts = Array.from(document.querySelectorAll("[data-jsid='versionStatusText']"));
			versionStatusTexts.forEach((statusTextElement) => {

				function displayToolTip(toggleOn) {
					const statusTextId = statusTextElement.getAttribute("aria-describedby");
					const 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);
				});
			});

			const savedOnChange = function () {
				return bulkSelect.onchange;
			}();

			bulkSelect.onchange = function () {};
			bulkSelect.addEventListener("change", async (event) => {
				event.preventDefault();

				if (event.target.value === "Activate") {

					const idsAndTitles = Array.from(table.querySelectorAll("tbody input[type='checkbox']:checked")).reduce(function (acc, checked) {
						const formid = checked.closest("[data-formid]").getAttribute("data-formid");
						const title = checked.closest("[data-title]").getAttribute("data-title");
						const isActive = checked.closest("[data-isformactive]").getAttribute("data-isformactive");
						const status = checked.closest("[data-status]").getAttribute("data-status");

						if (isActive === "False" || status === STATUS_CHANGED) {
							acc.push(formid + " " + title);
						}
						return acc;
					}, []);

					table.querySelectorAll("tbody input[type='checkbox']:checked").forEach((checked) => {
						const formid = checked.closest("[data-formid]").getAttribute("data-formid");
						const templateVersionId = checked.closest("[data-templateversionid]").getAttribute("data-templateversionid");
						const isActive = checked.closest("[data-isformactive]").getAttribute("data-isformactive");
						const status = checked.closest("[data-status]").getAttribute("data-status");

						const publishItem = {
							templateVersionId,
							formid,
							status,
						}
						
						if(isActive === "False" || status === STATUS_CHANGED) itemsToPublish.items.push(publishItem);
						if(status === STATUS_INPROGRESS || status === STATUS_CHANGED) itemsToPublish.shouldShowModal = true;
					});

					modalTitle.innerHTML = "";
					const frag = document.createDocumentFragment();
					idsAndTitles.forEach(function (text) {
						const div = document.createElement("div");
						div.appendChild(document.createTextNode(text));
						frag.appendChild(div);
					});

					if (itemsToPublish.shouldShowModal) {
						modalTitle.appendChild(frag);
						modal.removeAttribute("style");
						modalSave.setAttribute("data-isbulk", "true");
					} else {
						const {results, error} = await bulkPublishPost(itemsToPublish.items, "");
						modal.setAttribute("style", "display:none;");
						if(error) return showErrorMessage(error);
						location.reload();
					}

				} else if (event.target.value === "Deactivate") {

					var templateIds = Array.from(table.querySelectorAll("input[type='checkbox']:checked")).reduce(function (acc, checked) {
						var templateId = checked.closest("[data-templateid]").getAttribute("data-templateid");
						acc.push(templateId);
						return acc;
					}, []);

					Promise.all(templateIds.map(function (templateId) {
						return fetch(createUnpublishUrl(templateId), {
							method: "post",
							headers: {
								"Content-Type": "application/json",
							},
							credentials: "include",
						})
					})).then(function (responses) {
						location.reload();
					});
					
				} else if(event.target.value === "Date") {
					savedOnChange();
				}
			});

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

        });
    </script>
</asp:Content>