/* ===================================================================================================
* WARNING – This file is part of the base implementation for WebMaker, so it should not be edited or changed for any project. 
* These files are replaced if a project is re-imported to the WebMaker Studio or migrated to a new version of the product. 
* For guidance on ‘How do I override or clone Hyfinity webapp files such as CSS & javascript?’, please read the following relevant FAQ entry: 
* http://www.hyfinity.net/faq/index.php?solution_id=1113
==================================================================================================== */

if (typeof(hyf) == 'undefined')
{
    hyf = {
        version: 1.0
    }
}

hyf.pagingtable = {
    version: 1.0,
    desc: 'Provides for client side sorting and paging of an HTML table'
}


/**
 * Initialises the provided table to be sortable and provide paging capability
 * this currently uses the jQuery tablesorter control
 * @param table The HTML table object to convert
 * @param options Configuration options for the table.  This object can contain the following properties:
 *              enablePaging - boolean value indicating whether the table should provide paging as well as
 *                             sorting capabilities. (default true)
 *              pageSize     - If provided this fixes the number of records displayed on a page.  If not provided
 *                             a dropdown will be shown to allow the user to customize this.
 *              pageControlsCss - The CSS class name that should be applied to the HTML component containing
 *                             the paging controls.
 *              headerCss    - The CSS class name to apply to all the header rows in the table to indicate
 *                             that they can be sorted.
 *              headerAscCss - The CSS class name to apply to a header cell to indicate that the column is sorted ascending
 *              headerDescCss- The CSS class name to apply to a header cell to indicate that the column is sorted descending
 *              stripeRows   - Boolean indicating whether different styles should be applied to alternate
 *                             rows in the table. (default true)
 *              firstRowCss  - The first CSS class name to apply to the rows of the table to provide alternate shading.
 *              secondRowCss - The second CSS class name to apply to the rows of the table to provide alternate shading.
 */
hyf.pagingtable.init = function(table, options)
{
    var defaults = {
            enablePaging: true,
            pageSize: null,
            pagerControlsCss: 'tablesorterPager',
            headerCss: 'header',
            headerAscCss: 'headerSortUp',
            headerDescCss: 'headerSortDown',
            stripeRows: true,
            firstRowCss: 'firstRow',
            secondRowCss: 'alternateRow'
        }

    if (typeof(options) != 'undefined')
        dojo.mixin(defaults, options);

    //check jquery initialised
    if (typeof($) == 'function')
    {
        //need to actually initialise the paging table on load to make sure that our custom attributes are successfully
        //added to all the fields.  The table removes non visible rows from the HTML so prevents these from being added.
        if (hyf.pageLoaded)
            hyf.pagingtable.initImpl(table, defaults);
        else
            hyf.attachEventHandler(window, 'onload', function() {hyf.pagingtable.initImpl(table, defaults);});
    }
}

/**
 * This fucntion actually performs the table initialisation, and should be called when
 * all the needed startup stuff has already happened
 * @param table The HTML table to convert
 * @param defaults The set of options for this table.  This should be a combination of the defautls,
 * and the user provided options.
 * @private - call hyf.pagingtable.init instead.
 */
hyf.pagingtable.initImpl = function(table, defaults)
{
    dojo.addClass(table, 'tablesorter');

    var tableSortOptions = {
            widthFixed: true,
            cssHeader: defaults.headerCss,
            cssAsc: defaults.headerAscCss,
            cssDesc: defaults.headerDescCss,
            textExtraction: hyf.pagingtable.textExtractor
        }

    if (defaults.stripeRows)
    {
        tableSortOptions.widgets = ['zebra'];
        tableSortOptions.widgetZebra =  {css: [defaults.firstRowCss, defaults.secondRowCss]};
    }

    //initialise the sorting
    $(table).tablesorter(tableSortOptions);

    if (defaults.enablePaging)
    {
        //create a div container to store the paging controls
        var pc = document.createElement('div');
        var pcid = table.getAttribute('id') + '_pager';
        pc.className = defaults.pagerControlsCss;
        pc.setAttribute('id', pcid);

        //create the paging controls
        var pcHTML = '<span class="first" title="first page"></span><span class="prev" title="Previous page"></span>';
        pcHTML += '<input class="pagedisplay"/>';
        pcHTML += '<span class="next" title="next page"></span><span class="last" title="last page"></span>';
        if (defaults.pageSize != null)
            pcHTML += '<input type="hidden" class="pagesize" value="' + defaults.pageSize + '"/>'
        else
            pcHTML += '<select class="pagesize"><option selected="selected" value="10">10</option><option value="20">20</option><option value="30">30</option><option  value="40">40</option></select>';

        pc.innerHTML = pcHTML;

        table.parentNode.appendChild(pc);

        //initilise the paging
        $(table).tablesorterPager({
                container: $(pc),
                positionFixed: false
            });

        //call the change function on the page size to ensure the table is rendered correctly initially
        $('.pagesize', pc).change();
    }
}

/**
 * The function that is used to get the value out of a table cell.
 * This should handle cells that contain editable fields.
 */
hyf.pagingtable.textExtractor = function(node)
{
    if ($(node).find(':input').length > 0)
    {
        return $(node).find(':input')[0].value;
    }
    else
    {
        if (typeof(node.textContent) != 'undefined')
            return node.textContent;
        else
            return node.innerText;
    }
}

/**
 * Finds the last table object that has been output to the document.
 * This is used as the page is being rendered to initialise any ediatbale tables
 * This is an exact copy of the same function in the editabletable script
 * so should be combined at some point.
 */
hyf.pagingtable.getLastTableOutput = function()
{
    var elem = document.lastChild;
    while (elem.lastChild != null)
    {
        elem = elem.lastChild;
    }
    if (elem.nodeType != 1)
    {
        var prevElem = hyf.util.getPreviousElementSibling(elem);
        if (prevElem == null)
        {
            elem = elem.parentNode;
        }
        else
        {
            elem = prevElem;
        }
    }
    return elem.parentNode.getElementsByTagName('table')[0];
}