(function()
{
    'use strict';
    var page = jQuery(document);

    var table_selector = '.table-box table';

    page.on('contentloaded', function(e)
    {
        // find all tables and then check if they are inside a valid container
        // this is done separately in case a table container is itself reloaded
        jQuery(e.target).find('table').filter(table_selector).each(function()
        {
            // duplicate column headers in title attributes of each cell

            var table = jQuery(this);

            var header_row = table.find('thead tr').first();

            var column_headings = [];

            var heading_cells = header_row.find('th');
            if (heading_cells.length < 1)
            {
                // in some tables created in the richtext editor
                // the thead row may contain td elements instead of th
                // so use that as a fallback
                heading_cells = header_row.find('td');
            }
            heading_cells.each(function()
            {
                // prepare heading text
                // html is ignored in headings, so sub/sup elements must be removed completely
                // otherwise they become simple text numbers inside the title
                var heading_node = jQuery(this).clone();
                heading_node.find('sup, sub, button').remove();

                column_headings.push( jQuery.trim( heading_node.text() ) );
            });

            table.find('tr').not(header_row).each(function()
            {
                jQuery(this).find('th, td').each(function(column_index)
                {
                    var cell = jQuery(this);

                    if (!cell.attr('title'))
                    {
                        cell.attr('title', column_headings[column_index] );
                    }
                });
            });

        });
    });

}());
