/* Script to make it easy to find posts by particular author on a myBB based
 * forum thread. Collapses posts by other authors which can be expanded if
 * needed by clicking the respective footer.
 *
 * Will work with themes that display post metadata to the left of the post
 * by using a single table. If the theme displays post metadata above the post
 * or uses a div + nested table layout, this won't work.
 *
 * Test page:
 *      http://www.gfx-depot.com/forum/throw-something-at-the-person-above-you-t-1003.html
 *
 * Will not work for:
 *  (div + nested table) http://forums.redlinemotive.com/thread-442-page-1.html
 *  (metadata on top) http://forum.runbb.com/mypurebb-mybb-theme-and-template-development-downloads-t-21.html
 *
 *  Author: Abhijeet Maharana
 *  URL: http://abhijeetmaharana.com
 *  Date: 01-May-2010
 *
 * Modifies jQuerify bookmarklet by Karl Swedberg at http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
 */

(function() {

    // check if we have been run successfully on this page before
    if(window.hasForumPostCollapserRun)
    {
        var message = 'You can run this script only once per page.\n';
        message += 'Reload the page to run it again.';
        alert(message);
        
        return;
    }
    
    if(typeof jQuery!='undefined') {
        window.hasForumPostCollapserRun = startScript();
        return;
    }
    
    // more or less stolen from jquery core and adapted by paul irish
    function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
        done=false;
        // Attach handlers for all browsers
        script.onload=script.onreadystatechange = function(){
            if ( !done && (!this.readyState
                || this.readyState == 'loaded'
                || this.readyState == 'complete') ) {
                done=true;
                success();
            }
        };
        head.appendChild(script);
    }

    getScript('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',function() {
        if (typeof jQuery == 'undefined') {
            alert('A required library could not be loaded. Script terminated.');
        } else {
            window.hasForumPostCollapserRun = startScript();
        }
    });

    // http://www.codetoad.com/javascript_get_selected_text.asp
    function getSelectedText()
    {
        var txt = '';
        if (window.getSelection)
            txt = window.getSelection();
        else if (document.getSelection)
            txt = document.getSelection();
        else if (document.selection)
            txt = document.selection.createRange().text;
        return String(txt);
    }

    // http://www.whadiz.com/what-is.aspx/programming/javascript/javascript-trim
    String.prototype.trim = function()
    {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };

    // This is where we insert our functionality
    function startScript() {
        var author = getSelectedText();
        if(author == '')
            author = prompt('Screen name?');
        
        if(author == null || author == '')
            return false;

        author = author.trim().toLowerCase();

        // get hold of all posts on page
        var postRows = jQuery('div#container div#content table:first')  // get post table
        .children() // get tbody
        .children() // get trs
        .not('tr:has(td.trow_sep)') // remove post separators
        .not(':odd')    // remove post footer that has links
        .slice(1,-1);   // remove header and footer

        // Start: Check if user has any posts on this page
        var numPostsByAuthor = jQuery('td:first a[href^=member.php]', postRows).map(
            function(){
                if(jQuery(this).text().toLowerCase() == author)
                    return true;
                else
                    return null;
            }
        ).size();

        if(numPostsByAuthor == 0)
        {
            alert('There are no posts by \'' + author + '\' on this page.');
            return false;
        }
        // End: Check if user has any posts on this page

        // Hide posts by other users and modify footers so that they can be
        // clicked to show the hidden posts
        postRows.each(function(){
            var postAuthor = jQuery('td:first a[href^=member.php]',this).text().toLowerCase();
            if(author != postAuthor)
            {
                var currRow = jQuery(this);
                var nextRow = currRow.next();

                currRow.hide();
                var nextClass = nextRow.find('td:first').attr('class');

                var nextRowCol1 = jQuery('<td class=\'' + nextClass + ' smalltext\'>' + postAuthor + '</td>');
                var nextRowCol2 = jQuery('<td class=\'' + nextClass + '\'>[+]</td>');
                nextRow.html('');
                nextRow.append(nextRowCol1, nextRowCol2);
                nextRow.css('cursor','pointer');

                nextRow.toggle(function(){
                    currRow.show();
                    nextRow.css('font-weight','bold');
                    nextRowCol2.html('[-]');
                }, function(){
                    currRow.hide();
                    nextRowCol2.html('[+]');
                });
            }
        });

        return true;
    }
})();
