// ==UserScript==
// @name                Edit This Item
// @version             1.0
// @date                2008-11-05
// @author              Ian Malpass ( ian AT etsyhacks DOT com )
// @namespace           etsy.com
// @description         Adds links to edit and delete the item when viewing an item in your shop
// @include             http://www.etsy.com/view_listing.php*
// ==/UserScript==

/*
This script will first check to see if you're viewing an item in your own shop. If you are, then it adds links to
edit and delete the item to the right-hand panel, under the "report to Etsy" link.
*/

var links = document.getElementsByTagName( 'a' );
var shopPattern = /shop.php\?user_id=(\d+)/; // find shop links

var yourShop; // what's your shop ID?
var thisShop; // what's the current shop's ID?

var l = 0;
for ( 1; l < links.length; l++ ) {
    var link = links[ l ];
    if ( link.href ) {
        var match = shopPattern.exec( link.href );
        if ( match ) {
            // we have a shop link
            if ( link.title == 'Your Shop' ) {
                // this is the link to your shop in the top nav bar
                yourShop = match[ 1 ];
            } else if ( link.firstChild && link.firstChild.data && link.firstChild.data == 'shop' ) {
                // this is the link to the shop in the "seller info" box
                thisShop = match[ 1 ];
                // if we find this, we're done
                break;
            }
        }
    }
}

if ( yourShop == thisShop ) {
    // it's our item
    // find the listing ID
    var match = window.location.search.match( /listing_id=(\d+)/ );
    var listing_id = match[ 1 ];

    // create the "edit item" link
    var editLink = document.createElement( 'a' );
    editLink.innerHTML = 'Edit this item';
    editLink.href = '/reactivate_listing.php?listing_id=' + listing_id;

    // create the "delete item" link
    var deleteLink = document.createElement( 'a' );
    deleteLink.innerHTML = 'Delete this item';
    deleteLink.href = '/listing_remove.php?delete_listing_id=' + listing_id;

    // search for the "report to Etsy" link
    for ( 1; l < links.length; l++ ) {
        var link = links[ l ];
        if ( link.firstChild && link.firstChild.data && link.firstChild.data == 'Report this item to Etsy' ) {
            // found it - append the edit and delete links to that cell
            link.parentNode.appendChild( document.createElement( 'br' ) );
            link.parentNode.appendChild( editLink );
            link.parentNode.appendChild( document.createElement( 'br' ) );
            link.parentNode.appendChild( deleteLink );
            break;
        }
    }
}

