// ==UserScript==
// @name           Order convo enhancer
// @version        1.0
// @date           2009-05-30
// @author         Ian Malpass ( ian AT etsyhacks DOT com )
// @description    Add order ID number and receipt link to convos about orders
// @namespace      etsy.com
// @include        http://www.etsy.com/convo_new.php?*
// ==/UserScript==

if ( document.referrer ) {
    // we have a referrer - check to see if it was the receipt page
    var match = document.referrer.match( /receipt.php\?.*order_id=(\d+)/ );
    if ( match ) {
        // came from the receipt page - assume it's about that order
        var order_id = match[ 1 ];
        // search the page's inputs for the subject input
        // (in the absence of named forms, this cope's better with the possibility of 
        // a variable number of forms on the page
        var inputs = document.getElementsByTagName( 'input' );
        for ( var i = inputs.length -1; i >= 0; i-- ) {
            if ( inputs[ i ].name == 'subject' ) {
                // found the subject - add our text
                inputs[ i ].value = 'Etsy order #' + order_id;
                // find the message textarea and add the link
                var message = inputs[ i ].form.elements.namedItem( 'message_text' );
                message.value = '\n\nOrder: http://www.etsy.com/receipt.php?order_id=' + order_id
                // done
                break;
            }
        }
    }
}
