// ==UserScript==
// @name                Etsy convo linker
// @version             1.0
// @date                2008-10-22
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Turns the text "listing #..." or "transaction #..." on a convo page into a link to that listing or transaction
// @include             http://www.etsy.com/convo_view.php?convo_id=*
// ==/UserScript==

/*
If a customer uses the "contact the seller" link on one of your listing or transaction
pages, the subject line includes the text "listing #..." or "transaction #...", but it's
not easy to get to the corresponding page for that listing.

This Greasemonkey script runs on an Etsy "convo" page, and turns the text
"listing #..." or "transaction #..." into a web link to the listing or
transaction.
*/

// the whole convo is in a table with class "dark_grey_border"
// so we limit the search to that table to speed things up a bit
var tables = document.getElementsByClassName( 'dark_grey_border' );

// should be one and only one such table
var table = tables[ 0 ];

// call the recursive function 'decorate' to find the text we want and turn it into a link
decorate( table );


function decorate ( node ) {

    // loop through the node's child nodes
    for ( var c in node.childNodes ) {

        var child = node.childNodes[ c ];
        if ( child.nodeType == 3 ) {

            // nodeType 3 is a text node, which is what we're looking for
            var match = child.data.match( /(.*)(listing|transaction) #([0-9]+)(.*)/i );
            if ( match ) {

                // create and configure the link node
                var link = document.createElement( 'a' );
                link.href = 'view_' + match[ 2 ] + '.php?' + match[ 2 ] + '_id=' + match[ 3 ];
                link.target = '_blank';
                link.appendChild( document.createTextNode( match[ 2 ] + ' #' + match[ 3 ] ) );

                // build a set of nodes to replace the text node
                var fragment = document.createDocumentFragment();
                fragment.appendChild( document.createTextNode( match[ 1 ] ) ); // text before the link, if any
                fragment.appendChild( link );                                  // link
                fragment.appendChild( document.createTextNode( match[ 4 ] ) ); // text after the link, if any
                node.replaceChild( fragment, child ); // do the replacement

            }

        } else if ( child.nodeType == 1 ) {

            // nodeType 1 is an element node - check it for more text nodes
            decorate( child );

        }
    }
}
