// ==UserScript==
// @name                Quick reply
// @version             2.0
// @date                2009-01-30
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Adds a "reply" button next to each convo on the main convo list page
// @include             http://www.etsy.com/convo_main.php*
// @include             http://www.etsy.com/convo_view.php*
// ==/UserScript==

if ( document.location.href.indexOf( 'convo_main.php' ) > -1 ) {
    // find the first row of the convo listing table
    var rows = getElementsByClassName( 'row_grey' );
    var table = rows[ 1 ].parentNode;

    // adjust the header and footer rows to accomodate the extra cell
    table.rows[ 0 ].cells[ 1 ].colSpan = 2;
    table.rows[ 1 ].cells[ 0 ].colSpan = 6;
    table.rows[ table.rows.length - 2 ].cells[ 0 ].colSpan = 5;
    table.rows[ table.rows.length - 1 ].cells[ 0 ].colSpan = 4;

    // add an extra cell to the message rows with a 'reply' button
    for ( var r = 2; r < table.rows.length - 2; r++ ) {
        var row = table.rows[ r ];
        var link = row.getElementsByTagName( 'a' )[ 1 ];
        var cell = row.insertCell( 2 );
        cell.className = 'centered_text';
        cell.style.verticalAlign = 'middle';
        cell.style.padding = '0px 0px 0px 10px';
        // pass a 'reply' parameter to the convo_view page so we know to open the reply box
        cell.innerHTML = '<a href="' + link.href + '&reply=yes">reply</a>';
    }
} else {
    var nav = getElementsByClassName( 'list_dynamic_link' )[ 0 ];
    nav.addEventListener( 'click', function () { nav.style.display = 'none'; }, false );
    // we're on a convo view page
    if ( document.location.search.indexOf( 'reply=yes' ) > -1 ) {
        var box = document.getElementById( 'reply_box' );
        // show the reply box
        box.style.display = 'block';
        nav.style.display = 'none';
        // set the focus on the textarea
        box.getElementsByTagName( 'textarea' )[ 0 ].focus();
    }
}

// utility function to replicate getElementsByClassName() on older Firefoxes
function getElementsByClassName ( class, node ) {
    if ( node == null ) node = document;
    if ( node.getElementsByClassName ) {
        return node.getElementsByClassName( class );
    } else {
        var classElements = new Array();
        var els = node.getElementsByTagName( '*' );
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+class+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    }
}


