// David Stanek
// dstanek@dstanek.com
// www.traceback.org
//
// ==UserScript==
// @name DDJ Podcast Download Fix
// @description A Fix for the DDJ podcast download button
// @namespace http://www.python-industries.com/userscripts/
// @include http://www.ddj.com/*
// ==/UserScript==

/** Simplification of Firefox's built in evaluate function.

 From the examples at http://diveintogreasemonkey.org
*/
function xpath(query) {
    return document.evaluate(query, document, null,
        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
}

/** Rewrite the button link to actually work. */
function rewriteLink() {
    var inputs = xpath("//input[@value='download this podcast']");
    for (var i = 0; i < inputs.snapshotLength; i++) {
        var input = inputs.snapshotItem(i);
        input.addEventListener('click', function(event) {
            var w = unsafeWindow;
            var url = "http://www.dobbsprojects.com" +
                "/media/newengine/dynamp.php/" + w.podcast +
                "?site=" + escape(w.site) +
                "&affiliate=" + escape(w.affiliate) +
                "&target=" + escape(w.target) +
                "&title=" + escape(w.title) +
                "&artist=" + escape(w.artist) +
                "&album=" + escape(w.album) +
                "&comment=" + escape(w.comment) +
                "&podcast=" + escape(w.podcast);
            window.location.href = url;

            event.stopPropagation();
            event.preventDefault();
        }, true);
    }
}

/* Fire away */
window.addEventListener('load', rewriteLink, true);
