// ==UserScript==
// @name                Section counter
// @version             1.1
// @date                2009-01-30
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Adds a "no section" row to the sections table to make it easy to see if you have uncategorised items
// @include             http://www.etsy.com/sections.php*
// ==/UserScript==

// two "grey_border" tables - the first holds the section tab, the second the "all items" table
var gb = getElementsByClassName( 'grey_border' );

// find the total number of items for sale
var total = gb[ 1 ].getElementsByTagName( 'span' )[ 0 ].innerHTML;
total = Number( total.substr( 0, total.length - 6 ) );

// add up the total number of items in sections
var sections = gb[ 0 ];
var count = 0;
for ( var r = 0; r < sections.rows.length; r++ ) {
    count += Number( sections.rows[ r ].cells[ 1 ].innerHTML );
}

// if we have any sections, then add a "no section" row at the bottom
if ( sections.rows.length ) {
    var totalRow = sections.rows[ sections.rows.length - 1 ].cloneNode( true );
    totalRow.className = ( totalRow.className == 'row_light_grey' ) ? 'row_white' : 'row_light_grey';
    totalRow.cells[ 0 ].innerHTML = 'No section';
    totalRow.cells[ 1 ].innerHTML = total - count;
    totalRow.cells[ 2 ].innerHTML = '&nbsp;';
    totalRow.cells[ 3 ].innerHTML = '&nbsp;';
    sections.rows[ 0 ].parentNode.appendChild( totalRow );
}

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


