// ==UserScript==
// @name           Relist item
// @namespace      etsy.com
// @include        http://www.etsy.com/sold_orders.php*
// @description    Adds a link to relist a sold item from the Sold Orders page
// @version        1.0
// @date           2009-06-02
// @author         Ian Malpass ( ian AT etsyhacks DOT com )
// ==/UserScript==

// The orders have class names of row_grey and row_white
// Find the first row_grey and work up to its parent table node
var ordersTable = getElementsByClassName( 'row_grey' )[0].parentNode.parentNode;

// First (zeroth) row is the header row
// Work through the rest finding the transactions
for ( var r = 1; r < ordersTable.rows.length; r++ ) {
    var items =  ordersTable.rows[ r ].getElementsByTagName( 'table' );    
    // Every forth table contains the text links we're going to add to
    for ( var c = 1; c < items.length - 3; c += 4 ) {
        var links = items[ c ].getElementsByTagName( 'a' );
        var transaction = links[ 1 ].href.substring( links[ 0 ].href.indexOf( '=' ) + 1 );
        var row = links[ 1 ].parentNode.parentNode;
        // Append an extra row to the table for the cancel link
        var cancelRow = row.cloneNode( 1 );
        row.parentNode.appendChild( cancelRow );
        cancelRow.cells[ 0 ].innerHTML = '&bull; <a href="http://www.etsy.com/relist_listing.php?transaction_id=' + transaction + '">relist item</a>';
    }
}

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;
    }
}

