// ==UserScript==
// @name                Buyer notes
// @version             2.2
// @date                2010-04-14
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Adds the "notes from buyer" 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 );

var colour = GM_getValue( 'noteColour' );
if ( colour == null ) GM_setValue( 'noteColour', 'red' );

GM_registerMenuCommand( 'Set buyer note colour', setColour );

// 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( '/receipt.php' ) > -1 ) {
        // found an order
        var order_id = link.href.match( /order_id=(\d+)/ )[ 1 ];
        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;
            if ( node.className.indexOf( 'receipt-group' ) > -1 ) {
                nodeIdx = node.rowIndex + 1;
                while ( nodeIdx < node.parentNode.rows.length && node.parentNode.rows[ nodeIdx ].cells.length < 6 ) nodeIdx++;
                node = node.parentNode.rows[ nodeIdx - 1 ];
            }
            var row = node.parentNode.insertRow( node.rowIndex );
            row.className = 'etsyhacks_order_notes ' + node.className;
            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 );
        }
        displayNote( div, notes );
    }
}

// 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 ) {
    GM_xmlhttpRequest( {
        url: 'http://www.etsy.com/receipt.php?order_id=' + order_id,
        method: 'GET',
        headers: { Cookie: document.cookie },
        onload: genExtractMessage( order_id, cell )
    } );
}

// extract the message and fill in the field
function genExtractMessage ( order_id, cell ) {
    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' );
        for ( var l = lines.length - 1; l > 0; l-- ) {
            var line = lines[ l ];
            if ( line.indexOf( 'Message from the buyer:</td>' ) > -1 ) {
                // found the message  area, extract the message
                l += 3;
                var str = "";
                line = lines[ l ];
                while ( ! line.match( /<\/td>/ ) ) {
                    str += line;
                    l++;
                    line = lines[ l ];
                }
                str += line;
                str = str.replace( '<td>', '' );
                str = str.replace( '</td>', '' );
                // store the value for future use
                GM_setValue( order_id, str );
                // and display it
                displayNote( cell, str );
                return;
            }
        }
    };
}    

// format and display the message
function displayNote( node, text ) {
    if ( text != "None" ) {
        var colour = GM_getValue( 'noteColour' );
        if ( colour != "" ) {
            text = '<span style="color: ' + colour + '">' + text + '</span>';
        }
    }
    node.innerHTML = "<strong>Notes from buyer:</strong> " + text;
}

function setColour () {
    var prevColour = GM_getValue( 'noteColour' );
    var colour = prompt( "What colour would you like the Notes From Buyer to be?", prevColour );
    GM_setValue( 'noteColour', colour );
    if ( prevColour != colour ) {
        location.reload();
    }
}



