{{ define "body" }}
    <h3>Manage</h3>
    <p>Here you can manage your LabCA instance. Be careful!</p>

<ul class="nav nav-tabs nav-tabs-sticky">
  {{ if .Standalone }}
  <li class="active">
    <a data-toggle="tab" href="#backend">{{ .Backend }}</a>
  </li>
  {{ else }}
  <li class="active">
    <a data-toggle="tab" href="#system">System</a>
  </li>
  <li class="">
    <a data-toggle="tab" href="#backup">Backup</a>
  </li>
  <li class="">
    <a data-toggle="tab" href="#certs">Certificates</a>
  </li>
  <li class="">
    <a data-toggle="tab" href="#crls">CRLs</a>
  </li>
  <li class="">
    <a data-toggle="tab" href="#config">Config</a>
  </li>
  {{ end }}
  <li class="">
    <a data-toggle="tab" href="#account">Account</a>
  </li>
</ul>

<div class="tab-content">
  {{ if .Standalone }}
  <div class="tab-pane fade active in" id="backend">
  <br/>
    <form role="form">
      <div class="form-group">
        <label>MySQL server (IP address or hostname):</label>
        <input class="form-control non-fluid backend-input" type="text" name="mysql_server" id="mysql_server" value="{{ .MySQLServer }}" required>
        <span class="error backend-error hidden" id="mysqlserver-error"></span>
      </div>
      <div class="form-group">
        <label>MySQL port:</label>
        <input class="form-control non-fluid backend-input" type="text" name="mysql_port" id="mysql_port" value="{{ .MySQLPort }}" required>
        <span class="error backend-error hidden" id="mysqlport-error"></span>
      </div>
      <div class="form-group">
        <label>MySQL database name:</label>
        <input class="form-control non-fluid backend-input" type="text" name="mysql_dbname" id="mysql_dbname" value="{{ .MySQLDBName }}" required>
        <span class="error backend-error hidden" id="mysqldbname-error"></span>
      </div>
      <div class="form-group">
        <label>MySQL username:</label>
        <input class="form-control non-fluid backend-input" type="text" name="mysql_user" id="mysql_user" value="{{ .MySQLUser }}" required>
        <span class="error backend-error hidden" id="mysqluser-error"></span>
      </div>
      <div class="form-group">
        <label>MySQL password:</label>
        <input class="form-control non-fluid backend-input" type="password" name="mysql_passwd" id="mysql_passwd" value="{{ .MySQLPasswd }}" required>
        <span class="error backend-error hidden" id="mysqlpasswd-error"></span>
      </div>
      <br/>

      <div class="form-group">
        <label>Use HTTPS:</label>
        <input type="checkbox" class="use_https" id="use_https" name="use_https" value="https" {{ if .UseHTTPS }}checked{{ end }}></input><br/>
        <span class="error backend-error hidden" id="usehttps-error"></span>
      </div>
      <div class="form-group">
        <label>Certificate file:</label>
        <input class="form-control non-fluid backend-input" type="text" name="cert_path" id="cert_path" value="{{ .CertPath }}" required>
        <span class="error backend-error hidden" id="certpath-error"></span>
      </div>
      <div class="form-group">
        <label>Key file:</label>
        <input class="form-control non-fluid backend-input" type="text" name="key_path" id="key_path" value="{{ .KeyPath }}" required>
        <span class="error backend-error hidden" id="keypath-error"></span>
      </div>

      <div class="form-group">
        <span class="hidden" id="update-backend-result"></span>
        <button class="btn btn-default" type="button" id="update-backend" title="Update the backend settings">Update</button>
      </div>
    </form>
  </div>

  {{ else }}
  <div class="tab-pane fade active in" id="system">
    <br/>
    <div class="row">
      <div class="col-lg-6 col-md-9 col-sm-12">
        <table class="table table-bordered mb15 p48">
          <tbody>
            {{ range $item := .Components }}
            <tr>
              <td class="vmiddle">{{ $item.Name }}</td>
              <td class="vmiddle"{{ if ne $item.TimestampRel "stopped" }} title="{{ $item.Timestamp }}"{{ end }}>
                <span{{ if $item.Class }} class="{{ $item.Class }}"{{ end }}>
                  {{ if ne $item.TimestampRel "stopped" }}Up {{ end }}{{ $item.TimestampRel }}
                </span>
              </td>
              <td class="vmiddle">{{ if or $item.LogURL $item.LogTitle}}<a href="{{ $item.LogURL }}" title="{{ $item.LogTitle }}"><i class="fa fa-fw fa-file"></i></a>{{ end }}</td>
              <td class="vmiddle">
                {{ range $btn := $item.Buttons }}
                <button class="btn btn-outline btn-reg {{ $btn.Class }}" type="button" id="{{ $btn.Id }}" title="{{ $btn.Title }}">{{ $btn.Label }}</button>
                {{ end }}
                {{ if eq $item.Name "LabCA Application" }}
                <br/>
                <button class="btn btn-outline btn-wide btn-success mt5" type="button" id="version-check" title="Check if there is a newer version available">Check for updates</button>
                <span id="update-checked-span">
                    <br/>
                    Last checked: <span id="update-last-checked" title="{{ $.UpdateChecked }}">{{ $.UpdateCheckedRel }}</span>
                </span>
                {{ end }}
              </td>
            </tr>
            {{ end }}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="backup">
    <br/>
    <div class="row">
      <div class="col-lg-6 col-md-9 col-sm-12">
        <table class="table table-bordered mb15 p48">
          <tbody id="backups-tbody">
            {{ range .BackupFiles }}
            <tr>
              <td class="vmiddle"><a href="/admin/backup/{{.}}" class="backupdl">{{.}}</a></td>
              <td class="vmiddle">
                <button class="btn btn-outline btn-warning backup-restore" type="button" title="Restore this backup">Restore</button>
                <button class="btn btn-outline btn-danger backup-delete" type="button" title="Delete this backup">Delete</button>
              </td>
            </tr>
            {{ end }}
          </tbody>
        </table>
        <button class="btn btn-outline btn-success" type="button" id="backup-now" title="Create system backup now">Backup Now</button>
        <button class="btn btn-default" type="button" id="backup-upload" title="Upload a backup .tgz file downloaded earlier">Upload File</button>
        <span class="hidden" id="backup-result"></span>
      </div>
      <div class="col-lg-6 col-md-9 col-sm-12">
        <div class="well">
          Backups are automatically created once a week. Here you can manually create extra backups and download, delete
          or restore a selected backup. You can also upload a backup that was downloaded earlier.<br/>
          After restoring the services will be <b>automatically restarted</b>.<br/>
          Automatic backups are removed after one month, manual backups are kept until manually deleted.
        </div>
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="certs">
    <br/>
    <div class="row">
      <div class="col-lg-9 col-md-12">
        <table class="table table-bordered mb15 p48">
          <tbody>
            <tr>
              <th>Subject</th>
              <th></th>
              <th>Type</th>
              <th>Active</th>
              <th></th>
            </tr>
            {{ range $item := .CertificateChains }}
            <tr>
              <td class="vmiddle">
                {{ $item.RootCert.Subject }}
                <a href="#" title="View {{ $item.RootCert.BaseName }} details" id="show-{{ $item.RootCert.BaseName }}"><i class="fa fa-fw fa-eye"></i></a>
              </td>
              <td class="vmiddle">
                <a href="/certs/{{ $item.RootCert.BaseName }}.pem" title="Download this certificate">download</a>
              </td>
              <td class="vmiddle">{{ $item.RootCert.KeyType }}</td>
              <td class="vmiddle"></td>
              <td class="vmiddle">
                <button class="btn btn-outline btn-reg btn-success export-cert-key" type="button" title="Export this certificate and key" data-name="{{ $item.RootCert.BaseName }}" data-subject="{{ $item.RootCert.Subject }}">Export</button>
                <button class="btn btn-outline btn-reg btn-warning renew-cert" type="button" title="Generate new version with extended lifetime" data-name="{{ $item.RootCert.BaseName }}" data-rootname="{{ $item.RootCert.BaseName }}" data-subject="{{ $item.RootCert.Subject }}" data-keytype="{{ $item.RootCert.KeyType }}" data-rootsubject="{{ $item.RootCert.Subject }}" data-notbefore="{{ $item.RootCert.NotAfter }}" data-isroot="true">Renew</button>
                <!--
                <button class="btn btn-outline btn-new-issuer btn-warning new-issuer-cert" type="button" title="Generate new Issuer Certificate under this Root" data-root="{{ $item.RootCert.BaseName }}" data-rootsubject="{{ $item.RootCert.Subject }}">New Issuer</button>
                <button class="btn btn-outline btn-reg btn-danger delete-cert hidden" type="button" title="Delete this certificate" data-name="{{ $item.RootCert.BaseName }}">Delete</button>
                -->
              </td>
            </tr>
            {{ range $subitem := $item.IssuerCerts }}
            <tr>
              <td class="vmiddle">
                &nbsp;&#9494;&nbsp; {{ $subitem.Subject }}
                <a href="#" title="View {{ $subitem.BaseName }} details"><i class="fa fa-fw fa-eye" id="show-{{ $subitem.BaseName }}"></i></a>
              </td>
              <td class="vmiddle">
                <a href="/certs/{{ $subitem.BaseName }}.pem" title="Download this certificate">download</a>
              </td>
              <td class="vmiddle">{{ $subitem.KeyType }}</td>
              <td class="vmiddle center"><input type="radio" id="active-{{ $subitem.BaseName }}" name="issue-active" value="{{ $subitem.BaseName }}" title="Use this certificate for issueing leave certificates" {{ if $subitem.ActiveIssuer }}data-orig="true" checked{{ end }}/></td>
              <td class="vmiddle">
                <button class="btn btn-outline btn-reg btn-success export-cert-key" type="button" title="Export this certificate and key" data-name="{{ $subitem.BaseName }}" data-subject="{{ $subitem.Subject }}">Export</button>
                <button class="btn btn-outline btn-reg btn-warning renew-cert" type="button" title="Generate new version with extended lifetime" data-name="{{ $subitem.BaseName }}" data-rootname="{{ $item.RootCert.BaseName }}" data-subject="{{ $subitem.Subject }}" data-keytype="{{ $subitem.KeyType }}" data-rootsubject="{{ $item.RootCert.Subject }}" data-notbefore="{{ $subitem.NotAfter }}" data-notafter="{{ $item.RootCert.NotAfter }}" data-isroot="false">Renew</button>
                <!--
                <button class="btn btn-outline btn-reg btn-danger delete-cert" type="button" title="Delete this certificate" data-name="{{ $subitem.BaseName }}">Delete</button>
                -->
              </td>
            </tr>
            {{ end }}
            {{ end }}
          </tbody>
        </table>
        <!--
        <button class="btn btn-outline btn-6em btn-warning new-root-cert" type="button" title="Generate new Root Certificate">New Root</button>
        -->
      </div>
    </div>
  </div>

  <div class="tab-pane fade" id="crls">
    <br/>
    <div class="row">
      <div class="col-lg-3 col-md-6 col-sm-8">
        <table class="table table-bordered mb15 p48">
          <tbody>
            <tr>
              <td class="vmiddle">Root CRL</td>
              <td class="vmiddle">
                <button class="btn btn-outline btn-success mt5" type="button" id="gen-root-crl" title="Generate root CRL now (requires Root CA key)">Generate</button>
              </td>
            </tr>
            <tr>
              <td class="vmiddle">Issuer CRL</td>
              <td class="vmiddle">
                <button class="btn btn-outline btn-success mt5" type="button" id="gen-issuer-crl" title="Generate issuer CRL now">Generate</button>
              </td>
            </tr>
          </tbody>
        </table>
        <span class="hidden" id="root-crl-result"></span>
        <span class="hidden" id="issuer-crl-result"></span>
      </div>
    </div>
    <form role="form">
      <div class="form-group">
        <label for="crl-interval">CRL update interval:</label>
        <input class="form-control non-fluid" type="text" id="crl-interval" name="crl-interval" value="{{ .CRLInterval }}" required>
        <p>The Issuer CRL will be automatically generated in a regular interval.</p>
      </div>
      <div class="form-group">
        <button class="btn btn-default" type="button" id="update-crl-interval" title="Update the system configuration">Update</button>
        <span class="hidden" id="crl-interval-result"></span>
      </div>
    </form>
  </div>

  <div class="tab-pane fade" id="config">
    <br/>
    <form role="form">
      <div class="form-group">
        <label for="fqdn">FQDN for the PKI host:</label>
        <input class="form-control non-fluid" type="text" id="fqdn" name="fqdn" value="{{ .Fqdn }}" required>
        <span class="hidden" id="fqdn_warning">&nbsp;<img src="static/img/warning.png"> Are you sure? This differs from the address you are using right now!<br/></span>
        <span class="error config-error hidden" id="fqdn-error"></span>
      </div>
      <div class="form-group">
        <label for="organization">Organization name:</label>
        <input class="form-control non-fluid" type="text" id="organization" name="organization" value="{{ .Organization }}" required>
        <span class="error config-error hidden" id="organization-error"></span>
      </div>
      <div class="form-group">
        <label for="webtitle">Title on web pages (e.g. 'Internal ACME CA'):</label>
        <input class="form-control non-fluid" type="text" id="webtitle" name="webtitle" value="{{ .WebTitle }}">
        <span class="error config-error hidden" id="webtitle-error"></span>
      </div>
      <div class="form-group">
        <label for="dns">Internal DNS server to use:</label>
        <input class="form-control non-fluid" type="text" id="dns" name="dns" value="{{ .DNS }}" required>
        <span class="error config-error hidden" id="dns-error"></span>
      </div>

      <div class="form-group">
        <label>Domain mode:</label><br/>
        <span class="error config-error hidden" id="domainmode-error"></span>
        <input type="radio" id="lockdown" name="domain_mode" value="lockdown" {{ if eq .DomainMode "lockdown"}}checked{{ end }}/> Lockdown to only these domains (one per line):<br/>
        <textarea class="form-control non-fluid" rows="3" cols="24" id="lockdown_domains" name="lockdown_domains">{{ .LockdownDomains }}</textarea>
        <span class="error config-error hidden" id="lockdowndomains-error"></span>
        <br/>

        <input type="radio" id="whitelist" name="domain_mode" value="whitelist" {{ if eq .DomainMode "whitelist"}}checked{{ end }}/> Next to all official domains, also allow these domains (whitelist; one per line):<br/>
        <textarea class="form-control non-fluid" rows="3" cols="24" id="whitelist_domains" name="whitelist_domains">{{ .WhitelistDomains }}</textarea>
        <span class="error config-error hidden" id="whitelistdomains-error"></span>
        <br/>

        <input type="radio" id="standard" name="domain_mode" value="standard" {{ if eq .DomainMode "standard"}}checked{{ end }}/> Standard - any official domains
      </div>

      <div class="form-group" id="ld_options">
        <label>Lockdown options:</label><br/>
        <input type="checkbox" id="ld_public_contacts" name="ld_public_contacts" value="true" {{ if .LDPublicContacts }}checked{{ end }}></input>
        &nbsp;Still allow all public domain names in contact email addresses when creating new ACME accounts
      </div>

      <div class="form-group">
        <label>Extended timeout:</label><br/>
        <input type="checkbox" class="extended_timeout" id="extended_timeout" value="extend" {{ if .ExtendedTimeout }}checked{{ end }}></input>
        &nbsp;If you see timeout related errors on the Dashboard / Audit Log, try checking this box.
      </div>
      <div class="form-group" id="domain_mode_warning">
        <img src="static/img/warning.png"> Are you sure? This facilitates man-in-the-middle attacks!
      </div>
      <div class="form-group">
        <span class="hidden" id="update-config-result"></span>
        <button class="btn btn-default" type="button" id="update-config" title="Update the system configuration">Update</button>
      </div>
    </form>
  </div>

  {{ end }}

  <div class="tab-pane fade" id="account">
  <br/>
    <form role="form">
      <div class="form-group">
        <label>User name:</label>
        <input class="form-control non-fluid account-input" type="text" name="username" id="username" value="{{ .Name }}" required>
        <span class="error account-error hidden" id="username-error"></span>
      </div>
      <div class="form-group">
        <label>Email address:</label>
        <input class="form-control non-fluid account-input" type="email" name="accemail" id="accemail" value="{{ .Email }}" required>
        <span class="error account-error hidden" id="email-error"></span>
      </div>
      <div class="form-group">
        <label>Change password:</label>
        <input class="form-control non-fluid" type="password" name="new-password" id="new-password">
        <span class="fa fa-eye vizpwd"></span>
        <div class="progress mb5" style="height: 3px" id="password-strength">
          <div class="progress-bar strength-none" role="progressbar" style="width: 0px" aria-valuenow="1" aria-valuemin="0" aria-valuemax="4"></div>
        </div>
        <span class="error account-error hidden" id="newpassword-error"></span>
      </div>
      <div class="form-group">
        <label>Confirm new password:</label>
        <input class="form-control non-fluid" type="password" name="confirm" id="confirm">
        <span class="fa fa-eye vizpwd"></span>
        <span class="error account-error hidden" id="confirm-error"></span>
      </div>
      <div class="form-group">
        <label>Current password (required):</label>
        <input class="form-control non-fluid account-input" type="password" name="password" id="password" required>
        <span class="error account-error hidden" id="password-error"></span>
      </div>
      <div class="form-group">
        <span class="hidden" id="update-account-result"></span>
        <button class="btn btn-default" type="button" id="update-account" title="Update the admin account" disabled>Update</button>
      </div>
    </form>
  </div>
</div>

<span class="hidden" id="request-base">{{ .RequestBase }}</span>

<div id="modal-spinner" class="modal fade bd-modal-lg" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content" style="width: 48px">
      <img id="manage-spinner" src="static/img/spinner.gif" height="36">
    </div>
  </div>
</div>

<div id="modal-root-key" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-root-key-content">
      <h4>Root Key Required</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <p>Please provide the Root CA key file in PEM format. As soon as we are done with it, it will be removed from the system again.</p>
      <span id="modal-show-root-key-subject" class="hidden">Root subject: <span id="modal-root-key-subject"></span><br></span>
      <textarea class="form-control" id="modal-rootkey" rows="10" cols="80" required></textarea>
      <div class="form-group">
        <label for="modal-rootpassphrase">Passphrase (optional):</label>
        <input class="form-control" type="password" id="modal-rootpassphrase" value="">
      </div>
      <span class="error" id="modal-root-key-error" style="display: none;"></span><br/>
      <input class="btn btn-default btn-reg" value="Upload" id="modal-root-key-upload"/>
      <input class="btn btn-default btn-reg hidden" value="Upload" id="modal-root-key-renew"/>
      <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-rootkey">Cancel</button>
    </div>
  </div>
</div>

<div id="modal-crl" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-crl-content">
      <h4>CRL</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <p>Please provide the CRL for the Root CA.</p>
      <textarea class="form-control" id="modal-crl-val" rows="10" cols="80" required>{{ .CRL }}</textarea>
      <span class="error" id="modal-crl-error" style="display: none;"></span><br/>
      <input class="btn btn-default btn-reg" value="OK" id="modal-crl-done"/>
      <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-crl">Cancel</button>
    </div>
  </div>
</div>

<div id="modal-backup" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-backup-content">
      <h4>Upload Backup File</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <p>Please select a backup (.tgz) file that was downloaded from LabCA earlier.</p>
      <form enctype="multipart/form-data" id="modal-backup-form" method="POST">
        <input type="hidden" name="action" value="backup-upload">
        <input class="form-control non-fluid" type="file" id="backup-file" name="backup-file" required>
        <span class="error" id="modal-backup-error" style="display: none;"></span><br/>
        <input class="btn btn-default btn-reg" value="Upload" id="modal-backup-done"/>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-backup">Cancel</button>
      </form>
    </div>
  </div>
</div>

{{ range $item := .CertificateChains }}
<div id="modal-{{ $item.RootCert.BaseName }}" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-{{ $item.RootCert.BaseName }}-content">
      <h4>{{ $item.RootCert.Subject }}</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <pre>{{ $item.RootCert.Details }}</pre>
      <button type="button" class="btn btn-default btn-modal-dismiss" data-dismiss="modal">Close</button>
    </div>
  </div>
</div>
{{ range $subitem := $item.IssuerCerts }}
<div id="modal-{{ $subitem.BaseName }}" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-{{ $subitem.BaseName }}-content">
      <h4>{{ $subitem.Subject }} Details</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <pre>{{ $subitem.Details }}</pre>
      <button type="button" class="btn btn-default btn-modal-dismiss" data-dismiss="modal">Close</button>
    </div>
  </div>
</div>
{{ end }}
{{ end }}

<div id="modal-export" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-export-content">
      <h4>Export certificate + key</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <h5><span id="modal-export-subject"></span></h5>
      <form enctype="multipart/form-data" id="modal-export-form" method="POST">
        <input type="hidden" name="export-certname" id="export-certname">
        <div class="form-group">
          <label for="export-pfx">Export format:</label><br/>
          <input type="radio" class="export-rd" id="export-pfx" name="export-type" value="pfx" checked/> .pfx (PKCS#12) file<br/>
          <input type="radio" class="export-rd" id="export-zip" name="export-type" value="zip"/> .zip archive (less secure)<br/>
        </div>
        <div class="form-group">
          <label for="export-pwd">Export file password (twice):</label>
          <input class="form-control non-fluid" type="password" id="export-pwd" name="export-pwd" required/>
          <span class="fa fa-eye vizpwd"></span>
          <span class="error hidden" id="export-pwd-err"></span>
          <input class="form-control non-fluid" type="password" id="export-pwd2" name="export-pwd2" required/>
          <span class="fa fa-eye vizpwd"></span>
          <span class="error hidden" id="export-pwd2-err"></span>
        </div>
        <span class="error" id="modal-export-error" style="display: none;"></span><br/>
        <a id="export-target" style="display: none"></a>
        <input class="btn btn-default btn-reg" value="Export" id="modal-export-done"/>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-export">Cancel</button>
      </form>
    </div>
  </div>
</div>

<div id="modal-leaves" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-leaves-content">
      <h4>Are you sure?</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <form enctype="multipart/form-data" id="modal-leaves-form" method="POST">
        <input type="hidden" id="new-active-issuer" name="new-active-issuer">
        <span id="want-new-active-issuer" class="hidden">&#x2022; Change the active issuer certificate<br/></span>
        <span class="error" id="modal-leaves-error" style="display: none;"></span><br/>
        <input class="btn btn-default btn-reg btn-warning btn-6em" value="Change" id="modal-leaves-done"/>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-leaves">Cancel</button>
      </form>
    </div>
  </div>
</div>

<div id="modal-renew" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content modal-renew-content">
      <h4>Renew CA</h4>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span>&times;</span></button>
      <form enctype="multipart/form-data" id="modal-renew-form" method="POST">
        <input type="hidden" id="modal-renew-cert" name="modal-renew-cert">
        <input type="hidden" id="renew-rootcert" name="renew-rootcert">
        <input type="hidden" id="renew-rootsubject" name="renew-rootsubject">
        Subject: <span id="renew-subject"></span><br>
        Key Type: <span id="renew-keytype"></span><br><br>
        Current end date: <span id="renew-current-enddate"></span><br>
        <span id="renew-show-root-enddate" class="hidden">Root end date: <span id="renew-root-enddate"></span><br></span>
        <br>

        <label>New validity:</label>
        <input class="form-control non-fluid form-small-inline" type="text" name="renew-numdays" id="renew-numdays" required> days<br>
        <span class="error backend-error hidden" id="renew-numdays-error"></span><br>
        New end date: <span id="renew-new-enddate"></span><br>

        <span class="error" id="modal-renew-error" style="display: none;"></span><br/>
        <input class="btn btn-default btn-reg btn-warning" value="Renew" id="modal-renew-done"/>
        <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-renew">Cancel</button>
      </form>
    </div>
  </div>
</div>
{{end}}

{{ define "tail" }}
    <script type="text/javascript" src="static/js/zxcvbn.js"></script>
    <script type="text/javascript" src="static/js/pwdux.js"></script>
    <script type="text/javascript" src="static/js/jquery.stickytabs.js"></script>
    <script type="text/javascript" src="static/js/jquery.form.min.js"></script>
    <script type="text/javascript" src="static/js/bootstrap-dialog.min.js"></script>
    <script>
        $(function() {
            $('.nav-tabs-sticky').stickyTabs();

            $('#modal-backup-form').ajaxForm();
            $('#modal-export-form').ajaxForm();
            $('#modal-leaves-form').ajaxForm();
            $('#modal-renew-form').ajaxForm();

            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                positionFooter();
            });

            $("ul.nav").click(function() {
                setTimeout(function() {
                    $(window).resize();

                    pwduxInit('#password-strength', '#new-password');
                }, 250);
            });

            $(".backupdl").click(function(evt) {
                if (!window.confirm("WARNING: this backup file contains the private keys and other sensitive data in unprotected form. You should be very careful where you store it. Do you want to continue?")) {
                    return false;
                }
            });

            {{ range $item := .CertificateChains }}
            $("#show-{{ $item.RootCert.BaseName }}").click(function(evt) {
                $('#modal-{{ $item.RootCert.BaseName }}').modal('show');
                return false;
            });
            {{ range $subitem := $item.IssuerCerts }}
            $("#show-{{ $subitem.BaseName }}").click(function(evt) {
                $('#modal-{{ $subitem.BaseName }}').modal('show');
                return false;
            });
            {{ end }}
            {{ end }}

            function leave_issuer_changed() {
                iss_active = "";
                iss_active_changed = false;

                $('input[type=radio][name=issue-active]').each(function() {
                    if ($(this).prop('checked') && !$(this).data('orig')) {
                        iss_active = $(this).val();
                        iss_active_changed = true;
                    }
                });

                if (iss_active_changed) {
                    $("#new-active-issuer").val(iss_active);
                    $("#want-new-active-issuer").removeClass("hidden").show();

                    $('#modal-leaves').modal('show');
                } else {
                    $("#want-new-active-issuer").hide();
                }

                return false;
            }

            $('input[type=radio][name=issue-active]').change(function() {
                return leave_issuer_changed();
            });

            $(".btn").click(function(evt) {
                $('#modal-spinner').modal('show');
                if ($(evt.target).hasClass('btn-warning') || $(evt.target).hasClass('btn-danger')) {
                    if ($(evt.target).attr("id") != "modal-leaves-done" && $(evt.target).attr("id") != "modal-renew-done" && $(evt.target).attr("id") != "modal-newcert-done" &&
                        !$(evt.target).hasClass('renew-cert') && !$(evt.target).hasClass('new-issuer-cert') && !$(evt.target).hasClass('new-root-cert')) {
                        if (!window.confirm("Are you sure?")) {
                            $('#modal-spinner').modal('hide');
                            return false;
                        }
                    }
                }
                $(evt.target).blur();
                $("#backup-result").hide();
                $("#export-pwd-err").hide();
                $("#export-pwd2-err").hide();
                $("#cert-export-err").hide();
                $(".account-error").hide();
                $(".backend-error").hide();
                $("#update-account-result").hide();
                $(".config-error").hide();
                $("#update-config-result").hide();
                $("#root-crl-result").hide();
                $("#issuer-crl-result").hide();
                $("#crl-interval-result").hide();
                $("#modal-backup-error").hide();
                $("#modal-export-error").hide();
                $("#modal-leaves-error").hide();
                $("#modal-renew-error").hide();

                if ( $(evt.target).attr("id") == "backup-now") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully created backup";
                            $("#backup-result").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");

                            $("#backups-tbody").append('<tr><td class="vmiddle"><a href="/admin/backup/' + data.Message + '" class="backupdl">' + data.Message + '</a></td><td class="vmiddle"></td></tr>');

                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);

                        } else {
                            $("#backup-result").removeClass("hidden").removeClass("success").show().text(data.Message).addClass("error");
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#backup-result").removeClass("hidden").removeClass("success").show().text(err).addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "backup-upload") {
                    $('#modal-spinner').modal('hide');
                    $('#modal-backup').modal('show');
                    return false;

                } else if ( $(evt.target).attr("id") == "modal-backup-done") {
                    if ($("#backup-file").val() == "" || !$("#backup-file").val().match(/\.tgz$/)) {
                        $('#modal-spinner').modal('hide');
                        $("#modal-backup-error").removeClass("hidden").removeClass("success").show().text("Please provide a backup file").addClass("error");
                        return false;
                    } else {
                        $("#modal-backup-error").hide();

                        $("#modal-backup-form").ajaxSubmit({
                            method: "POST",
                            success: function(data)  {
                                $('#modal-spinner').modal('hide');
                                if (data.Success) {
                                    var msg = "Successfully uploaded backup";
                                    $("#backup-result").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");
                                    $("#backups-tbody").append('<tr><td class="vmiddle"><a href="/admin/backup/' + data.Message + '" class="backupdl">' + data.Message + '</a></td><td class="vmiddle"></td></tr>');
                                    $('#modal-backup').modal('hide');

                                    setTimeout(function() {
                                        window.location.reload();
                                    }, 2000);

                                } else {
                                    $("#modal-backup-error").removeClass("hidden").removeClass("success").show().text(data.Message).addClass("error");
                                }
                            },
                            error: function(xhr, status, err) {
                                $('#modal-spinner').modal('hide');
                                $("#modal-backup-error").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                            }
                        })
                    }

                } else if ( $(evt.target).hasClass("backup-restore") ) {
                    var name = $(this).parent().parent().children().first().text();

                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: "backup-restore",
                            backup: name,
                        },
                    })
                    .done(function(data) {
                        if (data.Success) {
                            var msg = "Successfully restored backup, restarting server now...";
                            setTimeout(function() {
                                window.location.reload();
                            }, 10000);
                            $("#backup-result").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");

                        } else {
                            $("#backup-result").removeClass("hidden").removeClass("success").show().text(data.Message).addClass("error");
                        }
                    })
                    .fail(function(xhr, status, err) {
                        if (status == 502 || err == "Bad Gateway") {
                            setTimeout(function() {
                                $('#modal-spinner').modal('hide');
                                $("#backup-result").removeClass("hidden").removeClass("error").show().html("Restarted control container.<br/>").addClass("success");
                            }, 2000);
                        } else {
                            $('#modal-spinner').modal('hide');
                            $("#backup-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                        }
                    });

                } else if ( $(evt.target).hasClass("backup-delete") ) {
                    var row = $(this).parent().parent();
                    var name = row.children().first().text();

                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: "backup-delete",
                            backup: name,
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully removed backup file";
                            $("#backup-result").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");
                            row.hide();

                        } else {
                            $("#backup-result").removeClass("hidden").removeClass("success").show().text(data.Message).addClass("error");
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#backup-result").removeClass("hidden").removeClass("success").show().text(err).addClass("error");
                    });

                } else if ($(evt.target).attr("id") == "modal-export-done") {
                    type = ($("#export-zip").prop('checked') ? "zip" : ($("#export-pfx").prop('checked') ? "pfx" : "none"));

                    if ($("#export-pwd").val().length < 4) {
                        $('#modal-spinner').modal('hide');
                        $("#export-pwd-err").removeClass("hidden").show().text("Password needs to be at least 4 characters!");
                    } else if ($("#export-pwd").val() != $("#export-pwd2").val()) {
                        $('#modal-spinner').modal('hide');
                        $("#export-pwd2-err").removeClass("hidden").show().text("Passwords are not the same!");
                    } else {
                        var req = new XMLHttpRequest();
                        req.open("POST", window.location.href, true);
                        req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                        req.responseType = "blob";

                        req.onload = function (event) {
                            $('#modal-spinner').modal('hide');

                            if (event.currentTarget.status == 200) {
                                var blob = req.response;
                                var fileName = null;
                                var contentType = req.getResponseHeader("content-type");

                                // IE/EDGE seems not returning some response header
                                if (req.getResponseHeader("content-disposition")) {
                                    var contentDisposition = req.getResponseHeader("content-disposition");
                                    fileName = contentDisposition.substring(contentDisposition.indexOf("=") + 1);
                                } else {
                                    fileName = "unnamed." + contentType.substring(contentType.indexOf("/") + 1);
                                }

                                if (window.navigator.msSaveOrOpenBlob) {
                                    // Internet Explorer
                                    window.navigator.msSaveOrOpenBlob(new Blob([blob], { type: contentType }), fileName);
                                } else {
                                    var el = document.getElementById("export-target");
                                    el.href = window.URL.createObjectURL(blob);
                                    el.download = fileName;
                                    el.click();
                                }

                                $('#modal-export').modal('hide');

                            } else if (event.currentTarget.status == 400 || event.currentTarget.statusText == "Bad Request") {
                                $("#modal-export-error").removeClass("hidden").show().text("Key is not extractable from the HSM!");
                            } else {
                                $("#modal-export-error").removeClass("hidden").show().text("Backend returned: " + event.currentTarget.statusText);
                            }
                        };

                        req.onerror = function (event) {
                            $('#modal-spinner').modal('hide');
                            $("#modal-export-error").removeClass("hidden").show().text("Error communicating with backend server");
                        };

                        req.send("action=cert-export&certname=" + $("#export-certname").val() + "&type=" + type + "&export-pwd=" + $("#export-pwd").val());
                    }

                } else if ( $(evt.target).attr("id") == "update-account") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                            username: $("#username").val(),
                            email: $("#accemail").val(),
                            password: $("#password").val(),
                            confirm: $("#confirm").val(),
                            "new-password": $("#new-password").val(),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully updated account.";
                            if ($("#new-password").val()) {
                                msg += " Please <a href=\"" + $("#request-base").text() + "/login\">login</a> again with your new password.";

                                setTimeout(function() {
                                    window.location.reload();
                                }, 5000);
                            }
                            msg += "<br/>";
                            $("#update-account-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                        } else {
                            jQuery.each(data.Errors, function(nm, val) {
                                $("#" + nm.toLowerCase() + "-error").removeClass("hidden").show().text(val);
                            });
                        }

                        $("#new-password").val("");
                        $("#confirm").val("");
                        $("#password").val("");
                        $("#update-account").prop('disabled', true);
                        pwduxReset('#password-strength');

                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#update-account-result").removeClass("hidden").removeClass("success").show().text(err).addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "update-backend") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                            backend: "{{ .Backend }}",
                            mysql_server: $("#mysql_server").val(),
                            mysql_port: $("#mysql_port").val(),
                            mysql_dbname: $("#mysql_dbname").val(),
                            mysql_user: $("#mysql_user").val(),
                            mysql_passwd: $("#mysql_passwd").val(),
                            use_https: ($("#use_https").prop("checked") ? "https" : "no"),
                            cert_path: $("#cert_path").val(),
                            key_path: $("#key_path").val(),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully updated configuration.<br/>";
                            $("#update-backend-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);

                        } else {
                            jQuery.each(data.Errors, function(nm, val) {
                                nm = nm.toLowerCase();
                                if (nm == "backendupdate") {
                                    $("#update-backend-result").removeClass("hidden").removeClass("success").show().html(val + "<br/>").addClass("error");
                                } else {
                                    $("#" + nm + "-error").removeClass("hidden").show().text(val);
                                }
                            });
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#update-backend-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "update-crl-interval") {
                    if ($("#crl-interval").val() == "") {
                        $('#modal-spinner').modal('hide');
                        $("#crl-interval-result").removeClass("hidden").removeClass("success").show().text("Please provide an interval value").addClass("error");
                        return false;
                    } else {
                        $.ajax(window.location.href, {
                            method: "POST",
                            data: {
                                action: $(evt.target).attr("id"),
                                crl_interval: $("#crl-interval").val(),
                            },
                        })
                        .done(function(data) {
                            $('#modal-spinner').modal('hide');

                            if (data.Success) {
                                var msg = "Successfully updated configuration and restarted Boulder (ACME).<br/>";
                                $("#crl-interval-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                            } else {
                                $("#crl-interval-result").removeClass("hidden").removeClass("success").show().text(data.Errors["CRLInterval"]).addClass("error");
                            }
                        })
                        .fail(function(xhr, status, err) {
                            $('#modal-spinner').modal('hide');
                            if (status == 502 || err == "Bad Gateway") {
                                $("#crl-interval-result").removeClass("hidden").removeClass("error").show().html("Restarted Boulder (ACME).<br/>").addClass("success");
                            } else {
                                $("#crl-interval-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                            }
                        });
                    }

                } else if ( $(evt.target).attr("id") == "update-config") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                            fqdn: $("#fqdn").val(),
                            organization: $("#organization").val(),
                            webtitle: $("#webtitle").val(),
                            dns: $("#dns").val(),
                            domain_mode: ($("#standard").prop('checked') ? 'standard' : ($("#whitelist").prop('checked') ? 'whitelist' : 'lockdown')),
                            lockdown_domains: $("#lockdown_domains").val(),
                            whitelist_domains: $("#whitelist_domains").val(),
                            ld_public_contacts: $("#ld_public_contacts").prop("checked"),
                            extended_timeout: $("#extended_timeout").prop("checked"),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully updated configuration.<br/>";
                            $("#update-config-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);

                        } else {
                            jQuery.each(data.Errors, function(nm, val) {
                                nm = nm.toLowerCase();
                                if (nm == "domainmode" || nm == "lockdowndomains" || nm == "whitelistdomains") {
                                    $("#" + nm + "-error").removeClass("hidden").show().html(val + "<br/>");
                                } else if (nm == "configupdate") {
                                    $("#update-config-result").removeClass("hidden").removeClass("success").show().html(val + "<br/>").addClass("error");
                                } else {
                                    $("#" + nm + "-error").removeClass("hidden").show().text(val);
                                }
                            });
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#update-config-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "version-check") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            if (data.UpdateAvailable) {
                                var notes = "<span class=\"rel-notes-title\">RELEASE NOTES</span><br/><br/>";
                                jQuery.each(data.Versions, function(idx, val) {
                                    notes += "<span class=\"rel-notes-title\">" + val + "</span><br/>"
                                    notes += "<span>" + data.Descriptions[idx] + "</span><br/><br/>"
                                });
                                BootstrapDialog.show({
                                    title: 'New version available!',
                                    message: notes,
                                    buttons: [{
                                        label: 'OK',
                                        cssClass: 'btn-outline btn-success',
                                        action: function(dialogRef){
                                            dialogRef.close();
                                        }
                                    }]
                                });
                            } else {
                                BootstrapDialog.show({
                                    title: 'No new version',
                                    message: 'There is currently no newer version available.',
                                    buttons: [{
                                        label: 'OK',
                                        cssClass: 'btn-outline btn-success',
                                        action: function(dialogRef){
                                            dialogRef.close();
                                        }
                                    }]
                                });
                            }
                            $("#update-last-checked").attr("title", data.UpdateChecked)
                            $("#update-last-checked").text(data.UpdateCheckedRel)

                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                    });

                } else if ( $(evt.target).attr("id") == "gen-issuer-crl") {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully generated Issuer CRL.<br/>";
                            $("#issuer-crl-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                        } else {
                            $("#issuer-crl-result").removeClass("hidden").removeClass("success").show().text(data.Errors["CRL"]).addClass("error");
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#issuer-crl-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "gen-root-crl") {
                    $('#modal-root-key').modal('hide');
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                        },
                    })
                    .done(function(data) {
                        $('#modal-spinner').modal('hide');

                        if (data.Success) {
                            var msg = "Successfully generated Root CRL.<br/>";
                            $("#root-crl-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                        } else if (data.Errors["CRL"] == "NO_ROOT_KEY") {
                            $('#modal-root-key').modal('show');
                            return false;

                        } else {
                            $("#root-crl-result").removeClass("hidden").removeClass("success").show().text(data.Errors["CRL"]).addClass("error");
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#root-crl-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                    });

                } else if ( $(evt.target).attr("id") == "modal-root-key-upload") {
                    if ($("#modal-rootkey").val() == "") {
                        $('#modal-spinner').modal('hide');
                        $("#modal-root-key-error").show().text("Please provide the root key");
                        return false;
                    } else {
                        $('#modal-root-key').modal('hide');
                        $("#modal-root-key-error").hide();
                        $.ajax(window.location.href, {
                            method: "POST",
                            data: {
                                action: 'gen-root-crl',
                                rootkey: $("#modal-rootkey").val(),
                                rootpassphrase: $("#modal-rootpassphrase").val(),
                            },
                        })
                        .done(function(data) {
                            $('#modal-spinner').modal('hide');
                            $('.modal-backdrop').remove();

                            if (data.Success) {
                                var msg = "Successfully generated Root CRL.<br/>";
                                $("#root-crl-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                            } else if (data.Errors["CRL"] == "NO_ROOT_KEY") {
                                $('#modal-root-key').modal('show');
                                return false;

                            } else {
                                $("#root-crl-result").removeClass("hidden").removeClass("success").show().text(data.Errors["CRL"]).addClass("error");
                            }
                        })
                        .fail(function(xhr, status, err) {
                            $('#modal-spinner').modal('hide');
                            $("#root-crl-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                        });
                    }

                } else if ( $(evt.target).attr("id") == "upload-root-crl") {
                    $('#modal-spinner').modal('hide');
                    $('#modal-crl').modal('show');
                    return false;

                } else if ( $(evt.target).attr("id") == "modal-crl-done") {
                    if ($("#modal-crl-val").val() == "") {
                        $('#modal-spinner').modal('hide');
                        $("#modal-crl-error").show().text("Please provide CRL content");
                        return false;
                    } else {
                        $('#modal-crl').modal('hide');
                        $("#modal-crl-error").hide();
                        $.ajax(window.location.href, {
                            method: "POST",
                            data: {
                                action: 'upload-root-crl',
                                crl: $("#modal-crl-val").val(),
                            },
                        })
                        .done(function(data) {
                            $('#modal-spinner').modal('hide');

                            if (data.Success) {
                                var msg = "Successfully uploaded Root CRL.<br/>";
                                $("#root-crl-result").removeClass("hidden").removeClass("error").show().html(msg).addClass("success");

                            } else {
                                $("#root-crl-result").removeClass("hidden").removeClass("success").show().text(data.Errors["CRL"]).addClass("error");
                            }
                        })
                        .fail(function(xhr, status, err) {
                            $('#modal-spinner').modal('hide');
                            $("#root-crl-result").removeClass("hidden").removeClass("success").show().html(err + "<br/>").addClass("error");
                        });
                    }

                } else if ($(evt.target).attr("id") == "cancel-rootkey" || $(evt.target).attr("id") == "cancel-crl" || $(evt.target).attr("id") == "cancel-backup" ||
                    $(evt.target).attr("id") == "cancel-export" || $(evt.target).attr("id") == "cancel-leaves" || $(evt.target).attr("id") == "cancel-renew" ||
                    $(evt.target).attr("id") == "cancel-newcert") {
                    $('#modal-spinner').modal('hide');
                    $('#modal-backup').modal('hide');
                    $('#modal-crl').modal('hide');
                    $('#modal-root-key').modal('hide');
                    $('#modal-export').modal('hide');
                    $('#modal-leaves').modal('hide');
                    $('#modal-renew').modal('hide');
                    $('#modal-newcert').modal('hide');
                    return false;

                } else if ($(evt.target).hasClass("btn-modal-dismiss")) {
                    $('#modal-spinner').modal('hide');
                    return true;

                } else if ($(evt.target).attr("id") == "modal-leaves-done") {
                    if ($("#want-new-active-issuer").hasClass("hidden")) {
                        $('#modal-spinner').modal('hide');
                        $('#modal-leaves').modal('hide');
                    } else {
                        var req = new XMLHttpRequest();
                        req.open("POST", window.location.href, true);
                        req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                        req.onload = function(event) {
                            $('#modal-spinner').modal('hide');

                            if (event.currentTarget.status == 200) {
                                try {
                                    res = JSON.parse(req.response);
                                    if (res.Success) {
                                        $('input[type=radio][name=issue-active]').each(function() {
                                            $(this).data('orig', $(this).prop('checked'))
                                        });
                                        $('#modal-leaves').modal('hide');

                                        var msg = "Successfully updated issuers, restarting 'Boulder (ACME)' now...";
                                        setTimeout(function() {
                                            window.location.reload();
                                        }, 10000);
                                        $("#modal-leaves-error").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");

                                    } else {
                                        $("#modal-leaves-error").removeClass("hidden").show().text(res.Error);
                                    }
                                } catch (e) {
                                    console.log(e);
                                    $("#modal-leaves-error").removeClass("hidden").show().text("Received an unexpected response from the server");
                                }

                            } else if (event.currentTarget.status == 502) {
                                // Is a result of the backend restart...
                                var msg = "Successfully updated issuers and restarted 'Boulder (ACME)'";
                                $("#modal-leaves-error").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");
                                setTimeout(function() {
                                    window.location.reload();
                                }, 2000);

                            } else {
                                $("#modal-leaves-error").removeClass("hidden").show().text("Backend returned: " + event.currentTarget.statusText);
                            }
                        };

                        req.onerror = function(event) {
                            $('#modal-spinner').modal('hide');
                            $("#modal-leaves-error").removeClass("hidden").show().text("Error communicating with backend server");
                        };

                        req.send("action=update-leave-issuers" + "&active=" + $("#new-active-issuer").val());
                    }
                    return false;

                } else if ($(evt.target).hasClass('export-cert-key')) {
                    $('#modal-spinner').modal('hide');
                    $('#modal-export-subject').text($(evt.target).data('subject'));
                    $('#export-certname').val($(evt.target).data('name'));
                    $('#modal-export').modal('show');
                    return false;

                } else if ($(evt.target).hasClass('renew-cert')) {
                    $('#modal-spinner').modal('hide');
                    $('#modal-renew-cert').val($(evt.target).data('name'));
                    $('#renew-rootcert').val($(evt.target).data('rootname'));
                    $('#renew-subject').text($(evt.target).data('subject'));
                    $('#renew-keytype').text($(evt.target).data('keytype'));
                    $('#renew-rootsubject').val($(evt.target).data('rootsubject'));
                    d = new Date($(evt.target).data('notbefore')).toUTCString()
                    $('#renew-current-enddate').text(d);
                    if ($(evt.target).data('isroot')) {
                        $("#renew-show-root-enddate").hide();
                        $("#renew-root-enddate").text("");
                        $('#renew-numdays').val(4 * 365);
                    } else {
                        $("#renew-show-root-enddate").removeClass("hidden").show();
                        d = new Date($(evt.target).data('notafter')).toUTCString()
                        $("#renew-root-enddate").text(d);
                        $('#renew-numdays').val(365);
                    }
                    updateEndDate();
                    $('#modal-renew').modal('show');
                    return false;

                } else if ($(evt.target).attr("id") == "modal-renew-done") {
                    var req = new XMLHttpRequest();
                    req.open("POST", window.location.href, true);
                    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                    req.onload = function(event) {
                        $('#modal-spinner').modal('hide');

                        if (event.currentTarget.status == 200) {
                            try {
                                res = JSON.parse(req.response);
                                if (res.Success) {
                                    var msg = "Successfully updated issuers and restarted 'Boulder (ACME)'";
                                    setTimeout(function () {
                                        $('#modal-renew').modal('hide');
                                        window.location.reload();
                                    }, 2000);
                                    $("#modal-renew-error").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");

                                } else if (res.Error.startsWith("NO_ROOT_KEY")) {
                                    $("#modal-show-root-key-subject").removeClass("hidden").show();
                                    $("#modal-root-key-subject").text($('#renew-rootsubject').val());
                                    $("#modal-root-key-upload").hide();
                                    $("#modal-root-key-renew").removeClass("hidden").show();
                                    if (res.Error.split(":").length > 1) {
                                        $("#modal-root-key-error").show().text(res.Error.split(":")[1]);
                                    }
                                    $('#modal-root-key').modal('show');
                                    $('#modal-renew').modal('hide');
                                    return false;

                                } else {
                                    $("#modal-renew-error").removeClass("hidden").show().text(res.Error);
                                }
                            } catch (e) {
                                console.log(e);
                                $("#modal-renew-error").removeClass("hidden").show().text("Received an unexpected response from the server");
                            }

                        } else if (event.currentTarget.status == 502) {
                            // Is a result of the backend restart...
                            var msg = "Successfully updated issuers and restarted 'Boulder (ACME)'";
                            $("#modal-renew-error").removeClass("hidden").removeClass("error").show().text(msg).addClass("success");
                            setTimeout(function() {
                                window.location.reload();
                            }, 2000);

                        } else {
                            $("#modal-renew-error").removeClass("hidden").show().text("Backend returned: " + event.currentTarget.statusText);
                        }
                    };

                    req.onerror = function(event) {
                        $('#modal-spinner').modal('hide');
                        $("#modal-renew-error").removeClass("hidden").show().text("Error communicating with backend server");
                    };

                    req.send("action=renew-cert&certname=" + $('#modal-renew-cert').val() + "&days=" + $("#renew-numdays").val() +
                        "&rootname=" + $('#renew-rootcert').val() + "&root_key=" + encodeURIComponent($("#modal-rootkey").val()) +
                        "&passphrase=" + encodeURIComponent($("#modal-rootpassphrase").val()));

                    return false;

                } else if ($(evt.target).attr("id") == "modal-root-key-renew") {
                    if ($("#modal-rootkey").val() == "") {
                        $('#modal-spinner').modal('hide');
                        $("#modal-root-key-error").show().text("Please provide the root key");
                        return false;
                    } else {
                        $("#modal-show-root-key-subject").hide();
                        $("#modal-root-key-upload").removeClass("hidden").show();
                        $("#modal-root-key-renew").hide();
                        $('#modal-root-key').modal('hide');
                        $('#modal-renew').modal('show');
                        $("#modal-renew-done").click();
                        return false;
                    }

                } else if ($(evt.target).hasClass('new-issuer-cert')) {
                    $('#modal-spinner').modal('hide');
                    window.location.href = "/manage/newissuer?root=" + $(evt.target).data('root');

                } else if ($(evt.target).hasClass('new-root-cert')) {
                    $('#modal-spinner').modal('hide');
                    window.location.href = "/manage/newroot";

                } else if ($(evt.target).hasClass("delete-cert")) {
                    console.log("TODO: implement delete...");

                } else {
                    $.ajax(window.location.href, {
                        method: "POST",
                        data: {
                            action: $(evt.target).attr("id"),
                        },
                    })
                    .done(function(data) {
                        if ( $(evt.target).attr("id") == "version-update") {
                            const date = Date.now();
                            let currentDate = null;
                            do {
                                currentDate = Date.now();
                            } while (currentDate - date < 60000);

                            window.location.reload();
                        }
                        $('#modal-spinner').modal('hide');

                        td = $(evt.target).parent().parent().find("td:eq(1)");
                        $(td).attr("title", data.Timestamp);
                        span = $(td).find("span:eq(0)");
                        $(span).attr("class", data.Class);
                        $(span).text((data.TimestampRel == "stopped" ? "" : "Up ") + data.TimestampRel);

                        if ( $(evt.target).attr("id") == "boulder-start" ) {
                            if (data.TimestampRel != "stopped") {
                                $("#boulder-start").hide();
                                $("#boulder-stop").removeClass("hidden").show();
                                $("#boulder-restart").removeClass("hidden").show();
                            }
                        }
                        if ( $(evt.target).attr("id") == "boulder-stop" || $(evt.target).attr("id") == "boulder-restart" ) {
                            if (data.TimestampRel == "stopped") {
                                $("#boulder-start").show();
                                $("#boulder-stop").hide();
                                $("#boulder-restart").hide();
                            }
                        }
                    })
                    .fail(function(xhr, status, err) {
                        $('#modal-spinner').modal('hide');
                        $("#cert-export-err").removeClass("hidden").show().text(err);
                    });
                }
            });

            $(".backup-restore").each(function() {
                if ($(this).parent().parent().find("td").eq(0).text().startsWith("dbdata-") ) {
                    $(this).addClass("hidden");
                }
            });

            function check_fqdn() {
                if ($("#fqdn").val() == window.location.host) {
                    $("#fqdn_warning").hide();
                } else {
                    $("#fqdn_warning").removeClass('hidden').show();
                }
            }

            $("#fqdn").blur(function() {
                check_fqdn();
            });

            $("#fqdn").keyup(function() {
                check_fqdn();
            });

            check_fqdn();

            $(".account-input").keyup(function() {
                ok = $("#username").val() && $("#accemail").val() && $("#password").val();
                $("#update-account").prop('disabled', !ok);
            });

            $(".account-input").blur(function() {
                ok = $("#username").val() && $("#accemail").val() && $("#password").val();
                $("#update-account").prop('disabled', !ok);
            });

            function updateEndDate() {
                // Determine new end date
                x = new Date();
                x.setDate(x.getDate() + parseInt($('#renew-numdays').val()))
                $('#renew-new-enddate').text(x.toUTCString());

                try {
                    c = new Date($('#renew-current-enddate').text());
                    if (x <= c) {
                        if ($("#renew-numdays-error").hasClass('hidden')) {
                            $("#renew-numdays-error").text("Validity cannot end before current end date");
                            $("#renew-numdays-error").removeClass('hidden').show();
                        }
                    } else if ($('#renew-root-enddate').text().length > 0) {
                        r = new Date($('#renew-root-enddate').text());
                        if (x > r) {
                            if ($("#renew-numdays-error").hasClass('hidden')) {
                                $("#renew-numdays-error").text("Validity cannot exceed root certificate end date");
                                $("#renew-numdays-error").removeClass('hidden').show();
                            }
                        } else {
                            $("#renew-numdays-error").text("");
                            if (!$("#renew-numdays-error").hasClass('hidden')) {
                                $("#renew-numdays-error").hide().addClass('hidden');
                            }
                        }
                    } else {
                        $("#renew-numdays-error").text("");
                        if (!$("#renew-numdays-error").hasClass('hidden')) {
                            $("#renew-numdays-error").hide().addClass('hidden');
                        }
                    }
                } catch (e) {
                    console.log(e);
                }

                $("#modal-renew-done").prop('disabled', !$("#renew-numdays-error").hasClass('hidden'));
            }

            $.fn.inputFilter = function(callback, errMsg) {
                return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function (e) {
                    if (callback(this.value)) {
                        // Accepted value
                        if (["keydown", "mousedown", "focusout"].indexOf(e.type) >= 0) {
                            $("#renew-numdays-error").text("");
                            if (!$("#renew-numdays-error").hasClass('hidden')) {
                                $("#renew-numdays-error").hide().addClass('hidden');
                            }
                        }
                        this.oldValue = this.value;
                        this.oldSelectionStart = this.selectionStart;
                        this.oldSelectionEnd = this.selectionEnd;
                        updateEndDate();
                    } else if (this.hasOwnProperty("oldValue")) {
                        // Rejected value - restore the previous one
                        $("#renew-numdays-error").text(errMsg);
                        if ($("#renew-numdays-error").hasClass('hidden')) {
                            $("#renew-numdays-error").removeClass('hidden').show();
                        }
                        this.value = this.oldValue;
                        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                    } else {
                        // Rejected value - nothing to restore
                        this.value = "";
                    }
                });
            };

            $("#renew-numdays").inputFilter(function (value) {
                return /^\d*$/.test(value);    // Allow digits only, using a RegExp
            }, "Only digits are allowed");

            $(".delete-cert.hidden").each(function () {
                try {
                    if ($($(this).parent().parent().next().children()[0]).text().indexOf("┖") < 0) {
                        $(this).removeClass('hidden');
                    }
                } catch (e) { }
            });

            pwduxHandlers('#password-strength', '#new-password', ['#username', '#accemail']);
        });
    </script>
{{ end }}
