// ==UserScript==
// @name                Contact buyer
// @version             1.3
// @date                2010-09-17
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Adds the buyer's email address to the sold orders page
// @include             http://www.etsy.com/your/listings/sold*
// ==/UserScript==

// set up some styles - other hacks may also create an order notes row, but make it hidden
var style = document.createElement( 'style' );
style.type = 'text/css';
style.innerHTML = '.etsyhacks_order_notes { display: table-row !important }';
document.getElementsByTagName( 'head' )[ 0 ].appendChild( style );

// seek orders to mark up
var links = document.getElementsByTagName( 'a' );
for ( var l = 0; l < links.length; l++ ) {
    var link = links[ l ];
    if ( link.href && link.href.indexOf( '/your/orders' ) > -1 ) {
        // found an order
        var order_id = link.href.match( /\/your\/orders\/(\d+)/ )[ 1 ];
        var buyer;
        for ( var l2 = l - 1; l2 > 0; l2-- ) {
            link = links[ l2 ];
            if ( link.href && link.href.indexOf( '/people/' ) > -1 ) {
                var match = link.href.match(/people\/(.+)/);
                buyer = match[1];
                break;
            }
        }
        var notes = GM_getValue( order_id );
        var cell = document.getElementById( 'order_notes_' + order_id );
        if ( cell == null ) {
            // we don't have an order notescell set up - create one
            var node = link.parentNode;
            while ( node.className.indexOf( 'odd' ) == -1 && node.className.indexOf( 'even' ) == -1 ) node = node.parentNode;
            while ( ! node.className || node.className.indexOf( 'order-footer' ) == -1 ) node = node.nextSibling;
            var row = node.parentNode.insertRow( node.rowIndex - 1 );
            row.className = 'etsyhacks_order_notes';
            cell = row.insertCell( 0 );
            cell.colSpan = 6;
            cell.style.padding = '5px 0px 0px 10px';
            cell.style.fontSize = '11px';
            cell.style.textAlign = 'left';
            cell.className = 'dark_grey_text';
            cell.id = 'order_notes_' + order_id;
        }
        // create a holder for the notes
        var div = document.createElement( 'div' );
        div.style.marginBottom = '5px';
        // add it to the order notes cell
        cell.appendChild( div );
        if ( notes == null ) {
            notes = "<em>loading</em>";
            getNotes( order_id, div, buyer );
        }
        displayNote( div, notes, buyer, order_id );
    }
}

// request the order's receipt and call the note-extractor function on the result
// note that we explicitly pass the cookie header - Greasemonkey can forget sometimes it seems
function getNotes ( order_id, cell, buyer ) {
    GM_xmlhttpRequest( {
        url: 'http://www.etsy.com/your/orders/' + order_id,
        method: 'GET',
        headers: { Cookie: document.cookie },
        onload: genExtractMessage( order_id, cell, buyer )
    } );
}

// extract the message and fill in the field
function genExtractMessage ( order_id, cell, buyer ) {
    return function ( response ) {
        if ( response.status != 200 ) return; // hm

        // seek using a regexp; kind of ugly but easier than trying to coerce it into a DOM tree
        var lines = response.responseText.split( '\n' );
        var emailCount = 0;
        for ( var l = 0; l < lines.length; l++ ) {
            var line = lines[ l ];
            var match = line.match( /<a href.*">(.*@.*)<\/a>/ );
            if ( match ) {
                emailCount++;
                if ( emailCount == 2 ) {
                    var value = '<a href="mailto:' + match[ 1 ] + '">' + match[ 1 ] + '</a>';
                    // store the value for future use
                    GM_setValue( order_id, value );
                    // and display it
                    displayNote( cell, value, buyer, order_id );
                    return;
                }
            }
        }
    };
}    

// format and display the message
function displayNote( node, email, buyer, order_id ) {
    node.innerHTML = "<strong>Contact:</strong> " + email + ' &bull; <a href="http://www.etsy.com/convo_new.php?ref_order=' + order_id + '&to_username=' + buyer + '">send convo</a> &bull <a href="http://www.etsy.com/convo_drop_search.php?drop_user_name=' + buyer + '&drop_tag=&submit=Go">view convos</a>';
}





