<!--#set global $pane="Servers"#-->
<!--#set global $help_uri = $confighelpuri + "servers"#-->
<!--#include $webdir + "/_inc_header_uc.tmpl"#-->

<!--#import json#-->
<!--#import datetime#-->

<script type="text/javascript">
    // Define variable needed for the server-statistics
    var serverBandwithData = {}
    var serverArticleTries = {}
    var serverArticleFailed = {}

    // Keep track of all used hostnames
    var hostnames = ""
</script>

<div class="server-frame">
    <a href="#">&times;</a>
    <iframe></iframe>
</div>

<div class="colmask">
    <div class="padding alt section">
        <button type="button" class="btn btn-default" id="addServerButton"><span class="glyphicon glyphicon-plus"></span> $T('button-addServer')</button>
        <label for="advanced-settings-button" class="form-control advanced-button ">
            <input type="checkbox" id="advanced-settings-button" name="advanced-settings-button"> $T('button-advanced')
        </label>

        <div class="advanced-buttonSeperator"></div>
        <div class="chart-selector-container" title="$T('selectedDates')" data-placement="bottom">
            <span class="glyphicon glyphicon-signal"></span>
            <!--#set today = datetime.date.today()#-->
            <input type="date" name="chart-start" id="chart-start" value="<!--#echo (today-datetime.timedelta(days=30)).strftime('%Y-%m-%d')#-->"> -
            <input type="date" name="chart-end" id="chart-end" value="<!--#echo today.strftime('%Y-%m-%d')#-->">
        </div>
    </div>
    <div class="section" id="addServerContent" style="display: none;">
        <div class="col2">
            <h3>$T('addServer') <a href="$help_uri" target="_blank"><span class="glyphicon glyphicon-question-sign"></span></a></h3>
        </div>
        <div class="col1">
            <form action="addServer" method="post" autocomplete="off" onsubmit="removeObfuscation();">
                <input type="hidden" name="apikey" value="$apikey" />
                <input type="hidden" name="output" value="json" />
                <fieldset>
                    <div class="field-pair">
                        <label class="config" for="enable">$T('srv-enable')</label>
                        <input type="checkbox" name="enable" id="enable" value="1" checked="checked" />
                        <span class="desc">$T('srv-enable')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="displayname">$T('srv-displayname')</label>
                        <input type="text" name="displayname" id="displayname" />
                    </div>
                    <div class="field-pair">
                        <label class="config" for="host">$T('srv-host')</label>
                        <input type="text" name="host" id="host" required />
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="port">$T('srv-port')</label>
                        <input type="number" name="port" id="port" size="8" value="563" min="0" max="65535" />
                    </div>
                    <div class="field-pair">
                        <label class="config" for="ssl">$T('srv-ssl')</label>
                        <input type="checkbox" name="ssl" id="ssl" value="1" checked />
                        <span class="desc">$T('explain-ssl')</span>
                    </div>
                    <!-- Tricks to avoid browser auto-fill, fixed on-submit with javascript -->
                    <div class="field-pair">
                        <label class="config" for="${pid}_000">$T('srv-username')</label>
                        <input type="text" name="${pid}_000" id="${pid}_000" data-hide="username" />
                    </div>
                    <div class="field-pair">
                        <label class="config" for="${pid}_001">$T('srv-password')</label>
                        <input type="text" name="${pid}_001" id="${pid}_001" data-hide="password" />
                    </div>
                    <div class="field-pair">
                        <label class="config" for="connections">$T('srv-connections')</label>
                        <input type="number" name="connections" id="connections" min="1" max="500" value="8" required />
                    </div>
                    <div class="field-pair">
                        <label class="config" for="priority">$T('srv-priority')</label>
                        <input type="number" name="priority" id="priority" min="0" max="99" /> <i>$T('explain-svrprio')</i>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="retention">$T('srv-retention')</label>
                        <input type="number" name="retention" id="retention" min="0" /> <i>$T('days')</i>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="timeout">$T('srv-timeout')</label>
                        <input type="number" name="timeout" id="timeout" min="20" max="240" /> <i>$T('seconds')</i>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="ssl_verify">$T('opt-ssl_verify')</label>
                        <select name="ssl_verify" id="ssl_verify">
                            <option value="3" selected>$T('ssl_verify-strict')</option>
                            <option value="2">$T('ssl_verify-medium')</option>
                            <option value="1">$T('ssl_verify-minimal')</option>
                            <option value="0">$T('ssl_verify-disabled')</option>
                        </select>
                        <span class="desc">$T('explain-ssl_verify').replace('-', '<br/>-')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="ssl_ciphers">$T('opt-ssl_ciphers')</label>
                        <input type="text" name="ssl_ciphers" id="ssl_ciphers" />
                        <span class="desc">$T('explain-ssl_ciphers') <br>$T('readwiki')
                        <a href="https://sabnzbd.org/wiki/advanced/ssl-ciphers" target="_blank">https://sabnzbd.org/wiki/advanced/ssl-ciphers</a></span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="required">$T('srv-required')</label>
                        <input type="checkbox" name="required" id="required" value="1" />
                        <span class="desc">$T('explain-required')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="optional">$T('srv-optional')</label>
                        <input type="checkbox" name="optional" id="optional" value="1" />
                        <span class="desc">$T('explain-optional')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="pipelining_requests">$T('srv-pipelining_requests')</label>
                        <input type="number" name="pipelining_requests" id="pipelining_requests" min="1" max="20" value="2" />
                        <span class="desc">$T('explain-pipelining_requests')<br>$T('readwiki')
                        <a href="https://sabnzbd.org/wiki/advanced/nntp-pipelining" target="_blank">https://sabnzbd.org/wiki/advanced/nntp-pipelining</a></span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="expire_date">$T('srv-expire_date')</label>
                        <input type="date" name="expire_date" id="expire_date" />
                        <span class="desc">$T('srv-explain-expire_date')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="quota">$T('swtag-quota')</label>
                        <input type="text" name="quota" id="quota" class="smaller_input" />
                        <span class="desc">$T('srv-explain-quota')</span>
                    </div>
                    <div class="field-pair advanced-settings">
                        <label class="config" for="notes">$T('srv-notes')</label>
                        <textarea name="notes" id="notes" rows="3" cols="50"></textarea>
                    </div>
                    <div class="field-pair no-field-pair-bg">
                        <button class="btn btn-default addNewServer" disabled data-toggle="tooltip" data-placement="top" title="$T('wizard-test-server-required')"><span class="glyphicon glyphicon-plus"></span> $T('button-addServer')</button>
                        <button class="btn btn-default testServer" type="button"><span class="glyphicon glyphicon-sort"></span> $T('button-testServer')</button>
                    </div>
                    <div class="field-pair result-box">
                        <div class="alert"></div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>

    <!--#set $prio_colors = ["#59cc33", "#26a69a", "#3366cc", "#7f33cc", "#cc33a6", "#f39c12", "#cc3333", "#8d6e63"] #-->
    <!--#set $cur_prio_color = -1 #-->
    <!--#set $last_prio = -1 #-->
    <!--#for $cur, $server in enumerate($servers) #-->
        <form action="saveServer" method="post" class="fullform" autocomplete="off">
            <input type="hidden" name="apikey" value="$apikey" />
            <input type="hidden" name="output" value="json" />
            <input type="hidden" name="server" value="$server['name']" />
            <input type="hidden" name="ajax" value=1 />

            <div class="section <!--#if int($server['enable']) == 0 then 'server-disabled' else ""#-->">
                <div class="col2 <!--#if int($server['enable']) == 0 then 'server-disabled' else ""#-->">
                    <h3 title="$server['displayname']">$server['displayname'] <a href="$help_uri" target="_blank"><span class="glyphicon glyphicon-question-sign"></span></a></h3>
                    <!--#if int($server['enable']) != 0 #-->
                        <!--#if $last_prio != $server['priority'] and $cur_prio_color+1 < len($prio_colors) #-->
                            <!--#set $cur_prio_color = $cur_prio_color+1 #-->
                            <!--#set $last_prio = $server['priority'] #-->
                        <!--#end if#-->
                        <span class="label label-primary" style="background-color: $prio_colors[$cur_prio_color]">$server['priority']</span>
                        <span class="label label-primary" style="background-color: $prio_colors[$cur_prio_color]">$T('srv-priority'):</span>
                    <!--#end if#-->
                    <table>
                        <tr>
                            <td><input type="checkbox" class="toggleServerCheckbox" id="enable_$cur" name="$server['name']" value="1" <!--#if int($server['enable']) != 0 then 'checked="checked"' else ""#--> /></td>
                            <td><label for="enable_$cur">$T('enabled')</label></td>
                        </tr>
                    </table>
                    <button type="button" class="btn btn-default showserver"><span class="glyphicon glyphicon-pencil"></span> $T('showDetails')</button>
                    <button type="button" class="btn btn-default clrServer"><span class="glyphicon glyphicon-remove"></span> $T('button-clrServer')</button>
                    <!--#if $server['notes'] #-->
                    <p>$server['notes'].replace('\n', '<br>')</p>
                    <!--#end if#-->
                </div>
                <div class="col1" style="display:none;">
                    <input type="hidden" name="enable" id="enable$cur" value="$int($server['enable'])" />
                    <fieldset>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="displayname$cur">$T('srv-displayname')</label>
                            <input type="text" name="displayname" id="displayname$cur" value="$server['displayname']" />
                        </div>
                        <div class="field-pair">
                            <label class="config" for="host$cur">$T('srv-host')</label>
                            <input type="text" name="host" id="host$cur" value="$server['host']" required />
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="port$cur">$T('srv-port')</label>
                            <input type="number" name="port" id="port$cur" value="$server['port']" size="8" min="0" max="65535" required />
                        </div>
                        <div class="field-pair">
                            <label class="config" for="ssl$cur">$T('srv-ssl')</label>
                            <input type="checkbox" name="ssl" id="ssl$cur" value="1" <!--#if int($server['ssl']) != 0 then 'checked="checked"' else ""#--> />
                            <span class="desc">$T('explain-ssl')</span>
                        </div>
                        <!-- Tricks to avoid browser auto-fill, fixed on-submit with javascript -->
                        <div class="field-pair">
                            <label class="config" for="${pid}_${cur}0">$T('srv-username')</label>
                            <input type="text" name="${pid}_${cur}0" id="${pid}_${cur}0" value="$server['username']" data-hide="username" />
                        </div>
                        <div class="field-pair">
                            <label class="config" for="${pid}_${cur}1">$T('srv-password')</label>
                            <input type="text" name="${pid}_${cur}1" id="${pid}_${cur}1" value="$server['password']" data-hide="password" />
                        </div>
                        <div class="field-pair">
                            <label class="config" for="connections$cur">$T('srv-connections')</label>
                            <input type="number" name="connections" id="connections$cur" value="$server['connections']" min="1" max="500" required />
                        </div>
                        <div class="field-pair">
                            <label class="config" for="priority$cur">$T('srv-priority')</label>
                            <input type="number" name="priority" id="priority$cur" value="$server['priority']" min="0" max="99" required /> <i>$T('explain-svrprio')</i>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="retention$cur">$T('srv-retention')</label>
                            <input type="number" name="retention" id="retention$cur" value="$server['retention']" min="0" required /> <i>$T('days')</i>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="timeout$cur">$T('srv-timeout')</label>
                            <input type="number" name="timeout" id="timeout$cur" value="$server['timeout']" min="20" max="240" required /> <i>$T('seconds')</i>
                        </div>

                        <div class="field-pair advanced-settings">
                            <label class="config" for="ssl_verify$cur">$T('opt-ssl_verify')</label>
                            <select name="ssl_verify" id="ssl_verify$cur">
                                <option value="3" <!--#if $server['ssl_verify'] == 3 then 'selected="selected"' else ""#--> >$T('ssl_verify-strict')</option>
                                <option value="2" <!--#if $server['ssl_verify'] == 2 then 'selected="selected"' else ""#--> >$T('ssl_verify-medium')</option>
                                <option value="1" <!--#if $server['ssl_verify'] == 1 then 'selected="selected"' else ""#--> >$T('ssl_verify-minimal')</option>
                                <option value="0" <!--#if $server['ssl_verify'] == 0 then 'selected="selected"' else ""#--> >$T('ssl_verify-disabled')</option>
                            </select>
                            <span class="desc">$T('explain-ssl_verify').replace('-', '<br/>-')</span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="ssl_ciphers$cur">$T('opt-ssl_ciphers')</label>
                            <input type="text" name="ssl_ciphers" id="ssl_ciphers$cur" value="$server['ssl_ciphers']" />
                            <span class="desc">$T('explain-ssl_ciphers') <br>$T('readwiki')
                            <a href="https://sabnzbd.org/wiki/advanced/ssl-ciphers" target="_blank">https://sabnzbd.org/wiki/advanced/ssl-ciphers</a></span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="required$cur">$T('srv-required')</label>
                            <input type="checkbox" name="required" id="required$cur" value="1" <!--#if int($server['required']) != 0 then 'checked="checked"' else ""#--> />
                            <span class="desc">$T('explain-required')</span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="optional$cur">$T('srv-optional')</label>
                            <input type="checkbox" name="optional" id="optional$cur" value="1" <!--#if int($server['optional']) != 0 then 'checked="checked"' else ""#--> />
                            <span class="desc">$T('explain-optional')</span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="pipelining_requests$cur">$T('srv-pipelining_requests')</label>
                            <input type="number" name="pipelining_requests" id="pipelining_requests$cur" value="$server['pipelining_requests']" min="1" max="20" required />
                            <span class="desc">$T('explain-pipelining_requests')<br>$T('readwiki')
                            <a href="https://sabnzbd.org/wiki/advanced/nntp-pipelining" target="_blank">https://sabnzbd.org/wiki/advanced/nntp-pipelining</a></span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="expire_date$cur">$T('srv-expire_date')</label>
                            <input type="date" name="expire_date" id="expire_date$cur"  value="$server['expire_date']" />
                            <span class="desc">$T('srv-explain-expire_date')</span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="quota$cur">$T('swtag-quota')</label>
                            <input type="text" name="quota" id="quota$cur" value="$server['quota']" class="smaller_input" />
                            <span class="desc">$T('srv-explain-quota')</span>
                        </div>
                        <div class="field-pair advanced-settings">
                            <label class="config" for="notes$cur">$T('srv-notes')</label>
                            <textarea name="notes" id="notes$cur" rows="3" cols="50">$server['notes']</textarea>
                        </div>
                        <div class="field-pair no-field-pair-bg">
                            <button class="btn btn-default saveButton"><span class="glyphicon glyphicon-ok"></span> $T('button-saveChanges')</button>
                            <button class="btn btn-default testServer" type="button"><span class="glyphicon glyphicon-sort"></span> $T('button-testServer')</button>
                            <button class="btn btn-default delServer"><span class="glyphicon glyphicon-trash"></span> $T('button-delServer')</button>
                        </div>
                        <div class="field-pair result-box">
                            <div class="alert"></div>
                        </div>
                    </fieldset>
                </div>
                <div class="col1" style="display:block;">
                    <!--#if 'amounts' in $server#-->
                        <div class="server-amounts-text">
                            <p>
                                <b>$T('srv-bandwidth'):</b><br/>
                                $T('total'): $(server['amounts'][0])B<br/>
                                $T('today'): $(server['amounts'][3])B<br/>
                                $T('thisWeek'): $(server['amounts'][2])B<br/>
                                $T('thisMonth'): $(server['amounts'][1])B<br/>
                                $T('selectedDates'): <span id="server-bandwith-value-${cur}"></span>
                            </p>

                            <p title="$T('readwiki')">
                                <b>$T('srv-article-availability'):</b><br/>
                                $T('selectedDates'): <span id="server-article-value-${cur}"></span><br/>
                                <a href="https://sabnzbd.org/not-complete" id="server-article-not-complete-${cur}" target="_blank">https://sabnzbd.org/not-complete</a>
                            </p>
                            <!--#if $server['expire_date']#-->
                            <p><b>$T('srv-expire_date'):</b> $(server['expire_date'])</p>
                            <!--#end if#-->
                            <!--#if $server['quota']#-->
                            <p><b>$T('quota-left'):</b> $(server['quota_left'])</p>
                            <!--#end if#-->
                        </div>
                        <div class="server-chart" data-serverid="${cur}">
                            <div id="server-chart-${cur}" class="ct-chart"></div>
                        </div>
                        <script type="text/javascript">
                            // Server data
                            serverBandwithData[${cur}] = <!--#echo json.dumps($server['amounts'][4])#-->
                            serverArticleTries[${cur}] = <!--#echo json.dumps($server['amounts'][5])#-->
                            serverArticleFailed[${cur}] = <!--#echo json.dumps($server['amounts'][6])#-->
                            <!--#if int($server['enable']) != 0#-->
                            hostnames += ",$server['host']"
                            <!--#end if#-->
                        </script>
                    <!--#end if#-->
                </div>
            </div>
        </form>
    <!--#end for#-->
</div>

<script type="text/javascript" src="${root}staticcfg/js/chartist.min.js"></script>
<script type="text/javascript" src="${root}staticcfg/js/filesize.min.js"></script>
<script type="text/javascript">
    // Standardize chart options
    var chartOptions = {
        fullWidth: true,
        showArea: true,
        axisX: {
            labelOffset: {
                x: -5
            },
            showGrid: false
        },
        axisY: {
            labelOffset: {
                y: 7
            },
            scaleMinSpace: 30
        },
        chartPadding: {
            top: 9,
            bottom: 0,
            left: 30,
            right: 20
        }
    }

    function showCharts() {
        // Get the constants
        const startDate = new Date(jQuery('#chart-start').val())
        const endDate = new Date(jQuery('#chart-end').val())
        const oneDay = 24 * 60 * 60 * 1000
        const nrDays = Math.round((endDate-startDate)/oneDay)

        // Show only maximum 10 labels to avoid cluttering
        const labelStep = Math.round(nrDays/10)

        // Save largest value
        var maxBandwith = 0

        // For each chart
        jQuery('.server-chart').each(function(j, elemn) {
            const server_id = jQuery(elemn).data('serverid')
            var totalBandwithThisRange = 0
            var totalArticlesTriedThisRange = 0
            var totalArticlesFailedThisRange = 0

            // Fill the data array
            var data = {
                labels: [],
                series: [[]]
            };

            for(var i = 0; i < nrDays+1; i++) {
                // Update the date
                const checkDate = new Date(startDate)
                checkDate.setDate(checkDate.getDate() + i);

                // Add X-label
                if(i % labelStep === 0) {
                    data['labels'].push(checkDate.getDate())
                } else {
                    data['labels'].push(NaN)
                }

                // Date we can check in the array
                const dateCheck = toFormattedDate(checkDate)

                // Add data if we have it
                if(dateCheck in serverBandwithData[server_id]) {
                    data['series'][0].push(serverBandwithData[server_id][dateCheck])
                    totalBandwithThisRange += serverBandwithData[server_id][dateCheck]
                    maxBandwith = Math.max(maxBandwith, serverBandwithData[server_id][dateCheck])
                } else {
                    data['series'][0].push(0)
                }

                // Article stats
                if(dateCheck in serverArticleTries[server_id]) {
                    totalArticlesTriedThisRange += serverArticleTries[server_id][dateCheck]
                    totalArticlesFailedThisRange += serverArticleFailed[server_id][dateCheck]
                }
            }

            // Update the text value
            jQuery('#server-bandwith-value-' + server_id).text(filesize(totalBandwithThisRange, {round: 1}))

            // Calculate article success ratio, if available
            var articleRatio = Math.round(100 * (1 - totalArticlesFailedThisRange/totalArticlesTriedThisRange))

            // If values were missing
            if(!isNaN(articleRatio)) {
                // Use filesize to convert to unit-display
                jQuery('#server-article-value-' + server_id).text('$T("srv-articles-tried")'.replace('%f', articleRatio).replace('%d', filesize(totalArticlesTriedThisRange, {unix: true, round: 0, spacer: "", base: 1})))
                // If we have a low value, we link them to the website
                if(articleRatio > 60) jQuery('#server-article-not-complete-' + server_id).hide()
            } else {
                jQuery('#server-article-value-' + server_id).text('$T("notAvailable")')
                jQuery('#server-article-not-complete-' + server_id).hide()
            }

            // Save bandwidth data in a very ugly way, but we need to do this
            // so we can calculate the maximum Y-axis for all graphs
            jQuery(elemn).data("chart-data", data)
        })

        // Set the maximum
        chartOptions.axisY.high = maxBandwith
        chartOptions.axisY.low = 0

        // Update all the axis with the largest value and draw the graph
        jQuery('.server-chart').each(function(j, elemn) {
            const server_id = jQuery(elemn).data('serverid')

            // Show the chart
            chart = new Chartist.Line('#server-chart-'+server_id, jQuery(elemn).data("chart-data"), chartOptions)
            chart.on('created', function(context) {
                // Make sure to add this as the first child so it's at the bottom
                context.svg.elem('rect', {
                    x: context.chartRect.x1,
                    y: context.chartRect.y2-1,
                    width: context.chartRect.width(),
                    height: context.chartRect.height()+2,
                    fill: 'none',
                    stroke: '#b9b9b9',
                    'stroke-width': '1px'
                }, '', context.svg, true)
                jQuery('#server-chart-'+server_id+' .ct-label.ct-vertical').each(function(index, elmn) {
                    elmn.innerHTML = filesize(elmn.innerHTML, {round: 1}).replace(' ','')
                })
            });
        })

        // Limit input to sensible values
        jQuery('#chart-start').attr("max", jQuery('#chart-end').val())
        jQuery('#chart-end').attr("min", jQuery('#chart-start').val())
    }

    // Need to mitigate timezone effects!
    function toFormattedDate(date) {
        var local = new Date(date);
        local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
        return local.toJSON().slice(0, 10);
    }

    /**
        When finished loading
    **/
    jQuery(document).ready(function(){
        // Initialize tooltips
        jQuery('[data-toggle="tooltip"]').tooltip()
        
        // Reload form in case we change items that make the servers appear different
        jQuery('input[name="priority"], input[name="displayname"], textarea[name="notes"]').on('change', function(event) {
            var parentForm = jQuery(event.target).parents("form")
            parentForm.unbind("submit")
            parentForm.find('input[name="ajax"]').val('')
        })

        /**
            Update charts when changed
        **/
        jQuery('#chart-start, #chart-end').on('change', function(elemn) {
            showCharts()

            // Lets us leave (needs to be called after the change event)
            setTimeout(function() {
                formWasSubmitted = true;
                formHasChanged = false;
            }, 100)
        })
        // And on page-load
        showCharts()

        /**
            Click events
        **/
        jQuery('.showserver').click(function () {
            if(jQuery(this).parent().hasClass('server-disabled')) {
                jQuery(this).parent().parent().toggleClass('server-disabled')
            }
            jQuery(this).parent().next().toggle();
            jQuery(this).parent().next().next().toggle();
            if (jQuery(this).text().indexOf("$T('showDetails')") > 0) {
                jQuery(this).html(jQuery(this).html().replace("$T('showDetails')", "$T('hideDetails')"));
            } else {
                jQuery(this).html(jQuery(this).html().replace("$T('hideDetails')", "$T('showDetails')"));
                // Recalculate the charts if changed while details were open
                showCharts()
            }
            // Add coloring
            addRowColor()
        });

        jQuery('#addServerButton').click(function(){
            jQuery('#addServerContent').show();
            // Add coloring
            addRowColor()
        });

        jQuery('[name="ssl"]').click(function() {
            // Use CSS transitions to do some highlighting
            var portBox = jQuery(this).parent().parent().find('[name="port"]')
            if(this.checked) {
                // Enabled SSL change port when not already a custom port
                if(portBox.val() === '119') {
                    portBox.val('563')
                    portBox.addClass('port-highlight')
                }
            } else {
                // Remove SSL port
                if(portBox.val() === '563') {
                    portBox.val('119')
                    portBox.addClass('port-highlight')
                }
            }
            setTimeout(function() { portBox.removeClass('port-highlight') }, 2000)
        })

        // Testing servers
        jQuery('.testServer').click(function(event){
            removeObfuscation()
            var theButton = jQuery(this)
            var resultBox = theButton.parents('.col1').find('.result-box .alert');
            theButton.attr("disabled", "disabled")
            theButton.find('span').toggleClass('glyphicon-sort glyphicon-refresh spin-glyphicon')
            jQuery.ajax({
                type: "POST",
                url: "../../api",
                data: "mode=config&name=test_server&" + jQuery(this).parents('form:first').serialize()
            }).then(function(data) {
                // Let's replace the link
                msg = data.value.message.replace('https://sabnzbd.org/certificate-errors', '<a href="https://sabnzbd.org/certificate-errors" class="alert-link" target="_blank">https://sabnzbd.org/certificate-errors</a>')
                msg = msg.replace('-', '<br>')
                // Fill the box and enable the button
                resultBox.removeClass('alert-success alert-danger').show()
                resultBox.html(msg)
                theButton.removeAttr("disabled")
                theButton.find('span').toggleClass('glyphicon-sort glyphicon-refresh spin-glyphicon')

                // Success or not?
                if(data.value.result) {
                    resultBox.addClass('alert-success')
                    resultBox.prepend('<span class="glyphicon glyphicon-ok-sign"></span> ')

                    // Allow adding the new server if we are in the new-server section
                    if(theButton.parents("form[action='addServer']").length) {
                        jQuery(".addNewServer").removeAttr("disabled")
                        jQuery(".addNewServer").removeAttr("data-toggle")
                        jQuery(".addNewServer").removeAttr("title")
                        jQuery(".addNewServer").tooltip("destroy")
                    }
                } else {
                    resultBox.addClass('alert-danger')
                    resultBox.prepend('<span class="glyphicon glyphicon-exclamation-sign"></span> ')

                    // Disable the adding of new server, just to be sure
                    if(theButton.parents("form[action='addServer']").length) {
                        jQuery(".addNewServer").attr("disabled", "disabled")
                        jQuery(".addNewServer").attr("data-toggle", "tooltip")
                        jQuery(".addNewServer").attr("data-placement", "top")
                        jQuery(".addNewServer").attr("title", "$T('wizard-test-server-required')")
                        jQuery(".addNewServer").tooltip()
                    }
                }
            });
        });

        jQuery('.delServer').click(function(){
            if( confirm("$T('confirm')") ) {
                jQuery(this).parents('form:first').attr('action','delServer').submit();
                // Let us leave!
                formWasSubmitted = true;
                formHasChanged = false;
                setTimeout(function() { location.reload(); }, 500)
            }
            return false;
        });

        jQuery('.clrServer').click(function(){
            if( confirm("$T('confirm')") ) {
                jQuery(this).parents('form:first').attr('action','clrServer').submit();
                // Let us leave!
                formWasSubmitted = true;
                formHasChanged = false;
                setTimeout(function() { location.reload(); }, 500)
            }
            return false;
        });

        jQuery('.toggleServerCheckbox').click(function(){
            var whichServer = jQuery(this).attr("name");
            jQuery.ajax({
                type: "POST",
                url: "toggleServer",
                data: {server: whichServer, apikey: "$apikey" }
            }).done(function() {
                // Let us leave!
                formWasSubmitted = true;
                formHasChanged = false;
                setTimeout(function() { location.reload(); }, 100)
            });
        });

        // Show text-ad if there is space
        if((jQuery("body").width() - jQuery("#content").width())/2 > (jQuery('.Servers .server-frame').width() + 40)) {
            // Do not show if dismissed previously
            if(localStorage.getItem("server-frame-hide-$version") === null) {
                // Let the page on the server tell us if we need to show
                function receiveMessage(event) {
                    // Check origin of message for security reasons
                    if(event.origin === 'https://sabnzbd.org') {
                        if(event.data === 'show_server') {
                            jQuery('.Servers .server-frame').show()
                            jQuery('.Servers .server-frame a').click(function () {
                                localStorage.setItem("server-frame-hide-$version", "hide")
                                jQuery('.Servers .server-frame').hide()
                            })
                        }
                        if(event.data === 'hide_server') {
                            // Hide and don't load anymore until the next release
                            jQuery('.Servers .server-frame').hide()
                            localStorage.setItem("server-frame-hide-$version", "hide")
                        }
                    }
                }
                window.addEventListener("message", receiveMessage, false);

                // NOTE: The hash-part cannot be seen by the server, so we don't know which hostnames you use!
                jQuery('.Servers .server-frame iframe').attr("src", "https://sabnzbd.org/servers#$active_lang" + hostnames)
            }
        }
    });
</script>

<!--#include $webdir + "/_inc_footer_uc.tmpl"#-->
