// ==UserScript==
// @name           Address reformatter
// @version        1.0
// @date           2009-05-26
// @author         Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace      etsy.com
// @description    Alter addresses on Etsy receipts to make them easier to cut-and-paste
// @include        http://www.etsy.com/receipt.php?order_id=*
// ==/UserScript==

// Local country command
GM_registerMenuCommand( 'Set local country', setLocalCountry );

// Find the address
var titles = getElementsByClassName( 'orange_text' );
for ( var t = titles.length - 1; t > 0; t-- ) {
    if ( titles[ t ].innerHTML.indexOf( 'Ship to' ) > -1 ) {
        // found it
        var localCountry = GM_getValue( 'localCountry' ) || '';
        // find the parent row
        var tr = titles[ t ];
        while ( tr.nodeName != 'TR' ) tr = tr.parentNode;
        tr = tr.parentNode;
        while ( tr.nodeName != 'TR' ) tr = tr.parentNode;
        // then navigate to the actual address row
        var row = tr.parentNode.rows[ tr.rowIndex + 2 ];
        // and modify the address
        var addr = row.getElementsByTagName( 'br' )[ 0 ].parentNode;
        addr.innerHTML = addr.innerHTML.replace( /\((.*)\)/, function () { return ( arguments[ 1 ] == localCountry ) ? '' : '<br />' + arguments[ 1 ] } );
        // all done
        break;
    }
}

// optionally set a "home country" to ignore
function setLocalCountry () {
    var localCountry = GM_getValue( 'localCountry' ) || '';
    var country = prompt( 'Local country', localCountry );
    if( country != null ) {
        GM_setValue( 'localCountry', country );
    }
}

// utility function to replicate getElementsByClassName() on older Firefoxes
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;
    }
}

