{% load i18n %}

<noscript><h3>{{ step }}</h3></noscript>
<style>
#target input{
    width: auto;
}
</style>
<table id='target' class="table table-bordered table-striped datatable">
    <thead><tr><th>From</th><th>protocol</th><th>To</th><th>Action</th></tr></thead>
    <tr>
        <td>
        <input type='text' class='numbers' name='from' />
        </td>
        <td>
        <select name='protocol'>
            <option value='http'>HTTP</option>
            <option value='https'>HTTPS</option>
            <option value='tcp'>TCP</option>
        </select>
        </td>

        <td>
        <input type='text' class='numbers' name='to' />
        </td>
        <td>
        <a class='btn btn-small' name='add'>+</a>
    </td>
        </tr>
</table>

<script>
function encode_lb_rule(from, protocol, to){
    return from + ':' + protocol + ',' + to;
}

function generate_lb_rule(from, protocol, to){
    var html = "<tr><td>" + from + "</td>" +
                "<td>" + protocol + "</td>" +
                "<td>" + to + "</td>" +
                "<td><a class='btn btn-small btn-danger'>-</a>";
    html = $(html);
    html.on('click', 'a', function(){
        $('option[value="' + encode_lb_rule(from, protocol, to) + '"]').remove();
        $(this).closest('tr').remove();
    });
    return html;
}

horizon.modals.addModalInitFunction(function (modal) {
    $("a[name='add']").on('click', function(){
        var from = $("input[name='from']").val();
        var protocol = $("select[name='protocol']").val();
        var to = $("input[name='to']").val();
        var encoded = encode_lb_rule(from, protocol, to);
        if(from && to && $('option[value="'+encoded+'"]').length == 0){
            $('#id_network').append($("<option></option>")
                .attr("value", encoded)
                .attr("selected", "selected")
                .text(encoded));
            generate_lb_rule(from, protocol, to).insertBefore($('#target tr:last'));
            // clean up
            $("input[name='from']").val('');
            $("input[name='to']").val('');
        }
    });

    $('input.numbers').keyup(function () {
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });
});
</script>

<div class="hidden">
    {% include "horizon/common/_form_fields.html" %}
</div>
