[%
    IF helper.dt_columns;
        helper.column_titles = [];
        helper.column_fields = [];
        helper.column_sortable_map = {};
        helper.custom_renderers = helper.custom_renderers ? helper.custom_renderers : {};
        helper.options = {};
        helper.columns_hidden = {};
        helper.search_tooltip = c.loc('Filter records for values of columns matching either condition:') _ '<dl>';
        FOR col IN helper.dt_columns;
            IF !col.accessor;
                col.accessor = col.name;
                col.accessor = col.accessor.replace('\.','_');
            END;
            search_dt = col.title;
            UNLESS search_dt;
                search_dt = col.accessor;
            END;
            search_dd = '';
            IF col.search;
                search_dd = c.loc('Search by wildcard pattern. A wildcard is implicitly appended at the end of the search string if no wildcard is used. A leading wildcard prevents using databases indexes (slow).');
            ELSIF col.strict_search;
                search_dd = c.loc('Search by the exact search string value (The * wildcard is considered as a literal string).');
            ELSIF col.int_search;
                search_dd = c.loc('Search string is converted to an integer value to search for.');
            END;
            IF search_dd;
                helper.search_tooltip = helper.search_tooltip _ '<dt>' _ search_dt _ '</dt>';
                helper.search_tooltip = helper.search_tooltip _ '<dd>' _ search_dd _ '</dd>';
            END;
            NEXT UNLESS col.title;
            helper.column_titles.push(col.title);
            helper.column_fields.push(col.accessor);
            helper.column_sortable_map.${col.accessor} = (col.sortable.defined ? col.sortable : 1);
            helper.options.${col.accessor} = {};
            IF col.custom_renderer.defined;
                helper.custom_renderers.${col.accessor} = col.custom_renderer;
            END;
            IF col.visible.defined && !col.visible;
                helper.columns_hidden.${col.accessor} = 1;
            END;
            IF col.dont_skip_empty_data;
                helper.options.${col.accessor}.dont_skip_empty_data = 1;
            END;
        END;
        helper.search_tooltip = helper.search_tooltip _ '</dl>';
    END;
    backuri = c.req.uri;
    tmp = backuri.query_param_delete('back');
    # create unique identifier
    helper.id_from_name = helper.identifier || helper.name.remove('[\s+\.#]');
    helper.identifier = 0; # make sure we don't use the same identifier twice
    IF search_tooltip;
        helper.search_tooltip = c.loc(search_tooltip);
    END;
-%]

<script src="/js/libs/bootstrap/datatables-paging.js"></script>
<script src="/js/libs/jquery-ui-timepicker-addon.js"></script>
<script type="text/javascript">

$.extend( $.fn.dataTableExt.oStdClasses, {
                "sSortAsc": "header headerSortDown",
                "sSortDesc": "header headerSortUp",
                "sSortable": "header",
                "sWrapper": "dataTables_wrapper form-inline",
            } );

$(document).ready(function() {
    var date_search_rendered = 0;
    var custom_search_filter_rendered = 0;
    var [% helper.id_from_name %]_tmp_footer;
    var [% helper.id_from_name %]_table = $('#[% helper.id_from_name %]_table')
        .dataTable( {
        "sDom": "<'row-fluid ngcp_dt_top_elements'lf<r>>t<'row-fluid'<'pull-left'i><'pull-right'p>>",
        "bProcessing": true,
        "bPaginate": [% helper.paginate || 'true' %],
        "bFilter": [% helper.filter || 'true' %],
        "bStateSave": [% IF helper.name == "Calls" %]false[% ELSE %]true[% END %],
        "iStateDuration": 0,

        "sPaginationType": "bootstrap",
        [% IF helper.length_change ;
            sLabelAll=c.loc('All');
            aDefaultPager='[[ 5, 10, 15, 20, 35, 50, 100, 250, -1], [5, 10, 15, 20, 35, 50, 100, 250, "' _ sLabelAll _ '"]]'
        -%]
            "bLengthChange": true,
            "aLengthMenu":  [% helper.length_menu || aDefaultPager %],
        [% ELSE %]
            "bLengthChange": false,
        [% END %]
        "bSort": [% IF helper.no_sort %] false [% ELSE %] true [% END %],
        "bInfo": true,
        "iDisplayLength": 5,
        "iShowPages": 5,
        "sAjaxSource": "[% helper.ajax_uri %]",
        "searchDelay": 800,
        [% IF helper.column_sort -%]
            "aaSorting": [
            [%
                FOR f IN helper.column_fields;
                    IF helper.column_sort == f;
            -%]
                [
                    [% loop.index %],
                    '[% helper.column_sort_order || "asc" %]'
                ],
            [%
                    END;
                END;
            -%]
            ],
        [% END -%]
        "oLanguage": {
            "sUrl": "/js/i18n/[% c.loc('dataTables.default.js') %]"
        },
        "aoColumns": [
            [% FOREACH f IN helper.column_fields -%]
            {
                "mData": "[% f %]",
                [%IF helper.columns_hidden.${f} %]
                "visible": false,
                "className": 'hidden',
                "hidden": true,
                [%END%]
                "mRender": function ( data, type, full, opt ) {
                    [% IF !helper.options.${f}.dont_skip_empty_data %]
                    if(data == null)
                      return '';
                    [% ELSE %]
                    if(data == null)
                      data = '';
                    [% END %]
                    if (opt == null || typeof opt !== 'object') {
                        opt = {};
                    }
                    opt.escapeHtml = true; // always escape HTML by default
                    [% IF helper.custom_renderers.${f} -%]
                        var renderCustom = [% helper.custom_renderers.${f} -%];
                    [% ELSE -%]
                        var renderCustom = function(data, type, full, opt) { return data; };
                    [% END -%]
                    var str = String(renderCustom(data, type, full, opt));
                    if (opt.escapeHtml) {
                        return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');//"
                    }
                    return str;
                },
                "bSortable": [% IF helper.column_sortable_map.${f} %] true [% ELSE %] false [% END %]
            },
            [% END -%]
            {   "mRender": function ( data, type, full, opt ) {
                    var html = '' +
                    '<div class="sw_actions pull-right">';
                    [%
                        backuri = backuri | uri;
                        FOR button IN helper.dt_buttons;
                            separator = '?';
                            confirm_delete = button.name == c.loc("Delete") ? 'data-confirm="' _ c.loc("Delete") _ '"' : '';
                            confirm_delete = button.name == c.loc("Terminate") ? 'data-confirm="' _ c.loc("Terminate") _ '"' : confirm_delete;
                            IF button.uri.search('\?');
                                separator = '&';
                            END;
                            IF !( button.no_back or button.uri.search('[\?\&]back=|^javascript:') );
                                button.uri = button.uri _ separator _ 'back=' _ backuri;
                            END;
                            IF button.condition;
                    -%]
                                if([% button.condition %]) {
                    [%
                            END;
                    -%]
                        html +=
                           '<a class="btn [% button.class %]" href="[% button.uri %]" [% confirm_delete %][%IF button.onclick -%] onclick="[%button.onclick%]"[%END%][%IF button.tooltip -%] rel="tooltip" data-original-title="[%button.tooltip%]"[%END%] [% button.attributes %]>' +
                              '<i class="[% button.icon %]"></i> [% button.name %]' +
                            '</a>';

                    [%
                            IF button.condition;
                    -%]
                        }
                    [%
                            END;
                        END;
                    -%]
                    html += '</div>';
                    return html;
                },
                "mData": null,
                "bSortable": false,
                "sClass": "ngcp-actions-column"
            }
        ],
        [%IF !helper.data_static %]
        "bServerSide": true,
        "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
            oSettings.jqXHR = $.ajax( {
                "dataType": 'json',
                "url": sSource,
                "data": aoData,
                "success": function(data, textStatus, jqXHR) {
                   if (data.dt_custom_footer) {
                       [% helper.id_from_name %]_tmp_footer = data.dt_custom_footer;
                   }
                   fnCallback(data, textStatus, jqXHR);
               }
            } );
        },
        "fnServerParams": function ( aoData ) {
            var params = localStorage.getItem("ngcp_dt.[%helper.id_from_name%]_table.paramsJSON");
            if(params){
                var paramsParsed = JSON.parse(params);
                for(var key in paramsParsed){
                    aoData.push( {"name":key,"value":paramsParsed[key]} );
                }
            }
        },
        [%ELSE%]
        "bServerSide": false,
        [%END%]
        [% IF helper.show_footer -%]
        "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) {
            if ([% helper.id_from_name %]_tmp_footer) {
                nFoot.getElementsByTagName('td')[0].innerHTML = '[% c.loc("Total") %]';
                for (var col in [% helper.id_from_name %]_tmp_footer) {
                    if ([% helper.id_from_name %]_tmp_footer.hasOwnProperty(col)) {
                        nFoot.getElementsByClassName('footer-'+col)[0].innerHTML = [% helper.id_from_name %]_tmp_footer[col];
                    }
                }
            }
        },
        [% END -%]
        "fnDrawCallback": function( oSettings ) {
                $('.sw_actions').css('visibility','hidden');
                $('.sw_action_row').mouseover(
                    function() { $(this).find('.sw_actions').css('visibility','visible'); },
                );
                $('.sw_action_row').mouseout(
                    function() { $(this).find('.sw_actions').css('visibility','hidden'); },
                );
                if ($('.sw_actions').find("[rel=tooltip]").length) {
                    $('.sw_actions').find("[rel=tooltip]").tooltip();
                }

                if (!custom_search_filter_rendered) {
                    custom_search_filter_rendered = 1;
                    [% IF helper.custom_filter -%]
                        var f = '[% helper.custom_filter.replace( "'", "\\'" ).replace("\n", "") %]';
                        $('#[% helper.id_from_name %]_table_filter').prepend(f);
                    [% END -%]
                }
                if(!date_search_rendered) {
                    date_search_rendered = 1;
                    [% has_from = 0; has_to = 0; -%]
                    [% FOR col IN helper.dt_columns -%]
                        [% IF col.search_from_epoch && !has_from -%]
                            var f = '<label>[% c.loc('From Date') %]: <input type="text" id="[% helper.id_from_name %]_datepicker_start" class="ngcp-datepicker" rel="tooltip" data-original-title="[% c.loc('YYYY-MM-DD') %]"/></label>';
                            $('#[% helper.id_from_name %]_table_filter').prepend(f);
                            $('#[% helper.id_from_name %]_datepicker_start').datetimepicker({
                                "dateFormat": "yy-mm-dd",
                                showTimepicker: [% IF col.search_datetime %] true [% ELSE %] false [% END %],
                                "onSelect": function(date) {
                                    [% helper.id_from_name %]_table.fnFilter(date, 0);
                                }
                            }).keyup( function () {
                                [% helper.id_from_name %]_table.fnFilter(this.value, 0);
                            });
                            [% has_from = 1 -%]
                        [% END -%]
                        [% IF col.search_to_epoch && !has_to -%]
                            var t = '<label>[% c.loc('To Date') %]: <input type="text" id="[% helper.id_from_name %]_datepicker_end" class="ngcp-datepicker" rel="tooltip" data-original-title="[% c.loc('YYYY-MM-DD') %]"/></label>';
                            if($('#[% helper.id_from_name %]_datepicker_start').length > 0) {
                                $('#[% helper.id_from_name %]_datepicker_start').parent().after(t);
                            } else {
                                $('#[% helper.id_from_name %]_table_filter').prepend(t);
                            }
                            $('#[% helper.id_from_name %]_datepicker_end').datetimepicker({
                                "dateFormat": "yy-mm-dd",
                                showTimepicker: [% IF col.search_datetime %] true [% ELSE %] false [% END %],
                                "onSelect": function(date) {
                                    [% helper.id_from_name %]_table.fnFilter(date, 1);
                                }
                            }).keyup( function () {
                                [% helper.id_from_name %]_table.fnFilter(this.value, 1);
                            });
                            [% has_to = 1-%]
                        [% END -%]
                    [% END %]
                }
        },
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            nRow.className = "sw_action_row";
            return nRow;
        },
        "initComplete": function(settings, json) {
            if ("[% helper.search_tooltip %]".length > 0) {
                $( "#[% helper.id_from_name %]_table_filter input" ).tooltip({
                    title: "[% helper.search_tooltip %]",
                    html: true,
                    placement: 'bottom'
                });
            }
        }
    } );

} );
</script>

[% IF (!back_created) || helper.top_buttons.size -%]
    <div class="row">
        [% UNLESS back_created || framed -%]
        <span class="pull-left" style="margin:0 5px 0 5px;">
            <a class="btn btn-primary btn-large" href="[% c.uri_for('/back') %]"><i class="icon-arrow-left"></i> [% c.loc("Back") %]</a>
        </span>
        [% back_created = 1 -%]
        [% END -%]
        [% FOR button IN helper.top_buttons -%]
            [% IF button.method == "post" -%]
                <form method="post" action="[% button.uri %]" style="float:left; margin:0 5px 0 5px;">
                    <button class="btn btn-primary btn-large" style="height:47px;"><i class="[% button.icon %]"></i> [% button.name %]</button>
                    <input type="hidden" name="back" value="[% c.req.uri %]"/>
                </form>
            [% ELSE -%]
                <span class="pull-left" style="margin:0 5px 0 5px;">
                    [% IF button.accordion_button == 1 && loop.count == 1 -%]
                    <a class="btn btn-primary btn-large" href="[% button.uri %]" style="margin-left:25px;"><i class="[% button.icon %]"></i> [% button.name %]</a>
                    [% ELSE -%]
                    <a class="btn btn-primary btn-large" href="[% button.uri %]"><i class="[% button.icon %]"></i> [% button.name %]</a>
                    [% END -%]
                </span>
            [% END -%]
        [% END -%]
    </div>
[% END -%]

[% IF helper.messages -%]
<div class="row">
    [% FOREACH m IN helper.messages -%]
        <div class="alert alert-[% m.type %]">[% m.text %]</div>
    [% END -%]
</div>
[% END -%]

<div class="ngcp-separator"></div>

<table class="table table-bordered table-striped table-highlight table-hover ngcp-datatable" id="[% helper.id_from_name %]_table" width="100%">
    <thead>
        <tr>
            [% FOREACH t IN helper.column_titles -%]
            <th>[% t %]</th>
            [% END -%]
            [% # one for actions -%]
            <th class="ngcp-actions-column"></th>
        </tr>
    </thead>
    [% IF helper.show_footer -%]
    <tfoot>
        <tr>
            [% FOREACH f IN helper.column_fields -%]
            <td class="footer-[% f %]"></td>
            [% END -%]
            <td></td>
        </tr>
    </tfoot>
    [% END -%]
    <tbody>
        <tr class="sw_action_row">
            <td colspan="[% helper.column_titles.size + 1 %]">[% c.loc('Loading...') %]</td>
        </tr>
    </tbody>
</table>

[% IF helper.edit_flag || helper.create_flag == 1 -%]
[%
    IF helper.form_object.has_for_js;
        helper.form_object.render_repeatable_js;
    END;
    PROCESS "helpers/modal.tt";
    modal_header(m.create_flag=helper.create_flag,
                 m.duplicate_flag=helper.duplicate_flag,
                 m.edit_flag=helper.edit_flag,
                 m.name = helper.name);
        helper.form_object.render;
    modal_footer();
    modal_script(m.close_target = helper.close_target);
-%]
[% END -%]
[%  # cleanup
    helper.show_footer = 0;
 -%]
[% # vim: set tabstop=4 syntax=html expandtab: -%]
