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

var checked_fields[%table_id%] = [];
var unchecked_fields[%table_id%] = [];
$(document).ready(function() {

    [%IF value%]
    JSON.parse('[% value %]').map( function (val) {
        //force string type for the correct comparison with $(nRow).find("td:first").text() below
        val = '' + val;
        checked_fields[%table_id%].push(val);
    });
    [%END%]
    function update_hidden_value () {
        $("#[% hidden_id %]").val( JSON.stringify(checked_fields[%table_id%]) );
    }
    $(document).on( "click", '#[% table_id %] tr td input[type="checkbox"]', function() {
        var my_id = $(this).parents("tr").find("td:first").text();
        var indexOfId = checked_fields[%table_id%].indexOf(my_id)
        if($(this).attr("checked") == "checked") {
            if(indexOfId < 0){
                checked_fields[%table_id%].push(my_id);
                unchecked_fields[%table_id%].splice(indexOfId,1);
            }
        } else {
            if( indexOfId >= 0){
                checked_fields[%table_id%].splice(indexOfId,1);
                unchecked_fields[%table_id%].push(my_id);
            }
        }
        update_hidden_value ();
    });
    $('#[% table_id %]')
        .dataTable( {
        "sDom": "<'row-fluid'<'pull-left'r><'pull-right'f>>t<'row-fluid'<'pull-left'i><'pull-right'p>>",
        "bProcessing": true,
        "bServerSide": true,
        "bPaginate": [%IF no_pagination; 'false'; ELSE; 'true'; END%],
        "sPaginationType": "bootstrap",
        "bLengthChange": false,
        "bSort": [%IF no_ordering; 'false'; ELSE; 'true'; END%],
        "bInfo": true,
        "iDisplayLength": 4,
        'iShowPages': 5,
        "oLanguage": {
            "sUrl": "/js/i18n/[% language_file %]"
        },
        "sAjaxSource": "[% ajax_src %]",
        "bStateSave": false,

        "aoColumns": [
                        [% FOREACH f IN table_fields -%]
                        {
                           "mData": "[% f %]",
                           "mRender": function ( data, type, full, opt ) {
                                if(data == null)
                                    return '';
                                [% IF custom_renderers.${f} -%]
                                    var renderCustom = [% custom_renderers.${f} -%];
                                [% ELSE -%]
                                    var renderCustom = function(data, type, full, opt) { return data; };
                                [% END -%]
                                return String(renderCustom(data, type, full)).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
                            }
                        },
                        [% END -%]
                        { "mRender": function ( data, type, full, opt ) {
                                return '<input type="checkbox" value="' + full.id + '"/>';
                            },
                          "mData": null,
                          "bSortable": false
                        }
        ],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            nRow.className = "sw_action_row";
            if(checked_fields[%table_id%].indexOf($(nRow).find("td:first").text()) >= 0 )
            {
                $(nRow).find("td input[type='checkbox']").attr("checked", "checked");
            }
            return nRow;
        },
        "fnServerParams": function ( aoData ) {
            //aoData.push( {"name":"iIdOnTop","value":"[% value %]"} );
        },
        [%IF only_visible_values %]
        "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
            oSettings.jqXHR = $.ajax( {
                "dataType": 'json',
                "url": sSource,
                "data": aoData,
                "success": function(data, textStatus, jqXHR) {
                    var aadata_length = data.aaData.length;
                    var serverArray = [];
                    for (var i = 0; i < aadata_length; i++) {
                        serverArray.push(data.aaData[i].id);
                    }
                    var checked_fields_length = checked_fields[%table_id%].length;
                    for (var i = 0; i < checked_fields_length; i++) {
                        var id_checked = checked_fields[%table_id%][i];
                        var serverIndexOf = serverArray.indexOf(id_checked);
                        if ( serverIndexOf < 0 ) {
                            checked_fields[%table_id%].splice(serverIndexOf,1);
                        }
                    }
                    var server_length = serverArray.length;
                    for (var i = 0; i < server_length; i++) {
                        var id_server = serverArray[i];
                        var uncheckedIndexOf = unchecked_fields[%table_id%].indexOf(id_server);
                        var checkedIndexOf = checked_fields[%table_id%].indexOf(id_server);
                        if (uncheckedIndexOf < 0 && checkedIndexOf < 0) {
                            checked_fields[%table_id%].push(id_server);
                        }
                    }
                    update_hidden_value();
                    fnCallback(data, textStatus, jqXHR);
               }
            } );
        },
        [%END%]
        "initComplete": function(settings, json) {
            if ("[% c.loc(search_tooltip) %]".length > 0) {
                $( "#[% table_id %]_filter input" ).tooltip({
                    title: "[% c.loc(search_tooltip) %]"
                });
            }
        }
    } );

} );
</script>

<div class="control-group [% IF errors.size %]error[% END %] [%wrapper_class%]">
     <label class="control-label" for="[% table_id %]">[% label %]</label>
     <div class="controls">
         <input type="hidden" name="[% field_name %]" value="[% value | html %]" id="[% hidden_id %]"/>
         <table class="table table-bordered table-striped table-highlight table-hover" id="[% table_id %]">
            <thead>
                <tr>
                    [% FOREACH t IN table_titles %]
                        <th>[% t %]</th>
                    [% END %]
                    <th class="span"></th>
                </tr>
            </thead>
            <tbody>
                <tr class="sw_action_row">
                    <td>Loading</td>
                </tr>
            </tbody>
        </table>
        [% IF errors.size -%]
        <span class="help-inline">
            [% errors.join('<br/>') %]
        </span>
        [% END -%]
    </div>
</div>
[% # vim: set tabstop=4 syntax=html expandtab: -%]
