[% PROCESS _header.tt %]
[% PROCESS _message.tt %]
[% PROCESS _blocks.tt %]

<script>
<!--
  var pageLoaded = false;
-->
</script>

[% BLOCK _check_type %]
  <table class="h-full w-full cellspacing striped rowhover rowhoverhighlight [% sub | html %] js-checks" style="display: none;">
    [% IF ctype == "new" %]
      <thead>
        <tr>
          <td align="center" colspan="7">
            <button class="my-2" onclick="jQuery('.js-radio-new[value=\'on\']:visible').attr('checked', true); return false;">Accept All New Checks</button>
          </td>
        </tr>
      </thead>
    [% ELSIF ctype == "obsolete" %]
      <thead>
        <tr>
          <td align="center" colspan="7">
            <button class="my-2" onclick="jQuery('.js-radio-obsolete[value=\'off\']:visible').attr('checked', true); return false;">Remove All Obsolete Checks</button>
          </td>
        </tr>
      </thead>
    [% END %]
    <tbody>
    [% FOREACH check = checks.$ctype; name = check.name %]
      [% IF services.exists(name); s = services.$name; END %]
      <tr>
        <th data-name="[% check.name | html %]">
          <div class="flex items-center min-w-max justify-between">
            <div class="text-ellipsis overflow-hidden max-w-lg">[% IF services.exists(name) %]<a href="extinfo.cgi?type=2&host=[% s.host_name | uri %]&service=[% s.description | uri %]&backend=[% s.peer_key %]" class="link">[% END %][% check.name | html %][% IF services.exists(name) %]</a>[% END %]</div>
            [% IF services.exists(name) %]
              [% comment_count = s.comments.size; has_bp=0; PROCESS _status_service_attributes service=s service_comment_count=comment_count loop_index=loop.index %]
            [% END %]
          </div>
        </th>
        <td class="max-w-min">
          [% state = 'PENDING' %]
          [% IF ctype == "exists" || ctype == "obsolete" %]
            [% IF services.exists(name) %]
              [% state = servicestatetext(s) %]
            [% END %]
            <div class='text-center badge [% state %]'>[% state %]</div>
          [% END %]
          [% IF ctype == "new" %]
            <div class='text-center badge PENDING'>new</div>
          [% END %]
          [% IF ctype == "disabled" %]
            [% IF check.defined("disabled") && check.disabled %]
              <div class='text-center badge PENDING clickable' onClick="jQuery('#info_link_[% name2id(check.id) | html %]').click(); return false;">disabled</div>
            [% ELSIF check.defined("exclude_reason") %]
              <div class='text-center badge PENDING clickable' onClick="jQuery('#info_link_[% name2id(check.id) | html %]').click(); return false;">excluded</div>
            [% ELSE %]
              <div class='text-center badge PENDING'>disabled</div>
            [% END %]
            [% IF check.defined("excluded_manually") && check.excluded_manually %]
              <div class='text-center badge UNKNOWN clickable' title="check has been manually disabled" onClick="jQuery('#info_link_[% name2id(check.id) | html %]').click(); return false;">manually</div>
            [% END %]
          [% END %]
        </td>
        [% IF ctype == "new" || ctype == "exists" || ctype == "obsolete" %]
        <td class="truncate max-w-xs text-left" title="additional check arguments&#013;ex.: override thresholds: warn='load > 5'">
          [% IF ctype == "new" %]
            <input type="text" name="args.[% check.id | html %]" class="js-checks ml-1" placeholder="additional arguments" onkeyup="jQuery('INPUT[name=\'check.[% check.id | html %]\'][value=\'on\']').attr('checked', true); checkSaveButtonColor();" onchange="checkSaveButtonColor();">
          [% ELSE %]
            <input type="text" name="args.[% check.id | html %]" class="js-checks ml-1" value="[% IF check.defined("args") %][% check.args | html %][% END %]" onkeyup="checkSaveButtonColor();" onchange="checkSaveButtonColor();">
          [% END %]
        </td>
        <td title="this service matches [% check.rules.size %] existing rules" class="clickable" onClick="jQuery('#info_link_[% name2id(check.id) | html %]').click(); set_sub(3, false, 'infosub_[% name2id(check.id) | html %]'); return false;">
          [% IF check.rules.size == 0 %]
          <span class="opacity-70">-</span>
          [% ELSE %]
            <span>[% check.rules.size %]</span>
          [% END %]
        </td>
        [% END %]
        <td class="[% IF ctype != "exists" %]w-full[% END %]">
          <a href="" id="info_link_[% name2id(check.id) | html %]" class="link ml-1" onclick="overcard({'bodyCls': 'p-2', 'mainCls': 'modalFG min-h-[500px]', 'fixedPos': true, 'draggable': true, 'resizable': true, 'bodyEl': 'info_[% name2id(check.id) | html %]', 'caption': 'Details for check: [% check.name | html %]', 'width': 900 }); set_sub(1, false, 'infosub_[% name2id(check.id) | html %]'); return false;">(info)</a>
          [% PROCESS _info_popup %]
        </td>
        [% IF ctype == "exists" || ctype == "obsolete" %]
        <td class='truncate w-1/2 max-w-xs'>
          [% IF services.exists(name) %]
            [% s.plugin_output %]
          [% END %]
        </td>
        [% END %]
        <td class="pt-px pb-px">
          <div class="flexrow flex-nowrap gap-x-2">
            <div class="radiogroup" style="width: 135px; height: 24px;">
              <input
                type="radio"
                value="on"
                class="js-checks js-radio-[% ctype %] activeENABLED"
                id="[% name2id(check.id) | html %]_on"
                name="check.[% check.id | html %]"[% IF ctype == "exists" || ctype == "obsolete" %]checked="checked"[% END %]
              >
              <label for="[% name2id(check.id) | html %]_on" title="Enables monitoring of this check">On</label>
              [% IF ctype == "new" %]
              <input
                type="radio"
                value="new"
                class="js-checks js-radio-[% ctype %]"
                id="[% name2id(check.id) | html %]_new"
                name="check.[% check.id | html %]"[% IF ctype == "new" %]checked="checked"[% END %]
              >
              <label for="[% name2id(check.id) | html %]_new" title="Keep check in the new section.">New</label>
              [% END %]
              <input
                type="radio"
                value="off"
                class="js-checks js-radio-[% ctype %]"
                id="[% name2id(check.id) | html %]_off"
                name="check.[% check.id | html %]"[% IF ctype == "disabled" %]checked="checked"[% END %]
              >
              <label for="[% name2id(check.id) | html %]_off" title="Set check into manually disabled mode">Off</label>
            </div>
          </div>
        </td>
      </tr>
    [% END %]
    </tbody>
    [% IF checks.$ctype.size == 0 %]
    <tfoot>
      <tr>
        <td class="text-center textHINT">[% IF agent.hostname != "new" %]no [% ctype %] checks.[% ELSE %]not yet scanned...[% END %]</td>
      </tr>
    </tfoot>
    [% END %]
  </table>
[% END %]

[% BLOCK _info_popup %]
  <div id="info_[% name2id(check.id) | html %]" class="hidden max-h-[calc(88vh-40px)] h-full min-h-32 flexcol flex-nowrap">
    <div class="head justify-between" style="flex: 0 0 40px;">
      <div class="grow"></div>
      <span class="tabs clickable text-center text-sm w-40 active" id="infosub_[% name2id(check.id) | html %]_1" onclick="set_sub(1, false, 'infosub_[% name2id(check.id) | html %]')">Info</span>
      <span class="tabs clickable text-center text-sm w-40" id="infosub_[% name2id(check.id) | html %]_2" onclick="set_sub(2, false, 'infosub_[% name2id(check.id) | html %]')">Attributes</span>
      <span class="tabs clickable text-center text-sm w-40" id="infosub_[% name2id(check.id) | html %]_3" onclick="set_sub(3, false, 'infosub_[% name2id(check.id) | html %]')">Rules</span>
      <div class="grow"></div>
    </div>
    <div class="infosub_[% name2id(check.id) | html %]_1 h-full max-h-[calc(88vh-40px)] overflow-auto">
      [% IF check.defined("disabled") && check.disabled %]
      <div>
        <h4>Disabled</h4>
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            [% FOREACH row = check.disabled %]
              [% IF perl_ref(row) == "ARRAY" %]
                <tr>
                  <th>[% row.0 | html %]</th>
                  <td class="pl-2">[% row.1 | html %]</td>
                </tr>
              [% ELSE %]
                <tr>
                  <td colspan="2">[% row | html %]</td>
                </tr>
              [% END %]
            [% END %]
          </tbody>
        </table>
      </div>
      [% ELSIF check.defined("exclude_reason") %]
      <div>
        <h4>Excluded</h4>
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            [% FOREACH row = check.exclude_reason %]
              <tr>
                <th>[% row.0 | html %]</th>
                <td class="pl-2">[% row.1 | html %]</td>
              </tr>
            [% END %]
          </tbody>
        </table>
      </div>
      [% END %]
      [% IF check.defined("extra_src") %]
      <div>
        <h4>Source</h4>
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            <tr>
              <td>[% check.extra_src | html %]</td>
            </tr>
          </tbody>
        </table>
      </div>
      [% END %]
      [% IF check.defined("check") %]
      <div class="mt-5">
        <h4>Check Command</h4>
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            <tr>
              <td>[% check.check | html %]</td>
            </tr>
          </tbody>
        </table>
      </div>
      [% END %]
      [% IF check.defined("cfg") %]
      <div class="mt-5">
        <h4>Config Source</h4>
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            <tr>
              <td colspan="2">[% strip_site_path(check.cfg._FILE) | html %] line [% check.cfg._LINE | html %]</td>
            </tr>
            [% FOREACH attr = check.cfg.keys.sort %]
            [% IF attr == "_FILE"; NEXT; END %]
            [% IF attr == "_LINE"; NEXT; END %]
            [% IF attr == "warn"; NEXT; END %]
            [% IF attr == "crit"; NEXT; END %]
            <tr>
              <td class="align-baseline">[% attr | html %]</td>
              <td class="pl-2">
                [% FOREACH val = check.cfg.$attr.list %]
                  [% val | html %][% IF !loop.last %]<br>[% END %]
                [% END %]
              </td>
            </tr>
            [% END %]
          </tbody>
        </table>
      </div>
      [% END %]
      <div class="mt-5">
        <h4>Default Arguments</h4>
        [% IF !check.defined("current_args") || check.current_args.size == 0 %]
          <div class="text-left">(none)</div>
        [% ELSE %]
          <table class="body w-fit striped rowhover cellborder border borderDefault">
            <tbody>
              [% FOREACH a = check.current_args %]
                <tr>
                  <td>[% a | html %]</td>
                </tr>
              [% END %]
            </tbody>
          </table>
        [% END %]
      </div>
    </div>
    <div class="infosub_[% name2id(check.id) | html %]_2 h-full max-h-[calc(88vh-40px)] overflow-auto" style="display: none;">
      <div>These attributes can be used in thresholds and filters.</div>
      [% IF check.defined("info") %]
        <table class="body w-fit striped rowhover cellborder border borderDefault">
          <tbody>
            [% FOREACH attr = check.info.keys.sort %]
              <tr>
                <th>[% attr | html %]</th>
                <td class="pl-2">[% check.info.$attr | html %]</td>
              </tr>
            [% END %]
          </tbody>
        </table>
      [% ELSE %]
        <div class="textHINT">no specific attributes available.</div>
      [% END %]
    </div>
    <div class="infosub_[% name2id(check.id) | html %]_3 h-full max-h-[calc(88vh-40px)] overflow-auto" style="display: none;">
      <div>The following rules apply to this service:</div>
      [% already_set = {} %]
      [% FOREACH r = check.rules.reverse %]
        [% IF !loop.first%]<hr class="my-3">[% END %]
        <table class="body w-fit striped rowhover mb-5 cellborder border borderDefault min-w-[400px]">
          <tbody>
            <tr>
              <th>Source</th>
              <td class="pl-2">[% strip_site_path(r._FILE) %] line [% r._LINE %]</td>
            </tr>
            <tr>
              <th colspan="2">Matching</th>
            </tr>
            [% IF r.exists("host") %]
              <tr>
                <th>Host</th>
                <td class="pl-2">[% r.host | html %]</td>
              </tr>
            [% END %]
            [% IF r.exists("service") %]
              <tr>
                <th>Service</th>
                <td class="pl-2">[% r.service | html %]</td>
              </tr>
            [% END %]
            [% IF r.exists("match") %]
              <tr>
                <th>Match</th>
                <td class="pl-2">[% r.match | html %]</td>
              </tr>
            [% END %]
            [% IF r.exists("tags") %]
              <tr>
                <th>Tags</th>
                <td class="pl-2">[% r.tags | html %]</td>
              </tr>
            [% END %]

            <tr>
              <th colspan="2" class="h-5"></th>
            </tr>
            <tr>
              <th colspan="2">Attributes</th>
            </tr>
            [% FOREACH attr = r.keys.sort %]
              [% IF attr == "_FILE"; NEXT; END %]
              [% IF attr == "_LINE"; NEXT; END %]
              [% IF attr == "host"; NEXT; END %]
              [% IF attr == "service"; NEXT; END %]
              [% IF attr == "tags"; NEXT; END %]
              [% IF attr == "section"; NEXT; END %]
              [% IF attr == "match"; NEXT; END %]
              <tr>
                <th class="min-w-32 [% IF already_set.exists(attr) %]line-through[% END %]">[% attr | html %]</th>
                <td class="pl-2 [% IF already_set.exists(attr) %]textHINTsoft[% END %]">[% r.$attr | html %]</td>
              </tr>
              [% val = r.$attr; IF !val.match("^(\\+|\\!)") %]
                [% already_set.$attr = 1 %]
              [% END %]
            [% END %]
          </tbody>
        </table>
      [% END %]
      [% IF check.rules.size == 0 %]
        <div class="textHINT">no specific rules available.</div>
      [% END %]
    </div>
  </div>
[% END %]

<div class="flexrow 2xl:justify-between h-full w-full max-w-[1200px]">
  <div class="card w-full flexcol gap-0 flex-nowrap h-full min-h-[500px]">
    <div class="head justify-between" style="flex: 0 0 40px;">
      <div class="w-40">
        <a href="agents.cgi" class="button header-button rounded w-[70px]" title="Go back to agent list"><i class="uil uil-angle-double-left"></i>Back</a>
      </div>
      <h3>[% IF agent.hostname != "new" %]Edit[% ELSE%]Add[% END %] Agent</h3>
      <div class="w-40 flex justify-end relative">
        <button class="w-fit ml-2 pr-1" onClick="toggleElement('action_menu', undefined, true); return false;">Actions <i class="uil uil-angle-down mr-0" title='More Host Actions'></i></button>
        <div id="action_menu" style="display: none;" class="context_menu w-[160px] left-0 top-[30px]">
          <form action="agents.cgi" method="POST">
            <input type="hidden" name="CSRFtoken" value="[% get_user_token(c) %]">
            <input type="hidden" name="hostname" value="[% agent.hostname | html %]">
            <input type="hidden" name="backend" value="[% agent.peer_key | html %]">
            <ul class="w-full">
              <li>
                <a href="agents.cgi?action=clone&amp;hostname=[% agent.hostname | uri %]&backend=[% agent.peer_key | uri %]" class="[% IF agent.hostname == "new" %]disabled[% END %]" onclick=""><i class="fa-solid fa-clone text-xs"></i> Clone</a>
              </li>
              <li><hr></li>
              <li class="[% IF agent.hostname != "new" %]hover-red[% END %]">
                <a href="" class="[% IF agent.hostname == "new" %]disabled[% END %]" onclick="if(confirm('really remove host: [% agent.hostname | html %]?')) { return send_form_in_background_and_forward(this, {action: 'remove' }, null, 'agents.cgi') }; return false;"><i class="fa-solid fa-trash text-xs"></i> Remove</a>
              </li>
            </ul>
          </form>
        </div>
      </div>
    </div>
    <form action="agents.cgi" method="POST" class="flexcol gap-y-0 w-full h-[calc(100%-50px)]" onsubmit="setFormBtnSpinner(this)">
      <input type="submit" onclick="return false;" class="hidden"><!--do not submit on enter-->
      <input type="hidden" name="CSRFtoken" value="[% get_user_token(c) %]">
      <input type="hidden" name="old_hostname" value="[% IF agent.hostname != "new"; agent.hostname | html; END %]">
      <input type="hidden" name="old_backend" value="[% agent.peer_key | html %]">
      [% IF agent.exists("cloned_from") %]
      <input type="hidden" name="cloned_from" value="[% agent.cloned_from | html %]">
      [% END %]
      <input type="hidden" name="type" value="[% agent.type | html %]">
      [% IF ! has_multiple_backends %]
      <input type="hidden" name="backend" value="[% (agent.peer_key || config_backends.keys.0) | html %]">
      [% END %]
      <div style="flex: 0 0 140px;">
        <table class="body cellspacing striped">
          <tbody>
            <tr>
              <th class="text-right px-0">Hostname</th>
              <td>
                <input class="w-full min-w-20" type="text" name="hostname" id="hostname" value="[% IF agent.hostname != 'new' %][% agent.hostname | html %][% END %]" required placeholder="enter existing or new hostname" onfocus="this.click()" onclick="ajax_search.init(this, 'host', { url: 'status.cgi?format=search&amp;type=hosts', emptymsg:'[% IF agent.hostname != 'new' %]rename this host[% ELSE %]create new host[% END %]', autosubmit:false })">
              </td>
              <th class="text-right px-0">IP Address</th>
              <td>
                <div class="flexrow flex-nowrap gap-x-1">
                  <input class="w-full min-w-20" type="text" name="ip" value="[% agent.ip | html %]" placeholder="will use hostname if empty">
                  <button class="js-ip-wzd-button" title="autofill address from hostname ip lookup."><i class="uil uil-lightbulb mr-0"></i></button>
                </div>
              </td>
              <th class="text-right px-0">Mode</th>
              <td>
                <select name="mode" class="w-full">
                  <option value="https"[% IF agent.mode == "https" %] selected[% END %]>https</option>
                  <option value="insecure"[% IF agent.mode == "insecure" %] selected[% END %]>https (no verification)</option>
                  <option value="http"[% IF agent.mode == "http" %] selected[% END %]>plain http</option>
                </select>
              </td>
              <th class="text-right px-0">Port</th>
              <td>
                <input type="text" name="port" value="[% IF agent.port != default_port %][% agent.port | html %][% END %]" class="w-full" placeholder="[% default_port | html %]">
              </td>
            </tr>
            <tr>
              <th class="text-right px-0">Password</th>
              <td colspan="3">
                <div class="js-toggle-password relative flex-grow">
                  <input type="password" name="password" value="" class="w-full" placeholder="[% IF agent.password != '' %]password set, enter new one to change[% ELSE %]enter agent password or macro, ex.: $USER9$[% END %]" autocomplete="new-password">
                  <i class="uil uil-eye-slash absolute z-10 right-0 top-0 mr-2 opacity-50 text-lg js-toggle-password"></i>
                </div>
              </td>
              <th class="text-right px-0">Section</th>
              <td colspan="3">
                <input class="w-full" type="text" name="section" value="[% agent.section | html %]" onfocus="this.click()" onclick="ajax_search.init(this, 'section', { url: 'agents.cgi?action=json&amp;type=section', emptymsg:'create new section', autosubmit:false })">
              </td>
            </tr>
            <tr>
              <th class="text-right px-0">Tags</th>
              <td colspan="3">
                <div class="tags-input">
                  <input
                    type="text"
                    name="tags"
                    value="[% agent.tags.join(', ') | html %]"
                    placeholder="additional tags"
                    onfocus="this.click()"
                    onclick="ajax_search.init(this, 'tag', { url: 'agents.cgi?action=json&type=tags', emptymsg:'press enter to create new tag', autosubmit:false, keepOpen: true, onselect:tags_input_cb, filter: tags_input_filter_duplicates })"
                  >
                </div>
              </td>
              [% IF has_multiple_backends %]
                <th class="text-right px-0">Site</th>
                <td>
                  <input type="text" name="backend" value="[% peer_name(agent) | html %]" class="w-full" onfocus="this.click()" onclick="ajax_search.init(this, 'site', { url: 'agents.cgi?action=json&amp;type=site', emptymsg:'select an existing site', autosubmit:false })" required>
                </td>
              [% ELSE %]
                <td colspan="2"></td>
              [% END %]
              <td colspan="2">
                <div class="flexrow justify-end">
                  <button class="ml-2 pr-1 w-36" onclick="jQuery('#advanced-options').toggleClass('hidden'); return false;">Advanded Options <i class="uil uil-angle-down mr-0"></i></button>
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="8">
                [% has_options = 0; opts = BLOCK %]
                  <span class="text-right w-fit textTH font-semibold self-center" title="if set, device can be offline for given duration, ex: 1d">Offline Threshold</span>
                  <input type="text" name="options.offline" placeholder="1d" value="[% IF agent.exists("settings") && agent.settings.exists("options") && agent.settings.options.exists("offline"); has_options = 1 %][% agent.settings.options.offline | html %][% END %]" class="w-16">
                [% END %]
                <div class="flexrow flex-nowrap gap-x-1[% IF !has_options %] hidden[% END %]" id="advanced-options">
                  [% opts %]
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="8" align="center">
                <div class="flexrow flex-nowrap justify-center gap-x-8">
                  <button class="w-44 js-rescan-btn [% IF checks_num == 0 %] green[% END %]" title="Connect to agent and discover services" onclick="return send_form_in_background_with_callback(this, {action: 'scan'}, scan_callback );"><i class="uil uil-search"></i> Discover Services</button>
                  <i class="uil uil-angle-double-right self-center"></i>
                  [% IF agent.hostname == "new" %]
                  <button class="w-44" onclick="jQuery('.js-radio-new[value=\'on\']').attr('checked', true); return false;">Accept All New Checks</button>
                  [% ELSE %]
                  <button class="w-44 js-preview-btn" name="action" title="Preview object configuration changes" value="save" onClick="previewChanges(this); return false;"><i class="uil uil-lightbulb"></i> Preview Changes</button>
                  [% END %]
                  <i class="uil uil-angle-double-right self-center"></i>
                  <button class="w-44 js-save-btn" name="action" title="Write object configuration" value="save" onClick="saveInitialFormValues()"><i class="uil uil-save"></i> Save Changes</button>
                  <i class="uil uil-angle-double-right self-center"></i>
                  <button class="w-44 js-activate-btn [% IF reload_required %]orange[% END %]" title="Reload core" onclick="return agents_activate(this);"><i class="uil uil-sync"></i> Activate Changes</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="head justify-between" style="flex: 0 0 40px;">
        <div class="grow">
          <input type="text" class="w-32 deletable" id="check_filter" placeholder="filter services..." onkeyup="filterServices(this); return false;" onchange="filterServices(this); return false;">
        </div>
        <span
          class="tabs clickable text-center text-sm w-40 active"
          id="sub_1"
          onclick="set_sub(1)"
          title="New checks are not yet active and created as object."
        >Add New (<span class="js-type-1-size">[% checks.new.size %]</span>)</span>
        <span
          class="tabs clickable text-center text-sm w-40"
          id="sub_2"
          onclick="set_sub(2)"
          title="Active checks are still actively monitored."
        >Active Checks (<span class="js-type-2-size">[% checks.exists.size %]</span>)</span>
        <span
          class="tabs clickable text-center text-sm w-40"
          id="sub_3"
          onclick="set_sub(3)"
          title="Obsolete services are no longer discovered but still exist as service."
        >Obsolete Checks (<span class="js-type-3-size">[% checks.obsolete.size %]</span>)</span>
        <span
          class="tabs clickable text-center text-sm w-40"
          id="sub_4"
          onclick="set_sub(4)"
          title="Disabled checks are not monitored."
        >Unwanted Checks (<span class="js-type-4-size">[% checks.disabled.size %]</span>)</span>
        <div class="grow">
          <div class="w-32">&nbsp;</div>
        </div>
      </div>
      <div id="checksTable" class="h-full overflow-auto">
        <div id="checksTableContent">
          [% PROCESS _check_type ctype="new" sub="sub_1" %]
          [% PROCESS _check_type ctype="exists" sub="sub_2" %]
          [% PROCESS _check_type ctype="obsolete" sub="sub_3" %]
          [% PROCESS _check_type ctype="disabled" sub="sub_4" %]
        </div>
      </div>
    </form>
  </div>

  <div class="w-[350px] hidden xl:block"></div>
</div>

<script>
<!--
function scan_callback(form, success, data, textStatus, jqXHR) {
  btn = jQuery(form).find("DIV.spinner").parents("BUTTON");
  if(!success || (data && data.ok === 0)) {
    var message = "unknown error";
    if(data && data.message) {
      message = data.message;
    }
    if(data && data.err) {
      message = data.err;
    }
    if(!showMessageFromCookie()) {
      thruk_message(1, message);
    }
    if(btn) {
      setBtnError(btn[0], "scan failed: "+message);
    }
    var msg = getXHRerrorMsg("", textStatus, jqXHR);
    if(success) {
      msg = message;
    }
    jQuery("#checksTableContent").html("<div class='text-center textHINT mt-5'>"+msg+"</div>");
    return;
  }

  btn = jQuery(form).find("DIV.spinner").parents("BUTTON");
  if(btn) {
    setBtnNoSpinner(btn[0]);
  }
  updateChecksTable(form);

  jQuery(".js-rescan-btn").removeClass("green");
}

function updateChecksTable(form) {
    var host    = jQuery(form).find("INPUT[name=hostname]").val();
    var backend = jQuery(form).find("INPUT[name=backend]").val();
    var type    = jQuery(form).find("INPUT[name=type]").val();
    var section = jQuery(form).find("INPUT[name=section]").val();
    var tags    = jQuery(form).find("INPUT[name=tags]").val();
    var cloned  = jQuery(form).find("INPUT[name=cloned_from]").val();
    jQuery('#checksTable').html("<div class='spinner'><\/div>");
    var url = "agents.cgi #checksTableContent";
    var data = {
      action:      'edit',
      hostname:    host,
      section:     section,
      tags:        tags,
      backend:     backend,
      cloned_from: cloned,
      type:        type
    };
    jQuery('#checksTable').load(url, data, function(text, status, req) {
      if(status == "error") {
        thruk_message(1, "updating checks failed");
        var msg = getXHRerrorMsg("", status, req);
        jQuery("#checksTable").html("<div class='text-center textHINT mt-5'>"+msg+"</div>");
        updateChecksTotals();
        return;
      }
      updateChecksTotals();
      start_hide_activity_icons_timer();
      if(lastActiveSub) {
        set_sub(lastActiveSub);
      }
      if(pageLoaded) {
        saveInitialFormValues();
      }
    });
}

var totals = {};
function updateChecksTotals() {
  jQuery("TABLE.js-checks > TBODY").each(function(i, tbody) {
    var num = tbody.rows.length;
    jQuery("SPAN.js-type-"+(i+1)+"-size").text(num);
    totals["sub_"+(i+1)] = num;
  });
}


var initial_form_values;
function saveInitialFormValues() {
  initial_form_values = getFormValues();
}

function getFormValues() {
  var formVal = jQuery("INPUT.js-checks").serialize();
  return(formVal);
}

function checkSaveButtonColor() {
  var cur_form_values = getFormValues();
  if(cur_form_values != initial_form_values) {
    jQuery(".js-save-btn").addClass("green");
  } else {
    jQuery(".js-save-btn").removeClass("green");
  }
}

function agents_activate(btn) {
  var form = document.createElement('form');
  form.action = '../r/config/reload';
  var data = { backend: "[% agent.peer_key | html %]", CSRFtoken: CSRFtoken };
  setBtnSpinner(btn);
  var cb = function(form, success, data, textStatus, jqXHR) {
    if(!success) {
      var msg = getXHRerrorMsg("", textStatus, jqXHR, false);
      setBtnError(btn, msg);
      return false;
    }
    if(data && data[0] && !data[0]["failed"]) {
      setBtnSuccess(btn);
      reloadPage();
    } else {
      setBtnError(btn, "reload failed");
      thruk_message(1, "reload failed, please check your logs...\n"+data[0]["output"]);
    }
  };
  submitFormInBackground(form, cb, data);
  return false;
}

jQuery(document).on("click", checkSaveButtonColor);

jQuery(window).on('beforeunload', function(e){
  var cur_form_values = getFormValues();
  if(cur_form_values != initial_form_values) {
    var msg = "Not applied changes will be lost if you leave this page.";
    e.returnValue = msg;
    triggerUnloadTimerSkipNext = true;
    return(msg);
  }
  return;
});

jQuery(document).ready(function() {
  updateChecksTotals();
  // activate first tab with entries
  var found = false;
  jQuery(["sub_1", "sub_2", "sub_3", "sub_4"]).each(function(i, name) {
    if(totals[name] > 0) {
      set_sub(i+1);
      found = true;
      return(false);
    }
    return(true);
  });
  if(!found) {
    set_sub(1);
  }

  pageLoaded = true;
  saveInitialFormValues();
  start_hide_activity_icons_timer();

  /* command line wizard / plugins */
  jQuery('button.js-ip-wzd-button').unbind("click").click(function() {
      var host = jQuery("#hostname").val();
      if(host == undefined) {
          return false;
      }

      jQuery.ajax({
          url: 'conf.cgi',
          data: {
              action:   'json',
              type:     'dig',
              host:      host,
              CSRFtoken: CSRFtoken
          },
          type: 'POST',
          success: function(data) {
            // simply fill if empty
            if(data.address && jQuery("INPUT[name=ip]").val() == "") {
              jQuery("INPUT[name=ip]").val(data.address).effect('highlight', {}, 1000);
              return;
            }

            if(confirm("autofill with resolved addess: "+data.address)) {
              jQuery("INPUT[name=ip]").val(data.address).effect('highlight', {}, 1000);
            }
          },
          error: ajax_xhr_error_logonly
      });
      return false;
  });
});

function previewChanges(btn) {
  overcard({
      'bodyCls': 'p-2',
      'mainCls': 'modalFG min-h-[500px] w-auto m-5',
      'body':     '<div id="preview_popup" class="min-h-40 mx-auto"><div class="flex justify-center min-h-40"><div class="p-2 h-10 w-10 spinner"></div></div><\/div>',
      'caption':  "Preview Changes",
      'minWidth':  800,
      'draggable': true,
      'resizable': true,
      'fixedPos':  true,
      'callback': function(doc) {
        var container = doc.getElementById("overcard");
        element_check_visibility(container);

        send_form_in_background_with_callback(btn, { 'action': 'preview' }, function(form, success, data, textStatus, jqXHR) {
          if(!success) {
            var msg = getXHRerrorMsg("", textStatus, jqXHR, false);
            doc.getElementById("preview_popup").innerHTML = "<div class='text-center textHINT mt-5'>"+msg+"</div>";
            return;
          }
          doc.getElementById("preview_popup").innerHTML = data;
        });
        setBtnReset(btn);
      }
  });

  return false;
}

function filterServices(input) {
  var filter = jQuery(input).val().toLowerCase();
  jQuery("table.js-checks tbody tr").each(function(i, row) {
    var name = jQuery(row).find("th").first().data("name");
    if(!name) {
      return;
    }
    if(matchOrIndex(name, filter, 'i')) {
      jQuery(row).show();
    } else {
      jQuery(row).hide();
    }
  });
}

-->
</script>


[% PROCESS _footer.tt %]
